From 2edc1444253bd1987217c660f3816589241a6290 Mon Sep 17 00:00:00 2001 From: Tan <102767855+tanRdev@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:36:21 -0500 Subject: [PATCH 1/4] feat(contracts): add fs watch/unwatch/changed IPC contracts (#8) --- packages/contracts/src/channels.ts | 3 ++ packages/contracts/src/domains/fs.spec.ts | 40 +++++++++++++++++++++ packages/contracts/src/domains/fs.ts | 42 +++++++++++++++++++++-- packages/shared/src/ipc/channels.ts | 3 ++ packages/shared/src/models/api.ts | 8 ++++- packages/shared/src/models/fs.ts | 13 +++++++ 6 files changed, 106 insertions(+), 3 deletions(-) diff --git a/packages/contracts/src/channels.ts b/packages/contracts/src/channels.ts index 01480e2f..3069f561 100644 --- a/packages/contracts/src/channels.ts +++ b/packages/contracts/src/channels.ts @@ -52,6 +52,9 @@ export const IPC_CHANNELS = { deleteFile: "fs:deleteFile", renameFile: "fs:renameFile", moveFile: "fs:moveFile", + watch: "fs:watch", + unwatch: "fs:unwatch", + changed: "fs:changed", }, git: { getRepositoryStatus: "git:getRepositoryStatus", diff --git a/packages/contracts/src/domains/fs.spec.ts b/packages/contracts/src/domains/fs.spec.ts index d126f856..b32b2132 100644 --- a/packages/contracts/src/domains/fs.spec.ts +++ b/packages/contracts/src/domains/fs.spec.ts @@ -2,11 +2,13 @@ import { Schema } from "effect"; import { describe, expect, it } from "vitest"; import { + FileChangeEventSchema, FsDeleteFileRequestSchema, FsMoveFileRequestSchema, FsReadDirectoryRequestSchema, FsReadFileRequestSchema, FsRenameFileRequestSchema, + FsWatchRequestSchema, FsWriteFileRequestSchema, fsContracts, } from "./fs.js"; @@ -92,5 +94,43 @@ describe("fsContracts", () => { expect(fsContracts.deleteFile.channel).toBe("fs:deleteFile"); expect(fsContracts.renameFile.channel).toBe("fs:renameFile"); expect(fsContracts.moveFile.channel).toBe("fs:moveFile"); + expect(fsContracts.watch.channel).toBe("fs:watch"); + expect(fsContracts.unwatch.channel).toBe("fs:unwatch"); + }); + + it("declares the fs:changed event contract", () => { + expect(fsContracts.changed.kind).toBe("event"); + expect(fsContracts.changed.channel).toBe("fs:changed"); + }); +}); + +describe("fs watch schemas", () => { + it("accepts valid watch payloads and rejects non-string paths", () => { + expect( + Schema.decodeUnknownSync(FsWatchRequestSchema)({ path: "/repo" }), + ).toEqual({ path: "/repo" }); + expect(() => + Schema.decodeUnknownSync(FsWatchRequestSchema)({ path: 42 }), + ).toThrow(); + }); + + it("accepts valid file change events", () => { + expect( + Schema.decodeUnknownSync(FileChangeEventSchema)({ + type: "create", + path: "/repo/src/new.ts", + timestamp: 123, + }), + ).toEqual({ type: "create", path: "/repo/src/new.ts", timestamp: 123 }); + }); + + it("rejects file change events with unknown types", () => { + expect(() => + Schema.decodeUnknownSync(FileChangeEventSchema)({ + type: "explode", + path: "/repo/src/new.ts", + timestamp: 123, + }), + ).toThrow(); }); }); diff --git a/packages/contracts/src/domains/fs.ts b/packages/contracts/src/domains/fs.ts index 38f51637..13c8bb23 100644 --- a/packages/contracts/src/domains/fs.ts +++ b/packages/contracts/src/domains/fs.ts @@ -1,12 +1,16 @@ import type { DirectoryListing, + FileChangeEvent, FileContent, FileEntry, } from "@pi-desktop/shared"; import { Schema } from "effect"; import { IPC_CHANNELS } from "../channels.js"; -import { createIpcContract } from "../contract-runtime.js"; +import { + createIpcContract, + createIpcEventContract, +} from "../contract-runtime.js"; import { ipcStringSchema, MAX_WRITE_FILE_BYTES, @@ -40,6 +44,20 @@ export const FsMoveFileRequestSchema = Schema.Struct({ destinationPath: ipcStringSchema(), }); +export const FsWatchRequestSchema = Schema.Struct({ + path: ipcStringSchema(), +}); + +export const FsUnwatchRequestSchema = Schema.Struct({ + path: ipcStringSchema(), +}); + +export const FileChangeEventSchema = Schema.Struct({ + type: Schema.Literal("create", "modify", "delete", "rename"), + path: Schema.String, + timestamp: Schema.Number, +}) satisfies Schema.Schema; + const FileEntrySchema = Schema.Struct({ name: Schema.String, path: Schema.String, @@ -111,6 +129,18 @@ export const fsContracts = { IPC_CHANNELS.fs.moveFile, FsMoveFileRequestSchema, ), + watch: createVoidResponseContract( + IPC_CHANNELS.fs.watch, + FsWatchRequestSchema, + ), + unwatch: createVoidResponseContract( + IPC_CHANNELS.fs.unwatch, + FsUnwatchRequestSchema, + ), + changed: createIpcEventContract({ + channel: IPC_CHANNELS.fs.changed, + payload: FileChangeEventSchema, + }), } as const; type AssignableTo = Decoded extends Target ? true : never; @@ -123,10 +153,15 @@ type _FileContentAssignable = AssignableTo< Schema.Schema.Type, FileContent >; +type _FileChangeEventAssignable = AssignableTo< + Schema.Schema.Type, + FileChangeEvent +>; export type FsSchemasAssignable = | _DirectoryListingAssignable - | _FileContentAssignable; + | _FileContentAssignable + | _FileChangeEventAssignable; export const fsContractList = [ fsContracts.readDirectory, @@ -135,4 +170,7 @@ export const fsContractList = [ fsContracts.deleteFile, fsContracts.renameFile, fsContracts.moveFile, + fsContracts.watch, + fsContracts.unwatch, + fsContracts.changed, ] as const; diff --git a/packages/shared/src/ipc/channels.ts b/packages/shared/src/ipc/channels.ts index 4c2ea876..24ae252b 100644 --- a/packages/shared/src/ipc/channels.ts +++ b/packages/shared/src/ipc/channels.ts @@ -56,6 +56,9 @@ export const IPC_CHANNELS = { deleteFile: "fs:deleteFile", renameFile: "fs:renameFile", moveFile: "fs:moveFile", + watch: "fs:watch", + unwatch: "fs:unwatch", + changed: "fs:changed", }, git: { getRepositoryStatus: "git:getRepositoryStatus", diff --git a/packages/shared/src/models/api.ts b/packages/shared/src/models/api.ts index e609b7f2..fb049e91 100644 --- a/packages/shared/src/models/api.ts +++ b/packages/shared/src/models/api.ts @@ -11,7 +11,7 @@ import type { SettingsSnapshot, } from "./agent.js"; import type { OpenDialogOptions } from "./dialog.js"; -import type { DirectoryListing, FileContent } from "./fs.js"; +import type { DirectoryListing, FileChangeEvent, FileContent } from "./fs.js"; import type { GitFileDiff, GitRepositoryStatus } from "./git.js"; import type { InstalledPackageSnapshot, @@ -92,6 +92,12 @@ export interface PiDesktopApi { deleteFile(path: string): Promise; renameFile(oldPath: string, newPath: string): Promise; moveFile(sourcePath: string, destinationPath: string): Promise; + /** + * Watch a workspace directory (recursively) for external changes. + * The listener receives `fs:changed` contract events for entries at or + * below `path`. Returns an unsubscribe function that stops the watch. + */ + watch(path: string, listener: (event: FileChangeEvent) => void): () => void; }; git: { getRepositoryStatus( diff --git a/packages/shared/src/models/fs.ts b/packages/shared/src/models/fs.ts index 864a1d31..1243bc16 100644 --- a/packages/shared/src/models/fs.ts +++ b/packages/shared/src/models/fs.ts @@ -10,6 +10,19 @@ export interface DirectoryListing { entries: FileEntry[]; } +export type FileChangeEventType = "create" | "modify" | "delete" | "rename"; + +/** + * A single filesystem change observed by the main-process workspace watcher + * and pushed to the renderer over the `fs:changed` event contract. `path` is + * the absolute path of the changed entry (nested paths included). + */ +export interface FileChangeEvent { + type: FileChangeEventType; + path: string; + timestamp: number; +} + export interface FileContent { path: string; content: string; From 2d33cdd56c117ce0e6ab5b18d6c3f346875cc637 Mon Sep 17 00:00:00 2001 From: Tan <102767855+tanRdev@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:36:27 -0500 Subject: [PATCH 2/4] feat(desktop): connect filesystem watcher to the file tree via typed IPC (#8) --- .../main/fs/workspace-file-watcher.spec.ts | 169 +++++++++++++++ .../src/main/fs/workspace-file-watcher.ts | 202 ++++++++++++++++++ .../ipc/register-filesystem-handlers.spec.ts | 96 +++++++++ .../main/ipc/register-filesystem-handlers.ts | 14 ++ .../ipc/register-filesystem-watch-handlers.ts | 94 ++++++++ apps/desktop/src/preload/api.spec.ts | 67 ++++++ apps/desktop/src/preload/api.ts | 28 +-- apps/desktop/src/preload/fs-api.ts | 74 +++++++ .../components/file-tree-panel.spec.tsx | 52 +++++ .../workspace/components/file-tree-panel.tsx | 13 +- .../features/workspace/use-file-tree.spec.ts | 83 +++++++ apps/desktop/src/renderer/src/global.d.ts | 4 - .../lib/file-watcher/file-watcher-bridge.ts | 4 +- .../lib/file-watcher/file-watcher-stream.ts | 10 +- 14 files changed, 872 insertions(+), 38 deletions(-) create mode 100644 apps/desktop/src/main/fs/workspace-file-watcher.spec.ts create mode 100644 apps/desktop/src/main/fs/workspace-file-watcher.ts create mode 100644 apps/desktop/src/main/ipc/register-filesystem-handlers.spec.ts create mode 100644 apps/desktop/src/main/ipc/register-filesystem-watch-handlers.ts create mode 100644 apps/desktop/src/preload/api.spec.ts create mode 100644 apps/desktop/src/preload/fs-api.ts diff --git a/apps/desktop/src/main/fs/workspace-file-watcher.spec.ts b/apps/desktop/src/main/fs/workspace-file-watcher.spec.ts new file mode 100644 index 00000000..05bf2f0e --- /dev/null +++ b/apps/desktop/src/main/fs/workspace-file-watcher.spec.ts @@ -0,0 +1,169 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { FileChangeEvent } from "@pi-desktop/shared"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + createWorkspaceFileWatcherService, + type FileWatchSender, + type WatchDirectoryFn, +} from "./workspace-file-watcher"; + +function createFakeSender() { + const sent: Array<{ channel: string; payload: FileChangeEvent }> = []; + const destroyedListeners: Array<() => void> = []; + const sender: FileWatchSender & { + sent: typeof sent; + triggerDestroyed: () => void; + } = { + sent, + send: (channel, payload) => { + sent.push({ channel, payload }); + }, + once: (_event, listener) => { + destroyedListeners.push(listener); + }, + triggerDestroyed: () => { + for (const listener of destroyedListeners) listener(); + }, + }; + return sender; +} + +function createFakeWatchDirectory() { + const listeners = new Map< + string, + (eventType: "rename" | "change", filename: string | null) => void + >(); + const closed: string[] = []; + const watchDirectory: WatchDirectoryFn = (rootPath, listener) => { + listeners.set(rootPath, listener); + return { + close: () => { + closed.push(rootPath); + listeners.delete(rootPath); + }, + }; + }; + return { watchDirectory, listeners, closed }; +} + +describe("createWorkspaceFileWatcherService", () => { + it("forwards classified events for nested paths on the fs:changed channel", () => { + const fake = createFakeWatchDirectory(); + const service = createWorkspaceFileWatcherService( + fake.watchDirectory, + () => 42, + ); + const sender = createFakeSender(); + + service.subscribe(sender, "/root"); + const listener = fake.listeners.get("/root"); + expect(listener).toBeDefined(); + + // "change" events are content modifications. + listener?.("change", path.join("src", "deep", "file.ts")); + expect(sender.sent).toEqual([ + { + channel: "fs:changed", + payload: { + type: "modify", + path: path.join("/root", "src", "deep", "file.ts"), + timestamp: 42, + }, + }, + ]); + }); + + it("classifies rename events by existence and ignores dependency/VCS trees", () => { + const root = mkdtempSync(path.join(tmpdir(), "pi-watch-")); + try { + mkdirSync(path.join(root, "src"), { recursive: true }); + writeFileSync(path.join(root, "src", "kept.ts"), "x"); + const fake = createFakeWatchDirectory(); + const service = createWorkspaceFileWatcherService(fake.watchDirectory); + const sender = createFakeSender(); + service.subscribe(sender, root); + const listener = fake.listeners.get(root); + + listener?.("rename", path.join("src", "kept.ts")); + listener?.("rename", path.join("src", "gone.ts")); + listener?.("change", path.join("node_modules", "pkg", "index.js")); + listener?.("rename", path.join(".git", "index")); + + const types = sender.sent.map((entry) => entry.payload.type); + expect(types).toEqual(["create", "delete"]); + service.unsubscribeAll(sender); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("shares one watcher per root and closes it when the last sender leaves", () => { + const fake = createFakeWatchDirectory(); + const service = createWorkspaceFileWatcherService(fake.watchDirectory); + const first = createFakeSender(); + const second = createFakeSender(); + + service.subscribe(first, "/root"); + service.subscribe(second, "/root"); + expect(fake.listeners.size).toBe(1); + expect(service.watcherCountFor(first)).toBe(1); + + service.unsubscribe(first, "/root"); + expect(fake.closed).toEqual([]); + fake.listeners.get("/root")?.("change", "a.ts"); + expect(first.sent).toHaveLength(0); + expect(second.sent).toHaveLength(1); + + service.unsubscribe(second, "/root"); + expect(fake.closed).toEqual(["/root"]); + expect(service.watcherCountFor(second)).toBe(0); + }); + + it("tears down a sender's watches when the sender is destroyed", () => { + const fake = createFakeWatchDirectory(); + const service = createWorkspaceFileWatcherService(fake.watchDirectory); + const sender = createFakeSender(); + + service.subscribe(sender, "/root"); + sender.triggerDestroyed(); + + expect(service.watcherCountFor(sender)).toBe(0); + expect(fake.closed).toEqual(["/root"]); + }); + + describe("with the real filesystem", () => { + let root: string; + + afterEach(() => { + if (root) { + rmSync(root, { recursive: true, force: true }); + } + }); + + it("reports a file created in a nested directory", async () => { + root = mkdtempSync(path.join(tmpdir(), "pi-watch-real-")); + mkdirSync(path.join(root, "src", "deep"), { recursive: true }); + const service = createWorkspaceFileWatcherService(); + const sender = createFakeSender(); + service.subscribe(sender, root); + + const nestedPath = path.join(root, "src", "deep", "new-file.ts"); + writeFileSync(nestedPath, "export {};\n"); + + await vi.waitFor(() => { + expect( + sender.sent.some( + (entry) => + entry.payload.path === nestedPath && + entry.payload.type === "create", + ), + ).toBe(true); + }); + + service.unsubscribeAll(sender); + expect(service.watcherCountFor(sender)).toBe(0); + }); + }); +}); diff --git a/apps/desktop/src/main/fs/workspace-file-watcher.ts b/apps/desktop/src/main/fs/workspace-file-watcher.ts new file mode 100644 index 00000000..3a67a759 --- /dev/null +++ b/apps/desktop/src/main/fs/workspace-file-watcher.ts @@ -0,0 +1,202 @@ +import { existsSync, type FSWatcher, watch as fsWatch } from "node:fs"; +import path from "node:path"; +import { type FileChangeEvent, IPC_CHANNELS } from "@pi-desktop/shared"; + +/** + * Workspace filesystem watcher (main process). + * + * Watches a workspace root recursively with `node:fs.watch` and pushes + * classified change events to each subscribed renderer over the typed + * `fs:changed` event contract (`fsContracts.changed`). Subscriptions are + * keyed by the IPC sender (a `WebContents`-shaped object), so a window only + * receives events for roots it asked to watch, and its watches are torn down + * when the sender is destroyed. + * + * Directory basenames in {@link IGNORED_DIRECTORY_NAMES} are never reported: + * they churn constantly (dependency installs, VCS internals) and are not + * shown in the file tree. + */ + +export interface FileWatchSender { + send(channel: string, payload: FileChangeEvent): void; + once?(event: "destroyed", listener: () => void): void; + isDestroyed?(): boolean; +} + +type RawWatchEventType = "rename" | "change"; + +export interface WatchDirectoryHandle { + close(): void; +} + +export type WatchDirectoryFn = ( + rootPath: string, + listener: (eventType: RawWatchEventType, filename: string | null) => void, +) => WatchDirectoryHandle; + +export interface WorkspaceFileWatcherService { + subscribe(sender: FileWatchSender, rootPath: string): void; + unsubscribe(sender: FileWatchSender, rootPath: string): void; + unsubscribeAll(sender: FileWatchSender): void; + /** Number of live watchers held for a sender (test/diagnostic hook). */ + watcherCountFor(sender: FileWatchSender): number; +} + +const IGNORED_DIRECTORY_NAMES: ReadonlySet = new Set([ + "node_modules", + ".git", +]); + +interface WatchEntry { + readonly rootPath: string; + readonly handle: WatchDirectoryHandle; + readonly senders: Set; +} + +function defaultWatchDirectory( + rootPath: string, + listener: (eventType: RawWatchEventType, filename: string | null) => void, +): WatchDirectoryHandle { + const watcher: FSWatcher = fsWatch( + rootPath, + { recursive: true }, + (eventType, filename) => { + listener( + eventType === "change" ? "change" : "rename", + filename === null ? null : String(filename), + ); + }, + ); + // A watcher error (e.g. the root was deleted) must not crash the main + // process; the subscription simply stops producing events. + watcher.on("error", () => undefined); + return watcher; +} + +function isIgnoredPath(rootPath: string, changedPath: string): boolean { + const relative = path.relative(rootPath, changedPath); + if (relative === "") return false; + return relative + .split(path.sep) + .some((segment) => IGNORED_DIRECTORY_NAMES.has(segment)); +} + +/** + * Classify a raw `fs.watch` callback into the contract event type. + * `rename` means an entry appeared, disappeared, or moved; existence on disk + * at delivery time decides between create / delete / rename. + */ +function classifyEvent( + eventType: RawWatchEventType, + changedPath: string, +): FileChangeEvent["type"] { + if (eventType === "change") { + return "modify"; + } + return existsSync(changedPath) ? "create" : "delete"; +} + +export function createWorkspaceFileWatcherService( + watchDirectory: WatchDirectoryFn = defaultWatchDirectory, + now: () => number = () => Date.now(), +): WorkspaceFileWatcherService { + /** Live watchers keyed by canonical root path. */ + const entriesByRoot = new Map(); + /** Senders already hooked for `destroyed` cleanup. */ + const hookedSenders = new WeakSet(); + + function teardownEntry(entry: WatchEntry): void { + entriesByRoot.delete(entry.rootPath); + try { + entry.handle.close(); + } catch { + // Closing an already-dead watcher is harmless. + } + } + + function removeSender(entry: WatchEntry, sender: FileWatchSender): void { + entry.senders.delete(sender); + if (entry.senders.size === 0) { + teardownEntry(entry); + } + } + + function handleRawEvent( + entry: WatchEntry, + eventType: RawWatchEventType, + filename: string | null, + ): void { + // Without a filename we cannot attribute the change to a path; the + // renderer debounces per path, so unattributed events are dropped. + if (!filename) return; + const changedPath = path.join(entry.rootPath, filename); + if (isIgnoredPath(entry.rootPath, changedPath)) return; + + const event: FileChangeEvent = { + type: classifyEvent(eventType, changedPath), + path: changedPath, + timestamp: now(), + }; + + for (const sender of [...entry.senders]) { + if (sender.isDestroyed?.()) { + removeSender(entry, sender); + continue; + } + try { + sender.send(IPC_CHANNELS.fs.changed, event); + } catch { + removeSender(entry, sender); + } + } + } + + function subscribe(sender: FileWatchSender, rootPath: string): void { + if (!hookedSenders.has(sender) && typeof sender.once === "function") { + hookedSenders.add(sender); + sender.once("destroyed", () => { + unsubscribeAll(sender); + }); + } + + const existing = entriesByRoot.get(rootPath); + if (existing) { + existing.senders.add(sender); + return; + } + + const entry: WatchEntry = { + rootPath, + senders: new Set([sender]), + handle: watchDirectory(rootPath, (eventType, filename) => { + handleRawEvent(entry, eventType, filename); + }), + }; + entriesByRoot.set(rootPath, entry); + } + + function unsubscribe(sender: FileWatchSender, rootPath: string): void { + const entry = entriesByRoot.get(rootPath); + if (!entry) return; + removeSender(entry, sender); + } + + function unsubscribeAll(sender: FileWatchSender): void { + for (const entry of [...entriesByRoot.values()]) { + removeSender(entry, sender); + } + } + + return { + subscribe, + unsubscribe, + unsubscribeAll, + watcherCountFor(sender: FileWatchSender): number { + let count = 0; + for (const entry of entriesByRoot.values()) { + if (entry.senders.has(sender)) count += 1; + } + return count; + }, + }; +} diff --git a/apps/desktop/src/main/ipc/register-filesystem-handlers.spec.ts b/apps/desktop/src/main/ipc/register-filesystem-handlers.spec.ts new file mode 100644 index 00000000..cee348d1 --- /dev/null +++ b/apps/desktop/src/main/ipc/register-filesystem-handlers.spec.ts @@ -0,0 +1,96 @@ +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { + FileWatchSender, + WorkspaceFileWatcherService, +} from "../fs/workspace-file-watcher"; +import { registerFilesystemHandlers } from "./register-filesystem-handlers"; + +type HandlerListener = ( + event?: unknown, + payload?: unknown, +) => Promise | unknown; + +describe("registerFilesystemHandlers watch contracts", () => { + let root: string; + let workspaceDir: string; + let listeners: Map; + let subscribe: ReturnType< + typeof vi.fn<(sender: FileWatchSender, rootPath: string) => void> + >; + let unsubscribe: ReturnType< + typeof vi.fn<(sender: FileWatchSender, rootPath: string) => void> + >; + let sender: FileWatchSender; + + beforeEach(() => { + root = mkdtempSync(path.join(tmpdir(), "pi-fs-handlers-")); + workspaceDir = path.join(root, "workspace"); + mkdirSync(workspaceDir, { recursive: true }); + + listeners = new Map(); + subscribe = vi.fn(); + unsubscribe = vi.fn(); + const fileWatcher: WorkspaceFileWatcherService = { + subscribe, + unsubscribe, + unsubscribeAll: vi.fn(), + watcherCountFor: vi.fn(() => 0), + }; + sender = { send: vi.fn() }; + + registerFilesystemHandlers({ + handle: (channel, listener) => { + listeners.set(channel, listener as HandlerListener); + }, + getWorkspaceRootPath: () => root, + fileWatcher, + }); + }); + + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it("subscribes the event sender with the canonical watched path", async () => { + const watchListener = listeners.get("fs:watch"); + expect(watchListener).toBeDefined(); + + await watchListener?.({ sender }, { path: workspaceDir }); + + expect(subscribe).toHaveBeenCalledTimes(1); + expect(subscribe).toHaveBeenCalledWith( + sender, + expect.stringContaining("workspace"), + ); + const subscribedPath = subscribe.mock.calls[0]?.[1] as string; + expect(path.basename(subscribedPath)).toBe("workspace"); + }); + + it("unsubscribes the event sender on fs:unwatch", async () => { + const unwatchListener = listeners.get("fs:unwatch"); + expect(unwatchListener).toBeDefined(); + + await unwatchListener?.({ sender }, { path: workspaceDir }); + + expect(unsubscribe).toHaveBeenCalledTimes(1); + expect(unsubscribe.mock.calls[0]?.[0]).toBe(sender); + }); + + it("rejects watch requests without an IPC sender", async () => { + const watchListener = listeners.get("fs:watch"); + await expect(watchListener?.({}, { path: workspaceDir })).rejects.toThrow(); + expect(subscribe).not.toHaveBeenCalled(); + }); + + it("rejects watch paths outside the workspace root", async () => { + const watchListener = listeners.get("fs:watch"); + const outside = path.join(tmpdir(), "pi-fs-handlers-outside"); + await expect( + watchListener?.({ sender }, { path: outside }), + ).rejects.toThrow(); + expect(subscribe).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/desktop/src/main/ipc/register-filesystem-handlers.ts b/apps/desktop/src/main/ipc/register-filesystem-handlers.ts index bdb8d213..883f7dd8 100644 --- a/apps/desktop/src/main/ipc/register-filesystem-handlers.ts +++ b/apps/desktop/src/main/ipc/register-filesystem-handlers.ts @@ -1,5 +1,10 @@ import { fsContracts, registerContractHandler } from "@pi-desktop/contracts"; import { PathGuardError, resolveInsideRoot } from "../fs/path-guards"; +import { + createWorkspaceFileWatcherService, + type WorkspaceFileWatcherService, +} from "../fs/workspace-file-watcher"; +import { registerFilesystemWatchHandlers } from "./register-filesystem-watch-handlers"; /** * Maximum size, in bytes, of a single read or write operation. Reads above @@ -89,6 +94,8 @@ interface RegisterFilesystemHandlersDependencies { listener: (event?: unknown, payload?: unknown) => unknown, ) => void; getWorkspaceRootPath(): string | null; + /** Injectable for tests; defaults to a real recursive fs watcher. */ + fileWatcher?: WorkspaceFileWatcherService; } function isVisibleFilesystemEntry(entry: { @@ -112,6 +119,7 @@ function requireRoots(getWorkspaceRootPath: () => string | null): string[] { export function registerFilesystemHandlers({ handle, getWorkspaceRootPath, + fileWatcher = createWorkspaceFileWatcherService(), }: RegisterFilesystemHandlersDependencies): void { registerContractHandler({ handle, @@ -281,6 +289,12 @@ export function registerFilesystemHandlers({ }, }); + registerFilesystemWatchHandlers({ + handle, + getWorkspaceRootPath, + fileWatcher, + }); + registerContractHandler({ handle, contract: fsContracts.moveFile, diff --git a/apps/desktop/src/main/ipc/register-filesystem-watch-handlers.ts b/apps/desktop/src/main/ipc/register-filesystem-watch-handlers.ts new file mode 100644 index 00000000..f44195c4 --- /dev/null +++ b/apps/desktop/src/main/ipc/register-filesystem-watch-handlers.ts @@ -0,0 +1,94 @@ +import { fsContracts, registerContractHandler } from "@pi-desktop/contracts"; +import { PathGuardError, resolveInsideRoot } from "../fs/path-guards"; +import type { + FileWatchSender, + WorkspaceFileWatcherService, +} from "../fs/workspace-file-watcher"; + +interface RegisterFilesystemWatchHandlersDependencies { + handle: ( + channel: string, + listener: (event?: unknown, payload?: unknown) => unknown, + ) => void; + getWorkspaceRootPath(): string | null; + fileWatcher: WorkspaceFileWatcherService; +} + +/** + * Extract the event sender (`WebContents`) from an IPC event so watch + * subscriptions can push `fs:changed` events back to the subscribing window. + */ +function extractWatchSender(event: unknown): FileWatchSender | null { + if (typeof event !== "object" || event === null) { + return null; + } + const sender = (event as { sender?: unknown }).sender; + if (typeof sender !== "object" || sender === null) { + return null; + } + if (typeof (sender as { send?: unknown }).send !== "function") { + return null; + } + return sender as FileWatchSender; +} + +function requireRoots(getWorkspaceRootPath: () => string | null): string[] { + const root = getWorkspaceRootPath(); + if (!root) { + throw new PathGuardError({ + code: "path/no-root-configured", + message: "workspace root is not configured", + }); + } + return [root]; +} + +/** + * Register the `fs:watch` / `fs:unwatch` contract handlers. Watching is a + * subscription, not a request/response: the invoke records the sender + * against the canonical workspace path in the watcher service, which then + * pushes `fs:changed` contract events to that sender until `fs:unwatch` + * (or sender destruction) tears the subscription down. + */ +export function registerFilesystemWatchHandlers({ + handle, + getWorkspaceRootPath, + fileWatcher, +}: RegisterFilesystemWatchHandlersDependencies): void { + registerContractHandler({ + handle, + contract: fsContracts.watch, + handler: async ({ path: watchPath }, event) => { + const sender = extractWatchSender(event); + if (!sender) { + throw new Error("fs.watch requires an IPC event sender"); + } + const roots = requireRoots(getWorkspaceRootPath); + const canonicalTarget = resolveInsideRoot(roots, watchPath); + fileWatcher.subscribe(sender, canonicalTarget); + }, + }); + + registerContractHandler({ + handle, + contract: fsContracts.unwatch, + handler: async ({ path: watchPath }, event) => { + const sender = extractWatchSender(event); + if (!sender) { + throw new Error("fs.unwatch requires an IPC event sender"); + } + const roots = requireRoots(getWorkspaceRootPath); + let canonicalTarget: string; + try { + canonicalTarget = resolveInsideRoot(roots, watchPath); + } catch { + // The watched root may have been deleted since subscribing; fall + // back to the lexical absolute path so teardown still matches the + // subscription key when possible, and never fail an unsubscribe. + const pathModule = await import("node:path"); + canonicalTarget = pathModule.resolve(watchPath); + } + fileWatcher.unsubscribe(sender, canonicalTarget); + }, + }); +} diff --git a/apps/desktop/src/preload/api.spec.ts b/apps/desktop/src/preload/api.spec.ts new file mode 100644 index 00000000..75e0e5b1 --- /dev/null +++ b/apps/desktop/src/preload/api.spec.ts @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from "vitest"; +import { createPiDesktopApi } from "./api"; + +function createPreloadHarness() { + const invoke = vi.fn( + async (_channel: string, _payload?: unknown) => undefined, + ); + const channelListeners = new Map void>(); + const onUnsubscribe = vi.fn(); + const on = vi.fn((channel: string, listener: (payload: unknown) => void) => { + channelListeners.set(channel, listener); + return onUnsubscribe; + }); + const api = createPiDesktopApi({ + invoke: invoke as never, + on: on as never, + }); + return { api, invoke, on, onUnsubscribe, channelListeners }; +} + +describe("createPiDesktopApi fs.watch", () => { + it("starts a main-process watch through the fs:watch contract", () => { + const { api, invoke } = createPreloadHarness(); + + api.fs.watch("/root", () => undefined); + + expect(invoke).toHaveBeenCalledWith("fs:watch", { path: "/root" }); + }); + + it("forwards fs:changed events for the watched root and its descendants only", () => { + const { api, channelListeners } = createPreloadHarness(); + const listener = vi.fn(); + api.fs.watch("/root", listener); + + const emit = channelListeners.get("fs:changed"); + expect(emit).toBeDefined(); + + emit?.({ type: "create", path: "/root/src/new.ts", timestamp: 1 }); + emit?.({ type: "create", path: "/other/src/new.ts", timestamp: 2 }); + emit?.({ type: "delete", path: "/root/old.ts", timestamp: 3 }); + + expect(listener).toHaveBeenCalledTimes(2); + expect(listener).toHaveBeenNthCalledWith(1, { + type: "create", + path: "/root/src/new.ts", + timestamp: 1, + }); + expect(listener).toHaveBeenNthCalledWith(2, { + type: "delete", + path: "/root/old.ts", + timestamp: 3, + }); + }); + + it("unsubscribe removes the channel listener and invokes fs:unwatch once", () => { + const { api, invoke, onUnsubscribe } = createPreloadHarness(); + + const unsubscribe = api.fs.watch("/root", () => undefined); + unsubscribe(); + unsubscribe(); + + expect(onUnsubscribe).toHaveBeenCalledTimes(1); + expect( + invoke.mock.calls.filter(([channel]) => channel === "fs:unwatch"), + ).toEqual([["fs:unwatch", { path: "/root" }]]); + }); +}); diff --git a/apps/desktop/src/preload/api.ts b/apps/desktop/src/preload/api.ts index 3f69b514..9f71d70b 100644 --- a/apps/desktop/src/preload/api.ts +++ b/apps/desktop/src/preload/api.ts @@ -4,7 +4,6 @@ import { createContractInvoker, createContractSubscriber, dialogContracts, - fsContracts, gitContracts, packagesContracts, repositoryContracts, @@ -29,6 +28,7 @@ import type { TerminalCreateOptions, } from "@pi-desktop/shared"; +import { createFsApi } from "./fs-api"; import { createStateApi } from "./state-api"; import { createUpdatesApi, @@ -165,31 +165,7 @@ export function createPiDesktopApi({ return invokeContract(dialogContracts.openExternal, { url }); }, }, - fs: { - readDirectory(path: string) { - return invokeContract(fsContracts.readDirectory, { path }) as Promise< - import("@pi-desktop/shared").DirectoryListing - >; - }, - readFile(path: string) { - return invokeContract(fsContracts.readFile, { path }); - }, - writeFile(path: string, content: string) { - return invokeContract(fsContracts.writeFile, { path, content }); - }, - deleteFile(path: string) { - return invokeContract(fsContracts.deleteFile, { path }); - }, - renameFile(oldPath: string, newPath: string) { - return invokeContract(fsContracts.renameFile, { oldPath, newPath }); - }, - moveFile(sourcePath: string, destinationPath: string) { - return invokeContract(fsContracts.moveFile, { - sourcePath, - destinationPath, - }); - }, - }, + fs: createFsApi({ invokeContract, subscribeContract }), git: { getRepositoryStatus( repositoryPath: string, diff --git a/apps/desktop/src/preload/fs-api.ts b/apps/desktop/src/preload/fs-api.ts new file mode 100644 index 00000000..10f2e9d0 --- /dev/null +++ b/apps/desktop/src/preload/fs-api.ts @@ -0,0 +1,74 @@ +import { + type createContractInvoker, + type createContractSubscriber, + fsContracts, +} from "@pi-desktop/contracts"; +import type { FileChangeEvent, PiDesktopApi } from "@pi-desktop/shared"; + +export interface CreateFsApiDependencies { + invokeContract: ReturnType; + subscribeContract: ReturnType; +} + +/** + * Filesystem preload API. `watch` is backed by the typed `fs:watch` / + * `fs:unwatch` invoke contracts plus the shared `fs:changed` event contract: + * subscribing starts a recursive main-process watch for the root, and the + * returned unsubscribe stops it again. + */ +export function createFsApi({ + invokeContract, + subscribeContract, +}: CreateFsApiDependencies): PiDesktopApi["fs"] { + return { + readDirectory(path: string) { + return invokeContract(fsContracts.readDirectory, { path }) as Promise< + import("@pi-desktop/shared").DirectoryListing + >; + }, + readFile(path: string) { + return invokeContract(fsContracts.readFile, { path }); + }, + writeFile(path: string, content: string) { + return invokeContract(fsContracts.writeFile, { path, content }); + }, + deleteFile(path: string) { + return invokeContract(fsContracts.deleteFile, { path }); + }, + renameFile(oldPath: string, newPath: string) { + return invokeContract(fsContracts.renameFile, { oldPath, newPath }); + }, + moveFile(sourcePath: string, destinationPath: string) { + return invokeContract(fsContracts.moveFile, { + sourcePath, + destinationPath, + }); + }, + watch(path: string, listener: (event: FileChangeEvent) => void) { + // The main process pushes changes for every watched root on the + // shared `fs:changed` channel; forward only this root's events. + const unsubscribe = subscribeContract( + fsContracts.changed, + (event: FileChangeEvent) => { + if ( + event.path === path || + event.path.startsWith(`${path}/`) || + event.path.startsWith(`${path}\\`) + ) { + listener(event); + } + }, + ); + void invokeContract(fsContracts.watch, { path }).catch(() => undefined); + let stopped = false; + return () => { + if (stopped) return; + stopped = true; + unsubscribe(); + void invokeContract(fsContracts.unwatch, { path }).catch( + () => undefined, + ); + }; + }, + }; +} diff --git a/apps/desktop/src/renderer/src/features/workspace/components/file-tree-panel.spec.tsx b/apps/desktop/src/renderer/src/features/workspace/components/file-tree-panel.spec.tsx index e8525031..f516d2d6 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/file-tree-panel.spec.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/file-tree-panel.spec.tsx @@ -193,6 +193,58 @@ describe("FileTreePanel", () => { }); }); + it("refreshes the tree when a nested file is created externally", async () => { + type Entry = { name: string; path: string; type: "file" | "directory" }; + type WatchCallback = (event: { + type: string; + path: string; + timestamp: number; + }) => void; + let entries: Entry[] = [ + { name: "src", path: "/root/src", type: "directory" }, + ]; + const watchRef: { callback: WatchCallback | null } = { callback: null }; + installMockPiDesktop({ + fs: { + readDirectory: vi.fn((path: string) => + Promise.resolve({ path, entries }), + ), + watch: vi.fn((_path: string, callback: WatchCallback) => { + watchRef.callback = callback; + return () => { + watchRef.callback = null; + }; + }), + }, + }); + + renderWithProviders( + {}} />, + ); + + await waitFor(() => { + expect(screen.getByText("src")).toBeInTheDocument(); + }); + expect(watchRef.callback).not.toBeNull(); + + entries = [ + { name: "src", path: "/root/src", type: "directory" }, + { name: "external.ts", path: "/root/external.ts", type: "file" }, + ]; + watchRef.callback?.({ + type: "create", + path: "/root/src/deep/external.ts", + timestamp: Date.now(), + }); + + await waitFor( + () => { + expect(screen.getByText("external.ts")).toBeInTheDocument(); + }, + { timeout: 3000 }, + ); + }); + it("exposes a tree role with aria-label", async () => { installMockPiDesktop({ fs: { diff --git a/apps/desktop/src/renderer/src/features/workspace/components/file-tree-panel.tsx b/apps/desktop/src/renderer/src/features/workspace/components/file-tree-panel.tsx index 0f216540..1452732e 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/file-tree-panel.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/file-tree-panel.tsx @@ -17,6 +17,7 @@ import { } from "@/components/ui/phosphor-icons"; import { useRecentFiles } from "@/features/workspace/recent-items"; import { useFileTree } from "@/features/workspace/use-file-tree"; +import { watch } from "@/lib/file-watcher"; import { toast } from "@/lib/toast"; import { FileTreeContextMenu } from "./file-tree-context-menu"; import { FileTreeItem } from "./file-tree-item"; @@ -75,6 +76,16 @@ export function FileTreePanel({ onMoveFile, repositoryStatus, }: FileTreePanelProps) { + // Stream of external filesystem changes for this workspace, backed by the + // typed `fs:watch`/`fs:changed` IPC contracts. `useFileTree` subscribes to + // it and refreshes the tree when entries are created/deleted/renamed at + // any depth; the stream tears the native watch down when its last + // subscriber (the tree) unsubscribes. + const watchEvents$ = useMemo( + () => (workspacePath ? watch(workspacePath) : undefined), + [workspacePath], + ); + const { rootNodes, isRootLoading, @@ -88,7 +99,7 @@ export function FileTreePanel({ toggleMultiSelect, handleKeyDown: handleTreeKeyDown, flatRows, - } = useFileTree(workspacePath); + } = useFileTree(workspacePath, { watchEvents$ }); const recentFiles = useRecentFiles(); const recentFileItems = useMemo( diff --git a/apps/desktop/src/renderer/src/features/workspace/use-file-tree.spec.ts b/apps/desktop/src/renderer/src/features/workspace/use-file-tree.spec.ts index fbb26ad8..44396d1b 100644 --- a/apps/desktop/src/renderer/src/features/workspace/use-file-tree.spec.ts +++ b/apps/desktop/src/renderer/src/features/workspace/use-file-tree.spec.ts @@ -3,12 +3,39 @@ import type { FileEntry } from "@pi-desktop/shared/models/fs"; import { act, renderHook, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { + FileChangeEvent, + FileChangeSubscriber, + FileWatcherStream, +} from "@/lib/file-watcher"; import { installMockPiDesktop, uninstallMockPiDesktop, } from "../../../../test/mock-pi-desktop"; import { useFileTree } from "./use-file-tree"; +function createFakeWatchStream(): { + stream: FileWatcherStream; + emit: (event: FileChangeEvent) => void; +} { + let subscriber: FileChangeSubscriber | null = null; + return { + stream: { + subscribe: (next: FileChangeSubscriber) => { + subscriber = next; + return () => { + subscriber = null; + }; + }, + getActivePath: () => "/root", + isActive: () => true, + }, + emit: (event: FileChangeEvent) => { + subscriber?.(event); + }, + }; +} + function entry(name: string, type: "file" | "directory" = "file"): FileEntry { return { name, @@ -479,4 +506,60 @@ describe("useFileTree", () => { expect(result.current.selectedPath).toBeNull(); }); }); + + describe("watch events", () => { + it("refreshes the root when a nested file is created externally", async () => { + let rootEntries = [entry("src", "directory")]; + const readDirectory = vi.fn((path: string) => + Promise.resolve({ path, entries: rootEntries }), + ); + installMockPiDesktop({ fs: { readDirectory } }); + const fakeWatch = createFakeWatchStream(); + + const { result } = renderHook(() => + useFileTree("/root", { watchEvents$: fakeWatch.stream }), + ); + await waitFor(() => expect(result.current.rootNodes).toHaveLength(1)); + const rootCallsBefore = readDirectory.mock.calls.filter( + ([path]) => path === "/root", + ).length; + + rootEntries = [entry("src", "directory"), entry("new-file.ts")]; + act(() => { + fakeWatch.emit({ + type: "create", + path: "/root/src/deep/new-file.ts", + timestamp: 1, + }); + }); + + await waitFor(() => expect(result.current.rootNodes).toHaveLength(2)); + expect( + readDirectory.mock.calls.filter(([path]) => path === "/root").length, + ).toBeGreaterThan(rootCallsBefore); + }); + + it("marks modified files dirty without reloading the root", async () => { + const readDirectory = vi.fn((path: string) => + Promise.resolve({ path, entries: [entry("a.ts")] }), + ); + installMockPiDesktop({ fs: { readDirectory } }); + const fakeWatch = createFakeWatchStream(); + + const { result } = renderHook(() => + useFileTree("/root", { watchEvents$: fakeWatch.stream }), + ); + await waitFor(() => expect(result.current.rootNodes).toHaveLength(1)); + + act(() => { + fakeWatch.emit({ + type: "modify", + path: "/root/a.ts", + timestamp: 1, + }); + }); + + expect(result.current.dirtyPaths.has("/root/a.ts")).toBe(true); + }); + }); }); diff --git a/apps/desktop/src/renderer/src/global.d.ts b/apps/desktop/src/renderer/src/global.d.ts index 8b094ff8..28f273ad 100644 --- a/apps/desktop/src/renderer/src/global.d.ts +++ b/apps/desktop/src/renderer/src/global.d.ts @@ -1,5 +1,4 @@ import type { PiDesktopApi } from "@pi-desktop/shared"; -import type { FsWatchFn } from "@/lib/file-watcher/file-watcher-stream"; declare global { interface Window { @@ -11,9 +10,6 @@ declare global { install(): Promise | unknown; subscribe(listener: (state: unknown) => void): () => void; }; - fs: PiDesktopApi["fs"] & { - watch?: FsWatchFn; - }; }; } } diff --git a/apps/desktop/src/renderer/src/lib/file-watcher/file-watcher-bridge.ts b/apps/desktop/src/renderer/src/lib/file-watcher/file-watcher-bridge.ts index e71caac4..d847facf 100644 --- a/apps/desktop/src/renderer/src/lib/file-watcher/file-watcher-bridge.ts +++ b/apps/desktop/src/renderer/src/lib/file-watcher/file-watcher-bridge.ts @@ -112,7 +112,5 @@ export function createFileWatcherBridge( } export function isNativeWatchAvailable(): boolean { - // TODO: add `watch` to shared fs type once the IPC channel is implemented - const desc = Object.getOwnPropertyDescriptor(window.piDesktop.fs, "watch"); - return typeof desc?.value === "function"; + return typeof window.piDesktop?.fs?.watch === "function"; } diff --git a/apps/desktop/src/renderer/src/lib/file-watcher/file-watcher-stream.ts b/apps/desktop/src/renderer/src/lib/file-watcher/file-watcher-stream.ts index d68f9d67..7846737b 100644 --- a/apps/desktop/src/renderer/src/lib/file-watcher/file-watcher-stream.ts +++ b/apps/desktop/src/renderer/src/lib/file-watcher/file-watcher-stream.ts @@ -30,12 +30,14 @@ function invokeNativeWatch( workspacePath: string, onEvent: (event: FileChangeEvent) => void, ): (() => void) | null { - // TODO: replace with window.piDesktop.fs.watch once the IPC channel is implemented - const desc = Object.getOwnPropertyDescriptor(window.piDesktop.fs, "watch"); - if (typeof desc?.value !== "function") { + // `window.piDesktop.fs.watch` is backed by the typed `fs:watch` / + // `fs:changed` IPC contracts; the main process watches the workspace + // recursively and pushes change events back to this window. + const watchFn = window.piDesktop?.fs?.watch; + if (typeof watchFn !== "function") { return null; } - const result = desc.value(workspacePath, onEvent); + const result = watchFn(workspacePath, onEvent); return typeof result === "function" ? result : null; } From 5cdd3a51201313ff5c13439a82fac73fcc9a2213 Mon Sep 17 00:00:00 2001 From: Tan <102767855+tanRdev@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:36:33 -0500 Subject: [PATCH 3/4] feat(desktop): wire command-palette Git actions to the Git controller (#8) --- .../features/command-palette/git-commands.ts | 7 +- .../workspace/git-palette-bridge.spec.ts | 162 ++++++++++++++++++ .../features/workspace/git-palette-bridge.ts | 130 ++++++++++++++ .../workspace/use-app-shell-controller.ts | 6 + .../workspace/use-workspace-windows.ts | 12 ++ 5 files changed, 314 insertions(+), 3 deletions(-) create mode 100644 apps/desktop/src/renderer/src/features/workspace/git-palette-bridge.spec.ts create mode 100644 apps/desktop/src/renderer/src/features/workspace/git-palette-bridge.ts diff --git a/apps/desktop/src/renderer/src/features/command-palette/git-commands.ts b/apps/desktop/src/renderer/src/features/command-palette/git-commands.ts index 82ac81d7..f827452f 100644 --- a/apps/desktop/src/renderer/src/features/command-palette/git-commands.ts +++ b/apps/desktop/src/renderer/src/features/command-palette/git-commands.ts @@ -2,9 +2,10 @@ import type { Command } from "./command-registry"; import { registerCommand } from "./command-registry"; /** - * Git commands. These dispatch `pi:git:*` events on `window` so the git - * surface (sidebar, status panel, commit composer) can react. The palette - * itself stays decoupled from git state. + * Git commands. These dispatch `pi:git:*` events on `window` so the palette + * itself stays decoupled from git state. The receiving end is + * `git-palette-bridge.ts` (mounted by the app-shell controller), which maps + * each event to the live workspace Git controller. */ const GROUP = "Git"; diff --git a/apps/desktop/src/renderer/src/features/workspace/git-palette-bridge.spec.ts b/apps/desktop/src/renderer/src/features/workspace/git-palette-bridge.spec.ts new file mode 100644 index 00000000..b86ace26 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/workspace/git-palette-bridge.spec.ts @@ -0,0 +1,162 @@ +// @vitest-environment jsdom +import type { GitRepositoryStatus } from "@pi-desktop/shared"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createWorktree } from "../../../../test/factories"; +import { + bindGitPaletteActions, + runGitPaletteAction, +} from "./git-palette-bridge"; +import type { WorkspaceGitController } from "./use-workspace-git"; + +function makeController( + overrides: Partial = {}, +): WorkspaceGitController { + const status: GitRepositoryStatus = { + repositoryPath: "/tmp/repo", + branch: "main", + commit: "abc1234", + upstreamBranch: "origin/main", + summary: createWorktree().git, + stagedChanges: [ + { + path: "staged.ts", + status: "modified", + indexStatus: "modified", + worktreeStatus: null, + }, + ], + unstagedChanges: [ + { + path: "dirty.ts", + status: "modified", + indexStatus: null, + worktreeStatus: "modified", + }, + { + path: "new.ts", + status: "untracked", + indexStatus: null, + worktreeStatus: "untracked", + }, + ], + conflictedChanges: [], + }; + + return { + activeGitRepositoryStatus: status, + gitCommitMessage: "", + setGitCommitMessage: vi.fn(), + refreshGitRepositoryStatus: vi.fn(async () => undefined), + stageGitFile: vi.fn(async () => undefined), + stageAllGitFiles: vi.fn(async () => undefined), + unstageGitFile: vi.fn(async () => undefined), + unstageAllGitFiles: vi.fn(async () => undefined), + discardGitFile: vi.fn(async () => undefined), + commitGitChanges: vi.fn(async () => undefined), + commitAndPushGitChanges: vi.fn(async () => undefined), + pullGitChanges: vi.fn(async () => undefined), + pushGitChanges: vi.fn(async () => undefined), + fetchGitChanges: vi.fn(async () => undefined), + ...overrides, + }; +} + +describe("runGitPaletteAction", () => { + it("stage-all stages every unstaged path from the controller status", async () => { + const controller = makeController(); + await runGitPaletteAction("stage-all", { controller }); + expect(controller.stageAllGitFiles).toHaveBeenCalledWith([ + "dirty.ts", + "new.ts", + ]); + }); + + it("unstage-all unstages every staged path from the controller status", async () => { + const controller = makeController(); + await runGitPaletteAction("unstage-all", { controller }); + expect(controller.unstageAllGitFiles).toHaveBeenCalledWith(["staged.ts"]); + }); + + it("focus-commit commits when a commit message is present", async () => { + const controller = makeController({ gitCommitMessage: "feat: thing" }); + const onShowGitSurface = vi.fn(); + await runGitPaletteAction("focus-commit", { + controller, + surface: { onShowGitSurface }, + }); + expect(controller.commitGitChanges).toHaveBeenCalledTimes(1); + expect(onShowGitSurface).not.toHaveBeenCalled(); + }); + + it("focus-commit surfaces the composer when the message is empty", async () => { + const controller = makeController({ gitCommitMessage: " " }); + const onShowGitSurface = vi.fn(); + await runGitPaletteAction("focus-commit", { + controller, + surface: { onShowGitSurface }, + }); + expect(controller.commitGitChanges).not.toHaveBeenCalled(); + expect(onShowGitSurface).toHaveBeenCalledTimes(1); + }); + + it("pull and push call the controller", async () => { + const controller = makeController(); + await runGitPaletteAction("pull", { controller }); + await runGitPaletteAction("push", { controller }); + expect(controller.pullGitChanges).toHaveBeenCalledTimes(1); + expect(controller.pushGitChanges).toHaveBeenCalledTimes(1); + }); + + it("show-diff surfaces the Git panel", async () => { + const controller = makeController(); + const onShowGitSurface = vi.fn(); + await runGitPaletteAction("show-diff", { + controller, + surface: { onShowGitSurface }, + }); + expect(onShowGitSurface).toHaveBeenCalledTimes(1); + }); + + it("stage-all is a no-op when there is no repository status", async () => { + const controller = makeController({ activeGitRepositoryStatus: null }); + await runGitPaletteAction("stage-all", { controller }); + expect(controller.stageAllGitFiles).toHaveBeenCalledWith([]); + }); +}); + +describe("bindGitPaletteActions", () => { + let unbind: (() => void) | undefined; + + afterEach(() => { + unbind?.(); + unbind = undefined; + }); + + it("dispatches pi:git:* window events to the current controller", async () => { + const controller = makeController(); + unbind = bindGitPaletteActions(() => ({ controller })); + + window.dispatchEvent(new CustomEvent("pi:git:pull")); + window.dispatchEvent(new CustomEvent("pi:git:stage-all")); + + await vi.waitFor(() => { + expect(controller.pullGitChanges).toHaveBeenCalledTimes(1); + expect(controller.stageAllGitFiles).toHaveBeenCalledWith([ + "dirty.ts", + "new.ts", + ]); + }); + }); + + it("stops dispatching after unbind", async () => { + const controller = makeController(); + unbind = bindGitPaletteActions(() => ({ controller })); + unbind(); + unbind = undefined; + + window.dispatchEvent(new CustomEvent("pi:git:push")); + await Promise.resolve(); + + expect(controller.pushGitChanges).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/desktop/src/renderer/src/features/workspace/git-palette-bridge.ts b/apps/desktop/src/renderer/src/features/workspace/git-palette-bridge.ts new file mode 100644 index 00000000..e33668c2 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/workspace/git-palette-bridge.ts @@ -0,0 +1,130 @@ +import * as React from "react"; +import type { WorkspaceGitController } from "./use-workspace-git"; + +/** + * Bridge between the command palette's Git commands and the workspace Git + * controller. + * + * The palette stays decoupled from git state: `git-commands.ts` dispatches + * `pi:git:*` window events. This module is the receiving end — it maps each + * event to the matching {@link WorkspaceGitController} method so palette + * actions actually stage, unstage, commit, pull, and push instead of + * dispatching into the void. + * + * - `stage-all` stages every path in the status' unstaged changes (the same + * set the Git panel's "stage all" button uses). + * - `unstage-all` unstages every path in the staged changes. + * - `focus-commit` commits with the current composer message when one is + * present (the controller itself no-ops without a message, mirroring the + * panel's disabled Commit button); with an empty message it asks the host + * to surface the commit composer instead. + * - `show-diff` has no controller method — diffs are rendered by the Git + * panel — so it asks the host to surface the Git panel. + */ + +export type GitPaletteAction = + | "stage-all" + | "unstage-all" + | "focus-commit" + | "pull" + | "push" + | "show-diff"; + +export interface GitPaletteSurfaceHandlers { + /** Bring the Git panel (commit composer / diff viewer) to the front. */ + onShowGitSurface?: () => void; +} + +export interface GitPaletteBinding { + controller: WorkspaceGitController; + surface?: GitPaletteSurfaceHandlers; +} + +const ACTION_EVENTS: ReadonlyArray = [ + ["pi:git:stage-all", "stage-all"], + ["pi:git:unstage-all", "unstage-all"], + ["pi:git:focus-commit", "focus-commit"], + ["pi:git:pull", "pull"], + ["pi:git:push", "push"], + ["pi:git:show-diff", "show-diff"], +]; + +export async function runGitPaletteAction( + action: GitPaletteAction, + binding: GitPaletteBinding, +): Promise { + const { controller, surface } = binding; + switch (action) { + case "stage-all": { + const paths = + controller.activeGitRepositoryStatus?.unstagedChanges.map( + (change) => change.path, + ) ?? []; + await controller.stageAllGitFiles(paths); + return; + } + case "unstage-all": { + const paths = + controller.activeGitRepositoryStatus?.stagedChanges.map( + (change) => change.path, + ) ?? []; + await controller.unstageAllGitFiles(paths); + return; + } + case "focus-commit": { + if (controller.gitCommitMessage.trim().length > 0) { + await controller.commitGitChanges(); + } else { + surface?.onShowGitSurface?.(); + } + return; + } + case "pull": { + await controller.pullGitChanges(); + return; + } + case "push": { + await controller.pushGitChanges(); + return; + } + case "show-diff": { + surface?.onShowGitSurface?.(); + return; + } + } +} + +/** + * Subscribe to the palette's `pi:git:*` events on `target` and dispatch them + * to the binding resolved at event time (so status/message changes are + * always current). Returns an unsubscribe function. + */ +export function bindGitPaletteActions( + resolveBinding: () => GitPaletteBinding, + target: Window = window, +): () => void { + const registrations = ACTION_EVENTS.map(([eventName, action]) => { + const listener = () => { + void runGitPaletteAction(action, resolveBinding()); + }; + target.addEventListener(eventName, listener); + return { eventName, listener }; + }); + + return () => { + for (const { eventName, listener } of registrations) { + target.removeEventListener(eventName, listener); + } + }; +} + +/** React binding for {@link bindGitPaletteActions}; binds once on mount. */ +export function useGitPaletteActions( + controller: WorkspaceGitController, + surface?: GitPaletteSurfaceHandlers, +): void { + const bindingRef = React.useRef({ controller, surface }); + bindingRef.current = { controller, surface }; + + React.useEffect(() => bindGitPaletteActions(() => bindingRef.current), []); +} diff --git a/apps/desktop/src/renderer/src/features/workspace/use-app-shell-controller.ts b/apps/desktop/src/renderer/src/features/workspace/use-app-shell-controller.ts index 823ef959..fe658b03 100644 --- a/apps/desktop/src/renderer/src/features/workspace/use-app-shell-controller.ts +++ b/apps/desktop/src/renderer/src/features/workspace/use-app-shell-controller.ts @@ -11,6 +11,7 @@ import { useAppDialogs, } from "@/app-shell/use-app-dialogs"; import type { WorkspaceShellProps } from "@/features/workspace/components/workspace-shell"; +import { useGitPaletteActions } from "@/features/workspace/git-palette-bridge"; import { useWorkspaceGit, type WorkspaceGitController, @@ -166,6 +167,11 @@ export function useAppShellController(): AppShellController { handleFileTreeRenameFile, handleFileTreeMoveFile, } = workspaceWindows; + // Command-palette Git actions (`pi:git:*` events) run against the live + // workspace Git controller. + useGitPaletteActions(workspaceGit, { + onShowGitSurface: workspaceWindows.handleShowGitSurface, + }); const workspaceTreeActions = useWorkspaceTreeActions({ repositories, activeRepository, diff --git a/apps/desktop/src/renderer/src/features/workspace/use-workspace-windows.ts b/apps/desktop/src/renderer/src/features/workspace/use-workspace-windows.ts index 7a35b447..c0e59998 100644 --- a/apps/desktop/src/renderer/src/features/workspace/use-workspace-windows.ts +++ b/apps/desktop/src/renderer/src/features/workspace/use-workspace-windows.ts @@ -38,6 +38,8 @@ export interface WorkspaceWindowsController { handleCloseFileWindow: (windowId: string) => void; handleToggleTerminal: () => void; handleOpenGit: () => void; + /** Open/focus the Git surface without toggling it shut when already open. */ + handleShowGitSurface: () => void; handleFileContentChange: (windowId: string, newContent: string) => void; handleFileSave: (windowId: string, filePath: string) => Promise; handleFileTreeFileSelect: (filePath: string) => Promise; @@ -187,6 +189,15 @@ export function useWorkspaceWindows({ windows, ]); + const handleShowGitSurface = React.useCallback(() => { + const gitSurfaceSelected = contextWindows.some( + (window) => window.kind === "git" && window.id === selectedContextSurface, + ); + if (!gitSurfaceSelected) { + handleOpenGit(); + } + }, [contextWindows, selectedContextSurface, handleOpenGit]); + const handleFileContentChange = React.useCallback( (windowId: string, newContent: string) => { updateFileDraftForWorktree({ @@ -283,6 +294,7 @@ export function useWorkspaceWindows({ handleCloseFileWindow, handleToggleTerminal, handleOpenGit, + handleShowGitSurface, handleFileContentChange, handleFileSave, handleFileTreeFileSelect, From f832685f2518abc0f707dbc8ffd64f1860ebd479 Mon Sep 17 00:00:00 2001 From: Tan <102767855+tanRdev@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:36:38 -0500 Subject: [PATCH 4/4] chore: bump file-size baseline for file-tree panel and app-shell controller (#8) --- scripts/file-size-baseline.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/file-size-baseline.json b/scripts/file-size-baseline.json index 376720ad..7909acdc 100644 --- a/scripts/file-size-baseline.json +++ b/scripts/file-size-baseline.json @@ -29,7 +29,7 @@ "apps/desktop/src/renderer/src/features/workspace/components/chat-thread-transcript.tsx": 244, "apps/desktop/src/renderer/src/features/workspace/components/file-tree-context-menu.tsx": 228, "apps/desktop/src/renderer/src/features/workspace/components/file-tree-item.tsx": 233, - "apps/desktop/src/renderer/src/features/workspace/components/file-tree-panel.tsx": 392, + "apps/desktop/src/renderer/src/features/workspace/components/file-tree-panel.tsx": 397, "apps/desktop/src/renderer/src/features/workspace/components/git-diff-viewer.tsx": 307, "apps/desktop/src/renderer/src/features/workspace/components/git-panel-change-list.tsx": 311, "apps/desktop/src/renderer/src/features/workspace/components/git-panel-model.ts": 385, @@ -45,7 +45,7 @@ "apps/desktop/src/renderer/src/features/workspace/components/workspace-shell-layout-props.tsx": 274, "apps/desktop/src/renderer/src/features/workspace/components/workspace-shell-main-pane.tsx": 217, "apps/desktop/src/renderer/src/features/workspace/components/workspace-shell.tsx": 374, - "apps/desktop/src/renderer/src/features/workspace/use-app-shell-controller.ts": 460, + "apps/desktop/src/renderer/src/features/workspace/use-app-shell-controller.ts": 464, "apps/desktop/src/renderer/src/features/workspace/use-file-tree.ts": 374, "apps/desktop/src/renderer/src/features/workspace/use-workspace-prompt.ts": 430, "apps/desktop/src/renderer/src/lib/perf/perf-overlay.tsx": 258,