Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<bucket>/<repository>` 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
Expand Down Expand Up @@ -331,6 +339,7 @@ picker to return to input selection, then `Esc` again to close rewind.
/tasks message <id> <text> send guidance to a running background agent
/tasks resume <id> [text] resume a stopped or failed background agent
/tasks stop <id> stop a running background task
/worktree list and open managed Git Worktrees
/search <text> search retained transcript blocks
/search next|prev|clear navigate or close transcript search
/transcript latest select the latest transcript block
Expand Down
77 changes: 75 additions & 2 deletions packages/zcode-tui/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -1528,6 +1529,7 @@ class ZCodeTui {
argumentHint: "[message|resume|stop <task-id>]"
},
{ 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" },
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -5400,6 +5431,45 @@ class ZCodeTui {
await this.submit(`/resume ${selected.value}`);
}

private async showManagedWorktrees(): Promise<void> {
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<void> {
while (true) {
await this.refreshRuntimeState();
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down
12 changes: 12 additions & 0 deletions packages/zcode-tui/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<SkillSuggestionResult>;

export type ListPluginReferences = () => Promise<unknown>;
Expand Down Expand Up @@ -129,6 +138,9 @@ export interface RuntimeAdapter {
stopWorkflow?: (options: { runId: string }) => Promise<unknown>;
subscribeWorkflowEvents?: (listener: (event: unknown) => void) => (() => void) | void;
subscribeSessionEvents?: (listener: (event: unknown) => void | Promise<void>) => (() => void) | void;
createManagedWorktree?: (directory: string) => Promise<TuiManagedWorktree>;
listManagedWorktrees?: (directory: string) => Promise<TuiManagedWorktree[]>;
restartTuiAtDirectory?: (directory: string) => void;
}

export interface TuiOptions extends RuntimeAdapter {
Expand Down
27 changes: 27 additions & 0 deletions scripts/sync-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(")
Expand All @@ -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)
Expand Down Expand Up @@ -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})}`;
Expand Down Expand Up @@ -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`);
}
Expand Down
1 change: 1 addition & 0 deletions src/runtime-config-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Loading
Loading