feat(f6): diff-view toggle on any file — global storage, untitled in-memory (#19)

F6 no longer requires a workspace file. It gets its own diffable predicate
(any file: or untitled:) decoupled from F2 isTracked, keys baselines by a
sha256 of the document URI, and stores them in VS Code GLOBAL storage
(context.globalStorageUri) — always present, never the repo (INV-19). Untitled
buffers have no durable identity → in-memory baseline only (lost on reload).

DiffViewController is now constructed before the workspace-root check and its
commands are always live (never stubbed) — the machine-landing advance wiring
stays in the with-root branch since the seam only fires on workspace files.
BaselineStore generalized to key-by-hash (Baseline.docPath → uri).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Ben Stull
2026-06-11 07:47:05 -07:00
parent 9e7ef4e052
commit e617f504e7
4 changed files with 144 additions and 119 deletions
+85 -79
View File
@@ -1,14 +1,21 @@
/**
* DiffViewController — F6 diff-view toggle (spec §6.2/§6.4). Owns the baseline
* lifecycle (initialize at first track / advance at every machine landing / pin
* lifecycle (initialize at first sight / advance at every machine landing / pin
* on demand), serves the baseline as a readonly `cowriting-baseline:` virtual
* document, and toggles a native vscode.diff (baseline left, the LIVE document
* right). A pure view: never mutates the document, sidecar, or attribution
* state (INV-19). Baselines persist via the vscode-free BaselineStore; if
* storage is unavailable the controller degrades to in-memory baselines + one
* warning (reload survival is lost; the toggle still works) — §6.5 PUC-5.
* state (INV-19).
*
* F6 works on ANY text document, not just workspace files — it needs no
* `.threads/` sidecar, only a stable doc identity + a storage home. So it has
* its OWN diffable predicate (any `file:` or `untitled:` doc), decoupled from
* F2's workspace `isTracked`. Persistable docs (`file:`) keep their baseline in
* VS Code's per-extension GLOBAL storage keyed by a hash of the document URI;
* untitled buffers have no durable identity, so their baseline is in-memory
* only (lost on reload) — the same degrade the storage-unavailable path uses.
*/
import * as path from "node:path";
import { createHash } from "node:crypto";
import * as vscode from "vscode";
import { BaselineStore, type Baseline, type BaselineReason } from "./baselineStore";
@@ -16,20 +23,17 @@ export const BASELINE_SCHEME = "cowriting-baseline";
export class DiffViewController implements vscode.Disposable {
private readonly disposables: vscode.Disposable[] = [];
/** Source of truth for the content provider; mirrors what the store persists. */
/** Source of truth for the content provider, keyed by `document.uri.toString()`. */
private readonly baselines = new Map<string, Baseline>();
private readonly onDidChangeEmitter = new vscode.EventEmitter<vscode.Uri>();
private storageWarned = false;
constructor(
private readonly store: BaselineStore | null,
private readonly rootDir: string,
) {
constructor(private readonly store: BaselineStore | null) {
const provider: vscode.TextDocumentContentProvider = {
onDidChange: this.onDidChangeEmitter.event,
provideTextDocumentContent: (uri) => {
const docPath = this.docPathFromBaselineUri(uri);
return this.baselines.get(docPath)?.text ?? "";
// The baseline URI carries the real document URI in its query (see baselineUri).
return this.baselines.get(uri.query)?.text ?? "";
},
};
this.disposables.push(
@@ -41,37 +45,49 @@ export class DiffViewController implements vscode.Disposable {
vscode.commands.registerCommand("cowriting.pinDiffBaseline", () =>
this.pinCommand(vscode.window.activeTextEditor),
),
// F6 captures a baseline for any diffable doc the moment it is first seen,
// independent of the workspace gate (so "opened" is the open-time text).
vscode.workspace.onDidOpenTextDocument((d) => this.ensureBaseline(d)),
);
for (const d of vscode.workspace.textDocuments) this.ensureBaseline(d);
}
// ---- tracking / uri helpers --------------------------------------------------------
// ---- diffability / identity --------------------------------------------------------
private isTracked(document: vscode.TextDocument): boolean {
return document.uri.scheme === "file" && document.uri.fsPath.startsWith(this.rootDir);
/** Any text document F6 can diff: a saved file OR an unsaved buffer. */
private isDiffable(document: vscode.TextDocument): boolean {
return document.uri.scheme === "file" || document.uri.scheme === "untitled";
}
private docPathOf(uri: vscode.Uri): string {
return vscode.workspace.asRelativePath(uri, false);
/** Only `file:` docs have a durable identity to persist a baseline against. */
private isPersistable(document: vscode.TextDocument): boolean {
return document.uri.scheme === "file";
}
/** The readonly virtual-doc URI whose content the provider serves for this doc. */
private baselineUri(docPath: string): vscode.Uri {
return vscode.Uri.from({ scheme: BASELINE_SCHEME, path: "/" + docPath });
/** In-memory map key — the full document URI. */
private uriKey(document: vscode.TextDocument): string {
return document.uri.toString();
}
private docPathFromBaselineUri(uri: vscode.Uri): string {
return uri.path.replace(/^\//, "");
/** Filesystem-safe storage key for a persistable doc: sha256 of its URI. */
private storageKey(uriKey: string): string {
return createHash("sha256").update(uriKey).digest("hex");
}
/** The readonly virtual-doc URI; its query carries the real document URI. */
private baselineUri(document: vscode.TextDocument): vscode.Uri {
const name = path.basename(document.uri.path) || "untitled";
return vscode.Uri.from({ scheme: BASELINE_SCHEME, path: "/" + name, query: this.uriKey(document) });
}
// ---- baseline lifecycle (§6.4) -----------------------------------------------------
/** First sight of a tracked doc: load the stored baseline, else capture `opened`. */
/** First sight of a diffable doc: load the stored baseline, else capture `opened`. */
ensureBaseline(document: vscode.TextDocument): void {
if (!this.isTracked(document)) return;
const docPath = this.docPathOf(document.uri);
if (this.baselines.has(docPath)) return;
if (this.store) {
if (!this.isDiffable(document)) return;
const key = this.uriKey(document);
if (this.baselines.has(key)) return;
if (this.store && this.isPersistable(document)) {
try {
const stored = this.store.load(docPath);
const stored = this.store.load(this.storageKey(key));
if (stored) {
this.baselines.set(docPath, stored);
this.baselines.set(key, stored);
return;
}
} catch {
@@ -83,35 +99,30 @@ export class DiffViewController implements vscode.Disposable {
/** Machine landing (INV-18): re-capture so landed text never shows as a change. */
advance(document: vscode.TextDocument): void {
if (!this.isTracked(document)) return;
if (!this.isDiffable(document)) return;
this.capture(document, "machine-landing");
}
/** Human pin: baseline := now; the open diff visibly empties (left = right). */
pin(document: vscode.TextDocument): void {
if (!this.isTracked(document)) return;
if (!this.isDiffable(document)) return;
this.capture(document, "pinned");
}
/** Capture buffer text at this epoch, persist, and refresh any open diff's left side. */
/** Capture buffer text at this epoch, persist (if persistable), refresh any open diff. */
private capture(document: vscode.TextDocument, reason: BaselineReason): void {
const docPath = this.docPathOf(document.uri);
const baseline: Baseline = {
docPath,
text: document.getText(),
capturedAt: new Date().toISOString(),
reason,
};
this.baselines.set(docPath, baseline);
if (this.store) {
const key = this.uriKey(document);
const baseline: Baseline = { uri: key, text: document.getText(), capturedAt: new Date().toISOString(), reason };
this.baselines.set(key, baseline);
if (this.store && this.isPersistable(document)) {
try {
this.store.save(docPath, baseline);
this.store.save(this.storageKey(key), baseline);
} catch {
this.warnStorageOnce();
}
}
// An open diff re-requests the left side when its baseline URI changes.
this.onDidChangeEmitter.fire(this.baselineUri(docPath));
this.onDidChangeEmitter.fire(this.baselineUri(document));
}
private warnStorageOnce(): void {
@@ -122,44 +133,21 @@ export class DiffViewController implements vscode.Disposable {
);
}
// ---- commands (toggle implemented in SLICE-3, Task 4) ------------------------------
private pinCommand(editor: vscode.TextEditor | undefined): void {
if (!editor || !this.isTracked(editor.document)) {
void vscode.window.showWarningMessage("Cowriting: open a tracked workspace document to pin its diff baseline.");
return;
}
this.pin(editor.document);
}
// ---- test-facing surface (§6.4) ----------------------------------------------------
getBaseline(docPath: string): { text: string; reason: BaselineReason; capturedAt: string } | undefined {
const b = this.baselines.get(docPath);
return b ? { text: b.text, reason: b.reason, capturedAt: b.capturedAt } : undefined;
}
/** Absolute on-disk path of this doc's persisted baseline, or undefined if in-memory. */
baselineFilePath(docPath: string): string | undefined {
return this.store?.baselinePath(docPath);
}
// ---- toggle UX (§6.5 PUC-1) --------------------------------------------------------
/**
* If this doc's baseline diff is the active/open tab → close it and reveal the
* normal editor; if the active editor is a tracked doc with no diff open →
* open vscode.diff (baseline left, the live document right). Untracked → warn,
* no diff.
* If this doc's baseline diff is open → close it and reveal the normal editor;
* else open vscode.diff (baseline left, the live document right). Warns only
* when there is no active text editor (or a non-diffable scheme).
*/
private async toggle(editor: vscode.TextEditor | undefined): Promise<void> {
if (!editor || !this.isTracked(editor.document)) {
if (!editor || !this.isDiffable(editor.document)) {
void vscode.window.showWarningMessage(
"Cowriting: open a tracked workspace document to toggle its diff view.",
"Cowriting: focus a text editor to toggle its diff view.",
);
return;
}
const document = editor.document;
const docPath = this.docPathOf(document.uri);
const openTab = this.findDiffTab(document.uri);
if (openTab) {
await vscode.window.tabGroups.close(openTab);
@@ -167,11 +155,13 @@ export class DiffViewController implements vscode.Disposable {
return;
}
this.ensureBaseline(document);
const baseline = this.baselines.get(docPath)!;
const title = `${path.basename(docPath)} — my changes since ${this.epochLabel(baseline)}`;
const baseline = this.baselines.get(this.uriKey(document))!;
const name = path.basename(document.uri.path) || "untitled";
const unsaved = this.isPersistable(document) ? "" : " (unsaved)";
const title = `${name} — my changes since ${this.epochLabel(baseline)}${unsaved}`;
await vscode.commands.executeCommand(
"vscode.diff",
this.baselineUri(docPath),
this.baselineUri(document),
document.uri,
title,
{ preview: false },
@@ -208,12 +198,28 @@ export class DiffViewController implements vscode.Disposable {
}
}
/**
* Test-facing (§6.4): is this doc's baseline diff currently open in any tab
* group? The diff's `modified` side is the document's own file: URI.
*/
isDiffOpen(docPath: string): boolean {
return this.findDiffTab(vscode.Uri.file(path.join(this.rootDir, docPath))) !== undefined;
private pinCommand(editor: vscode.TextEditor | undefined): void {
if (!editor || !this.isDiffable(editor.document)) {
void vscode.window.showWarningMessage("Cowriting: focus a text editor to pin its diff baseline.");
return;
}
this.pin(editor.document);
}
// ---- test-facing surface (§6.4) ----------------------------------------------------
getBaseline(uriString: string): { text: string; reason: BaselineReason; capturedAt: string } | undefined {
const b = this.baselines.get(uriString);
return b ? { text: b.text, reason: b.reason, capturedAt: b.capturedAt } : undefined;
}
/** Is this doc's baseline diff currently open in any tab group? */
isDiffOpen(uriString: string): boolean {
return this.findDiffTab(vscode.Uri.parse(uriString)) !== undefined;
}
/** Absolute on-disk path of this doc's persisted baseline, or undefined (untitled/in-memory). */
baselineFilePath(uriString: string): string | undefined {
if (!this.store || vscode.Uri.parse(uriString).scheme !== "file") return undefined;
return this.store.baselinePath(this.storageKey(uriString));
}
dispose(): void {