From 6e1c628ee7446f74135deb085cc95b67871a3450 Mon Sep 17 00:00:00 2001 From: Kingsword Date: Tue, 24 Nov 2026 16:53:03 +0800 Subject: [PATCH] feat(tui): start sessions in managed worktrees --- README.md | 9 + packages/zcode-tui/src/index.ts | 77 +++++++- packages/zcode-tui/src/types.ts | 12 ++ scripts/sync-runtime.ts | 27 +++ src/runtime-config-bridge.ts | 1 + src/runtime-worktrees.ts | 243 +++++++++++++++++++++++++ test/runtime/session-lifecycle.test.ts | 2 + test/runtime/worktrees.test.ts | 88 +++++++++ test/tui/fixtures/worktree.ts | 33 ++++ test/tui/worktree.test.ts | 46 +++++ 10 files changed, 536 insertions(+), 2 deletions(-) create mode 100644 src/runtime-worktrees.ts create mode 100644 test/runtime/worktrees.test.ts create mode 100644 test/tui/fixtures/worktree.ts create mode 100644 test/tui/worktree.test.ts diff --git a/README.md b/README.md index 869f3801..0c46ea09 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,14 @@ with Ctrl+O, then press Enter to resume. Both pickers use the runtime's configur session database, including `storage.sessionDbPath` and `ZCODE_SESSION_DB_PATH` overrides. Cross-directory resumes update the displayed workspace and Git branch, file completion and `/diff` to follow the restored session's working directory. +`/new` lets you start in the current checkout or create a detached Worktree at +`.zcode/worktrees//` and start a fresh session there. The +four-character hexadecimal bucket follows ZCode Desktop's managed Worktree +layout. If the project does not already ignore `.zcode/worktrees/`, the CLI adds +a repository-local rule to `.git/info/exclude`. The new Worktree starts at the +current `HEAD`, maps a monorepo subdirectory to its matching path, and does not +copy uncommitted or ignored files. `/worktree` lists managed Worktrees for the +repository and opens a selected one in a new session. **Login and permissions.** `/login` setup choices with masked API-key entry, redacted transcript/history and OAuth waiting state; suspended Z.AI browser @@ -331,6 +339,7 @@ picker to return to input selection, then `Esc` again to close rewind. /tasks message send guidance to a running background agent /tasks resume [text] resume a stopped or failed background agent /tasks stop stop a running background task +/worktree list and open managed Git Worktrees /search search retained transcript blocks /search next|prev|clear navigate or close transcript search /transcript latest select the latest transcript block diff --git a/packages/zcode-tui/src/index.ts b/packages/zcode-tui/src/index.ts index b39f742f..4b8c1466 100644 --- a/packages/zcode-tui/src/index.ts +++ b/packages/zcode-tui/src/index.ts @@ -271,7 +271,7 @@ import { } from "./turn-status.ts"; import { TurnPresentationRegistry } from "./turn-presentation-registry.ts"; import { TurnWorkTracker } from "./turn-work-tracker.ts"; -import { asString, isRecord, type PromptCallOptions, type TuiOptions } from "./types.ts"; +import { asString, isRecord, type PromptCallOptions, type TuiManagedWorktree, type TuiOptions } from "./types.ts"; import { UpdateAvailableView, updateCommand } from "./update-available-view.ts"; import { FullscreenHeader, @@ -702,6 +702,7 @@ class ZCodeTui { private currentToolGroupBlockId?: string; private currentToolGroupMessageId?: string; private pendingAttachments: PromptImageAttachment[] = []; + private pendingRestartDirectory?: string; private readonly editorHistory: string[] = []; private mode: string; private planEnabled = false; @@ -1528,6 +1529,7 @@ class ZCodeTui { argumentHint: "[message|resume|stop ]" }, { name: "diff", description: "Browse current and per-turn file changes" }, + { name: "worktree", description: "Open a managed Git Worktree in a new session" }, { name: "sessions", description: "Browse and resume past sessions (desktop and CLI)" }, { name: "context", description: "Inspect context usage and prompt composition" }, { name: "status", description: "Inspect detailed runtime and session status" }, @@ -1840,6 +1842,35 @@ class ZCodeTui { this.addNotice("Wait for the active turn or press Ctrl+C before running a slash command.", "warning"); return; } + if (input === "/new" && this.options.createManagedWorktree && this.options.restartTuiAtDirectory) { + const choice = await this.showChoice({ + title: "Start a new session", + prompt: "Choose where the new session should run.", + help: "Up/Down choose · Enter confirm · Esc cancel", + items: [ + { value: "checkout", label: "Current checkout", description: "Start in the current project directory" }, + { value: "worktree", label: "New Worktree", description: "Create an isolated checkout from the current HEAD" } + ] + }); + if (!choice) return false; + if (choice.value === "worktree") { + try { + this.addNotice("Creating a detached Worktree from the current HEAD…", "muted"); + this.ui.requestRender(true); + const worktree = await this.options.createManagedWorktree(this.workspaceDirectory); + this.pendingRestartDirectory = worktree.cwd ?? worktree.path; + this.addNotice(`Starting a new session in Worktree ${worktree.bucket}.`, "muted"); + this.stop(); + } catch (error) { + this.addNotice(error instanceof Error ? error.message : String(error), "error"); + } + return false; + } + } + if (input === "/worktree" || input === "/worktree list") { + await this.showManagedWorktrees(); + return; + } if (input === "/context") { await this.showContextDetails(); return; @@ -5400,6 +5431,45 @@ class ZCodeTui { await this.submit(`/resume ${selected.value}`); } + private async showManagedWorktrees(): Promise { + if (!this.options.listManagedWorktrees || !this.options.restartTuiAtDirectory) { + this.addNotice("Managed Worktrees are unavailable in this runtime.", "muted"); + return; + } + let worktrees: TuiManagedWorktree[]; + try { + worktrees = await this.options.listManagedWorktrees(this.workspaceDirectory); + } catch (error) { + this.addNotice(error instanceof Error ? error.message : String(error), "error"); + return; + } + if (worktrees.length === 0) { + this.addNotice("No managed Worktrees in this repository. Use /new to create one.", "muted"); + return; + } + const selected = await this.showChoice({ + title: "Managed Worktrees", + prompt: "Select a Worktree to open in a new session.", + help: "Up/Down choose · Enter open · Esc cancel", + items: worktrees.map((worktree) => ({ + value: worktree.bucket, + label: `Worktree ${worktree.bucket}`, + description: [ + worktree.branch ?? `detached at ${worktree.head.slice(0, 7)}`, + worktree.dirty ? "uncommitted changes" : "clean" + ].join(" · "), + preview: new Text(worktree.path, 1, 0), + payload: worktree + })) + }); + if (!selected) return; + const worktree = selected.payload as TuiManagedWorktree | undefined; + if (!worktree) return; + this.pendingRestartDirectory = worktree.cwd ?? worktree.path; + this.addNotice(`Starting a new session in Worktree ${worktree.bucket}.`, "muted"); + this.stop(); + } + private async showBackgroundTasks(): Promise { while (true) { await this.refreshRuntimeState(); @@ -6413,7 +6483,7 @@ class ZCodeTui { sessionId: resumeTarget, width: this.ui.terminal.columns }); - const lines = [ + const lines = this.pendingRestartDirectory ? [] : [ summary.divider && this.theme.muted(summary.divider), summary.tokenUsage, summary.resumeCommand @@ -6427,6 +6497,9 @@ class ZCodeTui { // Exit diagnostics must not prevent terminal cleanup. } } + if (this.pendingRestartDirectory) { + this.options.restartTuiAtDirectory?.(this.pendingRestartDirectory); + } } catch { // Exit diagnostics are supplementary; terminal cleanup is authoritative. } finally { diff --git a/packages/zcode-tui/src/types.ts b/packages/zcode-tui/src/types.ts index ccdc19e4..0edf1bab 100644 --- a/packages/zcode-tui/src/types.ts +++ b/packages/zcode-tui/src/types.ts @@ -68,6 +68,15 @@ export interface SkillSuggestionResult { totalDiscovered?: number; } +export interface TuiManagedWorktree { + bucket: string; + path: string; + cwd?: string; + branch?: string; + head: string; + dirty: boolean; +} + export type ListSkills = () => Promise; export type ListPluginReferences = () => Promise; @@ -129,6 +138,9 @@ export interface RuntimeAdapter { stopWorkflow?: (options: { runId: string }) => Promise; subscribeWorkflowEvents?: (listener: (event: unknown) => void) => (() => void) | void; subscribeSessionEvents?: (listener: (event: unknown) => void | Promise) => (() => void) | void; + createManagedWorktree?: (directory: string) => Promise; + listManagedWorktrees?: (directory: string) => Promise; + restartTuiAtDirectory?: (directory: string) => void; } export interface TuiOptions extends RuntimeAdapter { diff --git a/scripts/sync-runtime.ts b/scripts/sync-runtime.ts index bd20975a..e2443391 100755 --- a/scripts/sync-runtime.ts +++ b/scripts/sync-runtime.ts @@ -612,6 +612,9 @@ export function patchRuntimeTuiBridge(runtime: string): string { && runtime.includes(".readCustomSessionTitle=async()=>") && runtime.includes(".readSessionResumeTarget=async()=>") && runtime.includes(".readSessionDatabasePath=async()=>") + && runtime.includes(".createManagedWorktree=async $zDirectory=>") + && runtime.includes(".listManagedWorktrees=async $zDirectory=>") + && runtime.includes(".restartTuiAtDirectory=$zDirectory=>") && runtime.includes(interruptTurnMarker) && runtime.includes(interruptWaitForIdleMarker) && runtime.includes(".promoteQueuedInput=async(") @@ -633,6 +636,9 @@ export function patchRuntimeTuiBridge(runtime: string): string { && /readCustomSessionTitle:[A-Za-z_$][\w$]*\.readCustomSessionTitle/u.test(runtime) && /readSessionResumeTarget:[A-Za-z_$][\w$]*\.readSessionResumeTarget/u.test(runtime) && /readSessionDatabasePath:[A-Za-z_$][\w$]*\.readSessionDatabasePath/u.test(runtime) + && /createManagedWorktree:[A-Za-z_$][\w$]*\.createManagedWorktree/u.test(runtime) + && /listManagedWorktrees:[A-Za-z_$][\w$]*\.listManagedWorktrees/u.test(runtime) + && /restartTuiAtDirectory:[A-Za-z_$][\w$]*\.restartTuiAtDirectory/u.test(runtime) && /interruptTurn:[A-Za-z_$][\w$]*\.interruptTurn/u.test(runtime) && /promoteQueuedInput:[A-Za-z_$][\w$]*\.promoteQueuedInput/u.test(runtime) && /readSessionUsage:[A-Za-z_$][\w$]*\.readSessionUsage/u.test(runtime) @@ -775,6 +781,18 @@ export function patchRuntimeTuiBridge(runtime: string): string { // so register tasks from the native session/subagent read model. Its candidate // selection handles the active branch and its reducer owns lifecycle state. const helper = 'require(require("node:path").join(__dirname,"cli-config.cjs"))'; + const managedWorktreeMarker = ".createManagedWorktree=async $zDirectory=>"; + const listManagedWorktreesMarker = ".listManagedWorktrees=async $zDirectory=>"; + const restartTuiMarker = ".restartTuiAtDirectory=$zDirectory=>"; + if (!patched.includes(managedWorktreeMarker)) { + assignments.push(`${bridge}${managedWorktreeMarker}await ${helper}.createManagedWorktree($zDirectory)`); + } + if (!patched.includes(listManagedWorktreesMarker)) { + assignments.push(`${bridge}${listManagedWorktreesMarker}await ${helper}.listManagedWorktrees($zDirectory)`); + } + if (!patched.includes(restartTuiMarker)) { + assignments.push(`${bridge}${restartTuiMarker}${helper}.restartTuiAtDirectory($zDirectory)`); + } const queries = runtimeSubagentQueryBridge(runtime); const guardedBackgroundRestoreAssignment = `${bridge}.$zRestorePersistedBackgroundTasks=async $zApp=>await ${helper}.restoreTuiBackgroundTasks($zApp,${queries})`; const projectionAssignment = `${bridge}.readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await ${getApp}();return await ${helper}.readTuiRuntimeProjection($zRuntimeProjectionBridge,${bridge})}`; @@ -994,6 +1012,15 @@ export function patchRuntimeTuiBridge(runtime: string): string { if (!/readSessionDatabasePath:[A-Za-z_$][\w$]*\.readSessionDatabasePath/u.test(patched)) { optionFields.push(`readSessionDatabasePath:${submitBridge}.readSessionDatabasePath`); } + if (!/createManagedWorktree:[A-Za-z_$][\w$]*\.createManagedWorktree/u.test(patched)) { + optionFields.push(`createManagedWorktree:${submitBridge}.createManagedWorktree`); + } + if (!/listManagedWorktrees:[A-Za-z_$][\w$]*\.listManagedWorktrees/u.test(patched)) { + optionFields.push(`listManagedWorktrees:${submitBridge}.listManagedWorktrees`); + } + if (!/restartTuiAtDirectory:[A-Za-z_$][\w$]*\.restartTuiAtDirectory/u.test(patched)) { + optionFields.push(`restartTuiAtDirectory:${submitBridge}.restartTuiAtDirectory`); + } if (!/interruptTurn:[A-Za-z_$][\w$]*\.interruptTurn/u.test(patched)) { optionFields.push(`interruptTurn:${submitBridge}.interruptTurn`); } diff --git a/src/runtime-config-bridge.ts b/src/runtime-config-bridge.ts index 7c21cb85..47986af1 100644 --- a/src/runtime-config-bridge.ts +++ b/src/runtime-config-bridge.ts @@ -7,6 +7,7 @@ import { cliSettingsPath, desktopSettingsPath, legacyCliConfigPath, providerConf export { assertSessionModelReady, readSessionModelState } from "./session-model-recovery.ts"; export { assertResumableSession, ensureSessionForTitle, listSessionsForPicker, readSessionDatabasePath, readSessionResumeTarget } from "./runtime-session-lifecycle.ts"; export { readTuiRuntimeProjection, sendTuiBackgroundTaskMessage } from "./runtime-tui-bridge.ts"; +export { createManagedWorktree, listManagedWorktrees, restartTuiAtDirectory } from "./runtime-worktrees.ts"; export { createTuiWorkflowManagement, startTuiSavedWorkflow } from "./runtime-workflow-bridge.ts"; export { restoreTuiBackgroundTasks } from "./runtime-background-restore.ts"; export { withRecursiveWorkspacePathSuggestions } from "./runtime-workspace-paths.ts"; diff --git a/src/runtime-worktrees.ts b/src/runtime-worktrees.ts new file mode 100644 index 00000000..70f6201f --- /dev/null +++ b/src/runtime-worktrees.ts @@ -0,0 +1,243 @@ +import { randomBytes } from "node:crypto"; +import { appendFile, lstat, mkdir, readFile, realpath, rm } from "node:fs/promises"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { execFile, spawn } from "node:child_process"; +import { promisify } from "node:util"; + +const execFileAsync = promisify(execFile); +const managedDirectory = ".zcode/worktrees"; +const bucketPattern = /^[0-9a-f]{4}$/u; +const bucketAttempts = 64; + +export interface ManagedWorktree { + bucket: string; + path: string; + cwd?: string; + branch?: string; + head: string; + dirty: boolean; +} + +async function git(directory: string, args: string[]): Promise { + const { stdout } = await execFileAsync("git", args, { + cwd: directory, + timeout: 10 * 60_000, + maxBuffer: 8 * 1024 * 1024, + windowsHide: true, + env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" } + }); + return stdout; +} + +async function repositoryRoot(directory: string): Promise { + const checkout = (await git(directory, ["rev-parse", "--show-toplevel"])).trim(); + if (!checkout) throw new Error("The current directory is not inside a Git repository."); + const worktrees = parseWorktreeRecords(await git(checkout, ["worktree", "list", "--porcelain", "-z"])); + for (const record of worktrees.values()) { + try { + return await realpath(record.worktree); + } catch { + // The original checkout may have been removed while another Worktree remains. + } + } + throw new Error("Unable to find an existing Git checkout."); +} + +async function relativeWorkspaceDirectory(directory: string): Promise { + const checkout = await realpath((await git(directory, ["rev-parse", "--show-toplevel"])).trim()); + const workspace = await realpath(directory); + const relativePath = relative(checkout, workspace); + if (relativePath === ".." || relativePath.startsWith(`..${sep}`) || relativePath.startsWith(sep)) { + throw new Error("The active session directory is outside its Git checkout."); + } + return relativePath; +} + +async function assertIgnored(root: string): Promise { + const managedPath = `${managedDirectory}/`; + try { + await git(root, ["check-ignore", "--quiet", "--", managedPath]); + return; + } catch (error) { + if (!error || typeof error !== "object" || !("code" in error) || error.code !== 1) throw error; + } + + const excludePath = (await git(root, ["rev-parse", "--git-path", "info/exclude"])).trim(); + const excludeFile = isAbsolute(excludePath) ? excludePath : resolve(root, excludePath); + let current = ""; + try { + if ((await lstat(excludeFile)).isSymbolicLink()) { + throw new Error("Refusing to update a symbolic link at Git's local exclude path."); + } + current = await readFile(excludeFile, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + const rule = "/.zcode/worktrees/"; + if (!current.split(/\r?\n/u).includes(rule)) { + const separator = current && !current.endsWith("\n") ? "\n" : ""; + await mkdir(dirname(excludeFile), { recursive: true }); + await appendFile(excludeFile, `${separator}${rule}\n`); + } + try { + await git(root, ["check-ignore", "--quiet", "--", managedPath]); + } catch (error) { + throw new Error("Unable to ignore the project-local Worktree directory.", { cause: error }); + } +} + +async function ensureManagedRoot(root: string): Promise { + const zcodeDirectory = join(root, ".zcode"); + const managedRoot = join(root, managedDirectory); + for (const directory of [zcodeDirectory, managedRoot]) { + try { + if ((await lstat(directory)).isSymbolicLink()) { + throw new Error(`Refusing to use a symbolic link for ${relative(root, directory)}.`); + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + } + await mkdir(managedRoot, { recursive: true }); + const canonical = await realpath(managedRoot); + const pathFromRoot = relative(root, canonical); + if (pathFromRoot.startsWith(`..${sep}`) || pathFromRoot === ".." || pathFromRoot.startsWith(sep)) { + throw new Error("The managed worktree directory resolves outside the Git repository."); + } + return canonical; +} + +async function allocateBucket(root: string): Promise<{ bucket: string; path: string }> { + for (let attempt = 0; attempt < bucketAttempts; attempt += 1) { + const bucket = randomBytes(2).toString("hex"); + const path = join(root, bucket); + try { + await mkdir(path); + return { bucket, path }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } + } + throw new Error("Unable to allocate a unique Worktree directory after 64 attempts."); +} + +function parseWorktreeRecords(output: string): Map> { + const records = new Map>(); + let current: Record | undefined; + for (const field of output.split("\0")) { + if (!field) { + if (current?.worktree) records.set(current.worktree, current); + current = undefined; + continue; + } + const separator = field.indexOf(" "); + const key = separator < 0 ? field : field.slice(0, separator); + const value = separator < 0 ? "" : field.slice(separator + 1); + current ??= {}; + current[key] = value; + } + if (current?.worktree) records.set(current.worktree, current); + return records; +} + +function bucketForPath(managedRoot: string, worktreePath: string): string | undefined { + const pathFromRoot = relative(managedRoot, worktreePath); + if (!pathFromRoot || pathFromRoot.startsWith(`..${sep}`) || pathFromRoot === "..") return undefined; + const [bucket, name, ...rest] = pathFromRoot.split(sep); + if (!bucket || !name || rest.length > 0 || !bucketPattern.test(bucket)) return undefined; + return bucket; +} + +export async function createManagedWorktree(directory: string): Promise { + const root = await repositoryRoot(directory); + await assertIgnored(root); + const managedRoot = await ensureManagedRoot(root); + const workspace = await relativeWorkspaceDirectory(directory); + const head = (await git(directory, ["rev-parse", "HEAD"])).trim(); + const bucket = await allocateBucket(managedRoot); + const worktreePath = join(bucket.path, basename(root)); + try { + await git(root, ["worktree", "add", "--detach", worktreePath, head]); + const canonicalWorktreePath = await realpath(worktreePath); + const cwd = workspace + ? await realpath(join(canonicalWorktreePath, workspace)) + : canonicalWorktreePath; + return { bucket: bucket.bucket, path: canonicalWorktreePath, cwd, head, dirty: false }; + } catch (error) { + await git(root, ["worktree", "remove", "--force", worktreePath]).catch(() => undefined); + await git(root, ["worktree", "prune"]).catch(() => undefined); + await rm(bucket.path, { recursive: true, force: true }); + throw new Error(`Unable to create Worktree: ${error instanceof Error ? error.message : String(error)}`); + } +} + +export async function listManagedWorktrees(directory: string): Promise { + const root = await repositoryRoot(directory); + const managedRoot = join(root, managedDirectory); + const workspace = await relativeWorkspaceDirectory(directory); + const output = await git(root, ["worktree", "list", "--porcelain", "-z"]); + const records = parseWorktreeRecords(output); + const worktrees: ManagedWorktree[] = []; + for (const record of records.values()) { + const worktreePath = record.worktree; + const bucket = bucketForPath(managedRoot, worktreePath); + if (!bucket || basename(worktreePath) !== basename(root)) continue; + try { + const dotGit = await lstat(join(worktreePath, ".git")); + if (!dotGit.isFile()) continue; + const status = await git(worktreePath, ["status", "--porcelain", "--untracked-files=all"]); + const cwd = workspace + ? await realpath(join(worktreePath, workspace)).catch(() => undefined) + : worktreePath; + worktrees.push({ + bucket, + path: worktreePath, + ...(cwd ? { cwd } : {}), + head: record.HEAD ?? "", + ...(record.branch ? { branch: record.branch.replace(/^refs\/heads\//u, "") } : {}), + dirty: status.length > 0 + }); + } catch { + // A removed or incomplete entry is left for `git worktree prune`. + } + } + return worktrees.sort((left, right) => left.bucket.localeCompare(right.bucket)); +} + +function freshSessionArguments(args: string[]): string[] { + const result: string[] = []; + for (let index = 0; index < args.length; index += 1) { + const argument = args[index]!; + if (argument === "--resume" || argument === "--continue" || argument === "-c") { + if (argument !== "-c" && args[index + 1] && !args[index + 1]!.startsWith("-")) index += 1; + continue; + } + if (argument.startsWith("--resume=") || argument.startsWith("--continue=")) continue; + if (argument === "--cwd") { + if (args[index + 1] && !args[index + 1]!.startsWith("-")) index += 1; + continue; + } + if (argument.startsWith("--cwd=")) continue; + result.push(argument); + } + return result; +} + +/** Starts the extracted runtime in a fresh process so its session cwd is correct. */ +export function restartTuiAtDirectory(directory: string): void { + const runtimePath = process.argv[1]; + if (!runtimePath) throw new Error("Unable to locate the active ZCode runtime entrypoint."); + const args = freshSessionArguments(process.argv.slice(2)); + setTimeout(() => { + const child = spawn(process.execPath, [runtimePath, ...args], { + cwd: directory, + env: process.env, + stdio: "inherit", + windowsHide: true + }); + child.once("error", (error) => { + process.stderr.write(`Unable to start a session in ${directory}: ${error.message}\n`); + }); + child.unref(); + }, 500); +} diff --git a/test/runtime/session-lifecycle.test.ts b/test/runtime/session-lifecycle.test.ts index 2870b650..7a737da1 100644 --- a/test/runtime/session-lifecycle.test.ts +++ b/test/runtime/session-lifecycle.test.ts @@ -315,6 +315,8 @@ test.skipIf(process.platform === "win32").each([ await startup.wait(() => startup.screen.screenText().includes("/workflow-project")); expect(startup.screen.screenText()).not.toContain("resumed-branch"); startup.terminal.write("/new\r"); + await startup.wait(text => text.includes("Start a new session") && text.includes("Current checkout")); + startup.terminal.write("\r"); await startup.wait(() => startup.screen.screenText().includes("/launch-project") && startup.screen.screenText().includes("launch-branch")); expect(startup.screen.screenText()).not.toContain("resumed-branch"); expect(fixture.requests).toEqual([]); diff --git a/test/runtime/worktrees.test.ts b/test/runtime/worktrees.test.ts new file mode 100644 index 00000000..da31ebf7 --- /dev/null +++ b/test/runtime/worktrees.test.ts @@ -0,0 +1,88 @@ +import { expect, test } from "bun:test"; +import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { basename, join } from "node:path"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { createManagedWorktree, listManagedWorktrees } from "../../src/runtime-worktrees.ts"; + +const execFileAsync = promisify(execFile); + +async function git(directory: string, ...args: string[]): Promise { + await execFileAsync("git", ["-C", directory, ...args], { + env: { + ...process.env, + GIT_AUTHOR_NAME: "ZCode Test", + GIT_AUTHOR_EMAIL: "test@example.com", + GIT_COMMITTER_NAME: "ZCode Test", + GIT_COMMITTER_EMAIL: "test@example.com" + } + }); +} + +async function repository(): Promise { + const root = await mkdtemp(join(tmpdir(), "zcode-worktree-")); + await git(root, "init", "-q"); + await writeFile(join(root, ".gitignore"), ".zcode/\n"); + await writeFile(join(root, "README.md"), "fixture\n"); + await mkdir(join(root, "packages", "app"), { recursive: true }); + await writeFile(join(root, "packages", "app", "README.md"), "monorepo fixture\n"); + await git(root, "add", ".gitignore", "README.md", "packages/app/README.md"); + await git(root, "commit", "-qm", "initial commit"); + return root; +} + +test("creates and lists desktop-compatible managed worktrees in the project", async () => { + const root = await repository(); + try { + const worktree = await createManagedWorktree(root); + const canonicalRoot = await realpath(root); + expect(worktree.bucket).toMatch(/^[0-9a-f]{4}$/u); + expect(worktree.path).toBe(join(canonicalRoot, ".zcode", "worktrees", worktree.bucket, basename(canonicalRoot))); + expect(worktree.cwd).toBe(worktree.path); + expect(worktree.path.startsWith(join(canonicalRoot, ".zcode", "worktrees") + "/")).toBe(true); + + const worktrees = await listManagedWorktrees(root); + expect(worktrees).toEqual([worktree]); + expect((await gitRead(root, "status", "--short"))).toBe(""); + + const child = await createManagedWorktree(worktree.path); + expect(child.path).toBe(join(canonicalRoot, ".zcode", "worktrees", child.bucket, basename(canonicalRoot))); + expect(child.cwd).toBe(child.path); + expect((await listManagedWorktrees(worktree.path)).map((entry) => entry.bucket).sort()) + .toEqual([worktree.bucket, child.bucket].sort()); + + expect(new Set((await listManagedWorktrees(root)).map((entry) => entry.bucket))) + .toEqual(new Set([worktree.bucket, child.bucket])); + + const subdirectory = join(root, "packages", "app"); + const nestedWorktree = await createManagedWorktree(subdirectory); + expect(nestedWorktree.cwd).toBe(join(nestedWorktree.path, "packages", "app")); + expect((await listManagedWorktrees(subdirectory)).find((entry) => entry.bucket === nestedWorktree.bucket)?.cwd) + .toBe(nestedWorktree.cwd); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("adds the managed Worktree directory to the local Git exclude file when needed", async () => { + const root = await mkdtemp(join(tmpdir(), "zcode-worktree-unignored-")); + try { + await git(root, "init", "-q"); + await git(root, "commit", "--allow-empty", "-qm", "initial commit"); + await writeFile(join(root, ".git", "info", "exclude"), "local-user-rule\n"); + const worktree = await createManagedWorktree(root); + const exclude = await readFile(join(root, ".git", "info", "exclude"), "utf8"); + expect(exclude).toContain("local-user-rule"); + expect(exclude).toContain("/.zcode/worktrees/"); + expect(await gitRead(root, "status", "--short")).toBe(""); + expect(worktree.path).toContain("/.zcode/worktrees/"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +async function gitRead(directory: string, ...args: string[]): Promise { + const { stdout } = await execFileAsync("git", ["-C", directory, ...args]); + return stdout.trim(); +} diff --git a/test/tui/fixtures/worktree.ts b/test/tui/fixtures/worktree.ts new file mode 100644 index 00000000..5f74fe28 --- /dev/null +++ b/test/tui/fixtures/worktree.ts @@ -0,0 +1,33 @@ +import { appendFileSync } from "node:fs"; +import { runTui } from "../../../packages/zcode-tui/src/index.ts"; + +const record = (entry: unknown) => appendFileSync( + process.env.ZCODE_TUI_SCENARIO_RUNTIME_JOURNAL!, + `${JSON.stringify(entry)}\n` +); + +await runTui({ + initialModel: "scenario/model", + workspaceDirectory: process.cwd(), + loadSessionTranscript: async () => [], + submitPrompt: async (input) => { + record({ kind: "native-command", input: String(input) }); + return { response: "Native command handled" }; + }, + createManagedWorktree: async (directory) => { + record({ kind: "create", directory }); + return { + bucket: "1a2b", + path: `${directory}/.zcode/worktrees/1a2b/${directory.split("/").at(-1)}`, + head: "fixture-head", + dirty: false + }; + }, + listManagedWorktrees: async (directory) => [{ + bucket: "1a2b", + path: `${directory}/.zcode/worktrees/1a2b/${directory.split("/").at(-1)}`, + head: "fixture-head", + dirty: true + }], + restartTuiAtDirectory: (directory) => record({ kind: "restart", directory }) +}); diff --git a/test/tui/worktree.test.ts b/test/tui/worktree.test.ts new file mode 100644 index 00000000..3800d41e --- /dev/null +++ b/test/tui/worktree.test.ts @@ -0,0 +1,46 @@ +import { expect, test } from "bun:test"; +import { join } from "node:path"; +import { ScenarioWorkspace } from "./harness/scenario-workspace.ts"; +import { TerminalSession } from "./harness/terminal-session.ts"; + +const fixture = join(import.meta.dir, "fixtures/worktree.ts"); + +test("/new offers a Worktree and starts the next runtime in its directory", async () => { + await using workspace = await ScenarioWorkspace.create({ prefix: "zcode-worktree-new-" }); + await using session = TerminalSession.start({ command: [process.execPath, fixture], workspace }); + await session.waitForScreen("TUI ready", /scenario\/model/u); + await session.sendAndWait("/new\r", "new session choices", /New Worktree/u); + await session.send("\x1b[B\r"); + await session.exit(); + + const journal = await workspace.readRuntimeJournal(); + expect(journal).toContain('"kind":"create"'); + expect(journal).toContain('"kind":"restart"'); + expect(journal).toContain("/.zcode/worktrees/1a2b/"); +}); + +test("/new can keep using the current checkout", async () => { + await using workspace = await ScenarioWorkspace.create({ prefix: "zcode-worktree-current-" }); + await using session = TerminalSession.start({ command: [process.execPath, fixture], workspace }); + await session.waitForScreen("TUI ready", /scenario\/model/u); + await session.sendAndWait("/new\r", "new session choices", /Current checkout/u); + await session.sendAndWait("\r", "native new session command", /Native command handled/u); + await session.exit(); + + const journal = await workspace.readRuntimeJournal(); + expect(journal).toContain('"kind":"native-command","input":"/new"'); + expect(journal).not.toContain('"kind":"create"'); +}); + +test("/worktree lists the managed Worktree and starts a session there", async () => { + await using workspace = await ScenarioWorkspace.create({ prefix: "zcode-worktree-open-" }); + await using session = TerminalSession.start({ command: [process.execPath, fixture], workspace }); + await session.waitForScreen("TUI ready", /scenario\/model/u); + await session.sendAndWait("/worktree\r", "managed Worktree picker", /Worktree 1a2b/u); + await session.send("\r"); + await session.exit(); + + const journal = await workspace.readRuntimeJournal(); + expect(journal).toContain('"kind":"restart"'); + expect(journal).toContain("/.zcode/worktrees/1a2b/"); +});