Merge workspace: terminals, branches and worktrees, editor, setup
# Conflicts: # src/ui/App.tsx
This commit is contained in:
commit
a932f33857
6 files changed
+473
-40
No files matched your search
@@ -53,6 +53,9 @@ Navigation:
|
|||||||
| `c` | new thread (see below) |
|
| `c` | new thread (see below) |
|
||||||
| `.` | thread actions (see below); a right-click on a thread opens them too |
|
| `.` | thread actions (see below); a right-click on a thread opens them too |
|
||||||
| `m` | model, options (reasoning, fast mode…) and access mode |
|
| `m` | model, options (reasoning, fast mode…) and access mode |
|
||||||
|
| `T` | terminals: attach, new, close or clear |
|
||||||
|
| `b` | branches and worktrees: switch, create, pull or remove |
|
||||||
|
| `E` | open the workspace (or diff file) in the server's editor |
|
||||||
| `y` / `Y` / `n` | approve / always allow this session / decline the pending approval |
|
| `y` / `Y` / `n` | approve / always allow this session / decline the pending approval |
|
||||||
| `1`–`9` | pick an option when the agent asks a question (also in an empty message box) |
|
| `1`–`9` | pick an option when the agent asks a question (also in an empty message box) |
|
||||||
| `x` | dismiss the agent's question, or decline its secret request |
|
| `x` | dismiss the agent's question, or decline its secret request |
|
||||||
@@ -113,6 +116,18 @@ Submenus open as their own list, and typing finds their items from the top (`thr
|
|||||||
|
|
||||||
`ctrl+j` attaches to the thread's terminal on the T3 server, the same one the app's terminal drawer shows. If the thread has none, it starts one in the thread's worktree or project folder; with several, you pick one or start another. tui3 hands the whole screen to the terminal; `ctrl+j` or `ctrl+]` comes back. The terminal keeps running after you detach. The terminal's size is shared, so attaching resizes it for anyone else watching.
|
`ctrl+j` attaches to the thread's terminal on the T3 server, the same one the app's terminal drawer shows. If the thread has none, it starts one in the thread's worktree or project folder; with several, you pick one or start another. tui3 hands the whole screen to the terminal; `ctrl+j` or `ctrl+]` comes back. The terminal keeps running after you detach. The terminal's size is shared, so attaching resizes it for anyone else watching.
|
||||||
|
|
||||||
|
`T` opens the terminal picker even with only one terminal. Choose `New terminal`, `Close terminal…` or `Clear terminal…`; typing `close` or `clear` also finds each terminal's action directly. Closing ends the shell and deletes its history; clearing clears its scrollback. These actions are also in the command palette.
|
||||||
|
|
||||||
|
## Workspace
|
||||||
|
|
||||||
|
`b` opens the web app's ref selector: local and remote refs, existing worktrees, `Create and switch ref…`, and `Pull`. Selecting a ref reuses its worktree if it has one; selecting the default branch returns to the project folder. `Create worktree…` asks for a new branch name and moves this thread there. `Remove worktree…` asks first, detaches this thread's provider session and removes the worktree only if no other thread uses it and Git permits it (no forced deletion). Moving folders detaches the provider session, as in the web app.
|
||||||
|
|
||||||
|
Worktree preparation shows its current stage, percentage and detail above the message box, including failures. `Cancel worktree setup…` in the palette asks first.
|
||||||
|
|
||||||
|
`E` opens the workspace in an editor on the server. In a single-file diff it opens that file; in a whole-tree diff it asks which file. It uses the web app's fallback order among the server's available editors: the browser's last-used editor preference isn't shared with tui3. The pinned RPC has no line argument.
|
||||||
|
|
||||||
|
Server ready/restart, update outcomes and legacy-thread migration events flash on the bottom line. This server version doesn't publish update-available or shutting-down lifecycle events; connection loss uses the existing reconnect status.
|
||||||
|
|
||||||
## Alerts
|
## Alerts
|
||||||
|
|
||||||
tui3 alerts when a thread you aren't watching finishes or needs you (approval, input, a request, a failure or a usage limit), using T3 Code's own rules for when to alert. Subagents don't alert. Depending on `notificationMode`:
|
tui3 alerts when a thread you aren't watching finishes or needs you (approval, input, a request, a failure or a usage limit), using T3 Code's own rules for when to alert. Subagents don't alert. Depending on `notificationMode`:
|
||||||
|
|||||||
@@ -29,7 +29,12 @@ import {
|
|||||||
type RuntimeMode,
|
type RuntimeMode,
|
||||||
type TerminalAttachStreamEvent,
|
type TerminalAttachStreamEvent,
|
||||||
type TerminalSummary,
|
type TerminalSummary,
|
||||||
|
type TerminalOpenInput,
|
||||||
|
type EditorId,
|
||||||
|
type ServerLifecycleStreamEvent,
|
||||||
|
type WorktreeSetupSnapshot,
|
||||||
type VcsRef,
|
type VcsRef,
|
||||||
|
type VcsListRefsResult,
|
||||||
type OrchestrationV2ThreadLaunchInput,
|
type OrchestrationV2ThreadLaunchInput,
|
||||||
type OrchestrationV2ThreadShell,
|
type OrchestrationV2ThreadShell,
|
||||||
type VcsStatusLocalResult,
|
type VcsStatusLocalResult,
|
||||||
@@ -596,6 +601,99 @@ export class T3Session {
|
|||||||
return { isRepo: result.isRepo, ref: result.refs.find((ref) => ref.isDefault) ?? result.refs.find((ref) => ref.current) ?? null };
|
return { isRepo: result.isRepo, ref: result.refs.find((ref) => ref.isDefault) ?? result.refs.find((ref) => ref.current) ?? null };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Lists every page of local and remote refs for the branch picker. */
|
||||||
|
async listRefs(cwd: string): Promise<readonly VcsRef[]> {
|
||||||
|
const refs: VcsRef[] = [];
|
||||||
|
let cursor: number | null = 0;
|
||||||
|
do {
|
||||||
|
const page: VcsListRefsResult = await Effect.runPromise(this.requireConnection().rpc[WS_METHODS.vcsListRefs]({ cwd, refKind: "all", limit: 200, cursor }));
|
||||||
|
refs.push(...page.refs);
|
||||||
|
cursor = page.nextCursor;
|
||||||
|
} while (cursor !== null);
|
||||||
|
return refs;
|
||||||
|
}
|
||||||
|
|
||||||
|
switchRef(cwd: string, refName: string) {
|
||||||
|
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.vcsSwitchRef]({ cwd, refName }));
|
||||||
|
}
|
||||||
|
|
||||||
|
createRef(cwd: string, refName: string) {
|
||||||
|
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.vcsCreateRef]({ cwd, refName, switchRef: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
pull(cwd: string) {
|
||||||
|
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.vcsPull]({ cwd }));
|
||||||
|
}
|
||||||
|
|
||||||
|
createWorktree(cwd: string, refName: string, newRefName: string) {
|
||||||
|
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.vcsCreateWorktree]({ cwd, refName, newRefName, path: null }));
|
||||||
|
}
|
||||||
|
|
||||||
|
removeWorktree(cwd: string, path: string) {
|
||||||
|
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.vcsRemoveWorktree]({ cwd, path }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep shared worktrees, including ones held by idle children omitted from the shell. */
|
||||||
|
async removeThreadWorktree(threadId: ThreadId, cwd: string, path: string): Promise<void> {
|
||||||
|
const occupants = await Effect.runPromise(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds]({ worktreePath: path }));
|
||||||
|
if (occupants.threadIds.some((id) => id !== threadId)) throw new Error("Other threads still use this worktree.");
|
||||||
|
await this.detachThreadSessions(threadId);
|
||||||
|
await this.removeWorktree(cwd, path);
|
||||||
|
await this.setThreadWorkspace(threadId, null, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Changing folders detaches provider sessions before updating the thread, as the web does. */
|
||||||
|
async setThreadWorkspace(threadId: ThreadId, branch: string | null, worktreePath: string | null, previousWorktreePath: string | null): Promise<void> {
|
||||||
|
if (previousWorktreePath !== worktreePath) await this.detachThreadSessions(threadId);
|
||||||
|
await this.dispatch({ type: "thread.metadata.update", commandId: newCommandId(), threadId, branch, worktreePath });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Release provider sessions before moving or removing their workspace. */
|
||||||
|
async detachThreadSessions(threadId: ThreadId): Promise<void> {
|
||||||
|
const projection = await Effect.runPromise(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]({ threadId }));
|
||||||
|
for (const session of projection.providerSessions) {
|
||||||
|
await this.dispatch({ type: "provider-session.detach", commandId: newCommandId(), threadId, providerSessionId: session.id, reason: "client-requested" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
openInEditor(cwd: string, editor: EditorId) {
|
||||||
|
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.shellOpenInEditor]({ cwd, editor }));
|
||||||
|
}
|
||||||
|
|
||||||
|
cancelWorktreeSetup(threadId: ThreadId) {
|
||||||
|
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.worktreeSetupCancel]({ threadId }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Worktree preparation, shared and resubscribed after reconnects. */
|
||||||
|
watchWorktreeSetup(threadId: ThreadId, listener: Listener<{ readonly status: string; readonly snapshot: WorktreeSetupSnapshot | null; readonly error?: string }>): () => void {
|
||||||
|
return this.watchFeed(`setup:${threadId}`, { status: "loading", snapshot: null as WorktreeSetupSnapshot | null }, listener, (update) =>
|
||||||
|
this.requireConnection().rpc[WS_METHODS.subscribeWorktreeSetup]({ threadId }).pipe(
|
||||||
|
Stream.runForEach((snapshot) => Effect.sync(() => update({ status: "live", snapshot }))),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The pinned server emits welcome, ready and legacy-migration events. */
|
||||||
|
watchServerLifecycle(listener: Listener<{ readonly status: string; readonly event: ServerLifecycleStreamEvent | null; readonly error?: string }>): () => void {
|
||||||
|
return this.watchFeed("lifecycle", { status: "loading", event: null as ServerLifecycleStreamEvent | null }, listener, (update) =>
|
||||||
|
this.requireConnection().rpc[WS_METHODS.subscribeServerLifecycle]({}).pipe(
|
||||||
|
Stream.runForEach((event) => Effect.sync(() => update({ status: "live", event }))),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
openTerminal(input: TerminalOpenInput) {
|
||||||
|
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.terminalOpen](input));
|
||||||
|
}
|
||||||
|
|
||||||
|
closeTerminal(threadId: ThreadId, terminalId: string) {
|
||||||
|
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.terminalClose]({ threadId, terminalId, deleteHistory: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
clearTerminal(threadId: ThreadId, terminalId: string) {
|
||||||
|
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.terminalClear]({ threadId, terminalId }));
|
||||||
|
}
|
||||||
|
|
||||||
/** Every open terminal on the server; filter by thread. */
|
/** Every open terminal on the server; filter by thread. */
|
||||||
watchTerminals(listener: Listener<FeedState<TerminalSummary>>): () => void {
|
watchTerminals(listener: Listener<FeedState<TerminalSummary>>): () => void {
|
||||||
return this.watchFeed<FeedState<TerminalSummary>>("terminals", { status: "loading", items: [] }, listener, (update) =>
|
return this.watchFeed<FeedState<TerminalSummary>>("terminals", { status: "loading", items: [] }, listener, (update) =>
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { EDITORS, worktreeSetupStageLabel, type EditorId, type TerminalOpenInput, type TerminalSummary, type ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts";
|
||||||
|
import { projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||||
|
import { nextTerminalId } from "@t3tools/shared/terminalLabels";
|
||||||
|
|
||||||
|
export { resolveBranchSelectionTarget } from "../../vendor/t3code/apps/web/src/components/BranchToolbar.logic.ts";
|
||||||
|
|
||||||
|
/** Allocate and launch shells with the web's project environment and terminal numbering. */
|
||||||
|
export function newTerminalInput(threadId: ThreadId, projectRoot: string, worktreePath: string | null, terminals: readonly TerminalSummary[], metadataLive: boolean): TerminalOpenInput {
|
||||||
|
return {
|
||||||
|
threadId,
|
||||||
|
terminalId: nextTerminalId(terminals.map((terminal) => terminal.terminalId), metadataLive ? undefined : crypto.randomUUID()),
|
||||||
|
cwd: worktreePath ?? projectRoot,
|
||||||
|
worktreePath,
|
||||||
|
env: projectScriptRuntimeEnv({ project: { cwd: projectRoot }, worktreePath }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The web's fallback when its browser-local last-editor preference isn't available. */
|
||||||
|
export function preferredEditor(available: readonly EditorId[]): EditorId | null {
|
||||||
|
return EDITORS.find((editor) => available.includes(editor.id))?.id ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Show the active preparation stage without hiding failures after setup stops. */
|
||||||
|
export function worktreeSetupNote(snapshot: WorktreeSetupSnapshot | null): string | null {
|
||||||
|
if (!snapshot || snapshot.phase === "done") return null;
|
||||||
|
const stage = snapshot.stages.find((stage) => stage.status === "running") ?? snapshot.stages.find((stage) => stage.status === "failed");
|
||||||
|
return [
|
||||||
|
`Worktree setup: ${snapshot.phase}`,
|
||||||
|
stage ? worktreeSetupStageLabel(stage.id) : null,
|
||||||
|
stage?.percent !== null && stage?.percent !== undefined ? `${stage.percent}%` : null,
|
||||||
|
snapshot.error ?? stage?.detail,
|
||||||
|
].filter(Boolean).join(" · ");
|
||||||
|
}
|
||||||
+7
-40
@@ -10,7 +10,7 @@ import {
|
|||||||
} from "@t3tools/client-runtime/state/pending-user-input";
|
} from "@t3tools/client-runtime/state/pending-user-input";
|
||||||
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
|
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
|
||||||
import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
|
import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
|
||||||
import { DEFAULT_TERMINAL_ID, type ContextMenuItem, type DiscoveredLocalServer, type ModelSelection, type OrchestrationV2ThreadShell, type ProviderApprovalDecision, type ScheduledTask, type TerminalSummary, type ThreadId } from "@t3tools/contracts";
|
import { type ContextMenuItem, type DiscoveredLocalServer, type ModelSelection, type OrchestrationV2ThreadShell, type ProviderApprovalDecision, type ScheduledTask, type ThreadId } from "@t3tools/contracts";
|
||||||
import { homedir } from "node:os";
|
import { homedir } from "node:os";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
|
||||||
@@ -37,7 +37,7 @@ import { QuestionPanel } from "./QuestionPanel.tsx";
|
|||||||
import { QueuePanel } from "./QueuePanel.tsx";
|
import { QueuePanel } from "./QueuePanel.tsx";
|
||||||
import { SecretPanel } from "./SecretPanel.tsx";
|
import { SecretPanel } from "./SecretPanel.tsx";
|
||||||
import { SettingsView } from "./SettingsView.tsx";
|
import { SettingsView } from "./SettingsView.tsx";
|
||||||
import { attachTerminal } from "./terminalAttach.ts";
|
import { useWorkspace } from "./useWorkspace.ts";
|
||||||
import { copyText, desktopNotify, ring } from "./terminalOut.ts";
|
import { copyText, desktopNotify, ring } from "./terminalOut.ts";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
import { ThreadList } from "./ThreadList.tsx";
|
import { ThreadList } from "./ThreadList.tsx";
|
||||||
@@ -111,7 +111,6 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
const [pickerIndex, setPickerIndex] = useState(0);
|
const [pickerIndex, setPickerIndex] = useState(0);
|
||||||
/** Model changes waiting for each thread's next message, as the web composer holds them. */
|
/** Model changes waiting for each thread's next message, as the web composer holds them. */
|
||||||
const [pendingModels, setPendingModels] = useState<ReadonlyMap<ThreadId, ModelSelection>>(new Map());
|
const [pendingModels, setPendingModels] = useState<ReadonlyMap<ThreadId, ModelSelection>>(new Map());
|
||||||
const [terminals, setTerminals] = useState<FeedState<TerminalSummary> | null>(null);
|
|
||||||
/** Idle subagents the shell leaves out, fetched when you open one. */
|
/** Idle subagents the shell leaves out, fetched when you open one. */
|
||||||
const [familyShells, setFamilyShells] = useState<ReadonlyMap<ThreadId, OrchestrationV2ThreadShell>>(new Map());
|
const [familyShells, setFamilyShells] = useState<ReadonlyMap<ThreadId, OrchestrationV2ThreadShell>>(new Map());
|
||||||
const [confirmation, setConfirmation] = useState<Confirmation | null>(null);
|
const [confirmation, setConfirmation] = useState<Confirmation | null>(null);
|
||||||
@@ -258,7 +257,6 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
const vcsCwd = threadShell ? detailsCwd(threadShell, project) : null;
|
const vcsCwd = threadShell ? detailsCwd(threadShell, project) : null;
|
||||||
const live = shell.status.type === "live";
|
const live = shell.status.type === "live";
|
||||||
useEffect(() => (live ? session.watchServerConfig(setServerConfig) : undefined), [session, live]);
|
useEffect(() => (live ? session.watchServerConfig(setServerConfig) : undefined), [session, live]);
|
||||||
useEffect(() => (live ? session.watchTerminals(setTerminals) : undefined), [session, live]);
|
|
||||||
// An idle subagent isn't in the shell; its family (root, forks, all subagents) is, on servers that serve it.
|
// An idle subagent isn't in the shell; its family (root, forks, all subagents) is, on servers that serve it.
|
||||||
const supportsFamilies = serverConfig?.config?.shellThreadFamilies === true;
|
const supportsFamilies = serverConfig?.config?.shellThreadFamilies === true;
|
||||||
const unlisted = threadId !== undefined && !threadShell;
|
const unlisted = threadId !== undefined && !threadShell;
|
||||||
@@ -776,40 +774,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
// The thread's terminals, as the web's terminal drawer: attach to one, or open the first.
|
const workspace = useWorkspace({ session, renderer, live, thread: threadShell, project, serverConfig: serverConfig?.config ?? null, draft: draft !== null, diff, openPicker, confirm, run, say });
|
||||||
const threadTerminals = threadShell ? (terminals?.items ?? []).filter((terminal) => terminal.threadId === threadShell.id) : [];
|
|
||||||
const enterTerminal = (terminal: { terminalId: string; cwd: string; worktreePath: string | null; label?: string }) => {
|
|
||||||
if (!threadShell) return;
|
|
||||||
attachTerminal(renderer, session, { threadId: threadShell.id, terminalId: terminal.terminalId, cwd: terminal.cwd, worktreePath: terminal.worktreePath, label: terminal.label || terminal.terminalId }, (message) => {
|
|
||||||
if (message) say(message, true);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
const openTerminal = () => {
|
|
||||||
if (!threadShell) return say("Open a thread first.", true);
|
|
||||||
const cwd = threadShell.worktreePath ?? project?.workspaceRoot;
|
|
||||||
if (!cwd) return say("This thread has no folder to open a terminal in.", true);
|
|
||||||
const fresh = (id: string) => ({ terminalId: id, cwd, worktreePath: threadShell.worktreePath });
|
|
||||||
if (threadTerminals.length === 0) return enterTerminal(fresh(DEFAULT_TERMINAL_ID));
|
|
||||||
if (threadTerminals.length === 1 && threadTerminals[0]) return enterTerminal(threadTerminals[0]);
|
|
||||||
const taken = new Set(threadTerminals.map((terminal) => terminal.terminalId));
|
|
||||||
let next = 1;
|
|
||||||
while (taken.has(`term-${next}`)) next += 1;
|
|
||||||
openPicker({
|
|
||||||
placeholder: "Terminal",
|
|
||||||
groups: [
|
|
||||||
{
|
|
||||||
label: "Terminals",
|
|
||||||
items: threadTerminals.map((terminal) => ({
|
|
||||||
id: `terminal:${terminal.terminalId}`,
|
|
||||||
title: terminal.label || terminal.terminalId,
|
|
||||||
hint: terminal.status === "running" ? (terminal.hasRunningSubprocess ? "busy" : "running") : terminal.status,
|
|
||||||
run: () => enterTerminal(terminal),
|
|
||||||
})),
|
|
||||||
},
|
|
||||||
{ label: "New", items: [{ id: "terminal:new", title: "New terminal", run: () => enterTerminal(fresh(`term-${next}`)) }] },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
/** The composer's text in $EDITOR. */
|
/** The composer's text in $EDITOR. */
|
||||||
const openEditor = () => {
|
const openEditor = () => {
|
||||||
@@ -979,7 +944,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
command("draft-cancel", "Cancel new thread", () => setDraft(null), { keywords: ["discard"] });
|
command("draft-cancel", "Cancel new thread", () => setDraft(null), { keywords: ["discard"] });
|
||||||
}
|
}
|
||||||
if (currentModel) command("model", "Change model, options or mode", openModelPicker, { shortcut: "m", keywords: ["provider", "thinking", "reasoning", "effort", "speed", "fast", "access", "approval"] });
|
if (currentModel) command("model", "Change model, options or mode", openModelPicker, { shortcut: "m", keywords: ["provider", "thinking", "reasoning", "effort", "speed", "fast", "access", "approval"] });
|
||||||
if (threadShell && !draft) command("terminal", "Open terminal", openTerminal, { shortcut: "ctrl+j", keywords: ["shell", "console"] });
|
commands.push(...workspace.commands);
|
||||||
if (threadId || draft) command("editor", "Write the message in $EDITOR", openEditor, { shortcut: "ctrl+g", keywords: ["vim", "editor", "compose"] });
|
if (threadId || draft) command("editor", "Write the message in $EDITOR", openEditor, { shortcut: "ctrl+g", keywords: ["vim", "editor", "compose"] });
|
||||||
command("settings", "Settings", openSettings, { keywords: ["preferences", "config", "options", "notifications", "alerts"] });
|
command("settings", "Settings", openSettings, { keywords: ["preferences", "config", "options", "notifications", "alerts"] });
|
||||||
command("quit", "Quit tui3", quit, { shortcut: "q", keywords: ["exit"] });
|
command("quit", "Quit tui3", quit, { shortcut: "q", keywords: ["exit"] });
|
||||||
@@ -1006,7 +971,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
const globalKey = (key: KeyEvent): boolean => {
|
const globalKey = (key: KeyEvent): boolean => {
|
||||||
if (key.ctrl && key.name === "c") return quit(), true;
|
if (key.ctrl && key.name === "c") return quit(), true;
|
||||||
if (key.ctrl && key.name === "k") return openPalette(), true;
|
if (key.ctrl && key.name === "k") return openPalette(), true;
|
||||||
if ((key.ctrl && key.name === "j") || key.name === "linefeed") return openTerminal(), true;
|
if ((key.ctrl && key.name === "j") || key.name === "linefeed") return workspace.openTerminal(), true;
|
||||||
if (key.ctrl && key.name === "g" && (threadId || draft)) return openEditor(), true;
|
if (key.ctrl && key.name === "g" && (threadId || draft)) return openEditor(), true;
|
||||||
// One-line inputs keep ctrl+u and ctrl+d for editing.
|
// One-line inputs keep ctrl+u and ctrl+d for editing.
|
||||||
const lineInput = mode === "filter" || mode === "palette" || mode === "confirm";
|
const lineInput = mode === "filter" || mode === "palette" || mode === "confirm";
|
||||||
@@ -1200,6 +1165,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
return setMode("nav");
|
return setMode("nav");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (workspace.key(key)) return;
|
||||||
switch (key.name) {
|
switch (key.name) {
|
||||||
case "q":
|
case "q":
|
||||||
if (diff) return setDiff(null);
|
if (diff) return setDiff(null);
|
||||||
@@ -1405,6 +1371,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
<text fg={colors.muted}>{shell.snapshot ? "No thread selected." : "Waiting for threads…"}</text>
|
<text fg={colors.muted}>{shell.snapshot ? "No thread selected." : "Waiting for threads…"}</text>
|
||||||
</box>
|
</box>
|
||||||
)}
|
)}
|
||||||
|
{workspace.note ? <text fg={workspace.setupFailed ? colors.bad : colors.muted}>{workspace.note}</text> : null}
|
||||||
{mode !== "confirm" && secret.request ? <SecretPanel request={secret.request} value={secret.value} error={secret.error} busy={secret.busy} /> : null}
|
{mode !== "confirm" && secret.request ? <SecretPanel request={secret.request} value={secret.value} error={secret.error} busy={secret.busy} /> : null}
|
||||||
{queue.queued.length > 0 ? <QueuePanel queued={queue.queued} focus={queue.focus} editingRunId={queue.editingRunId} held={queue.queue?.held ?? false} width={width - listWidth - (detailsColumn ? DETAILS_WIDTH : 0) - 2} /> : null}
|
{queue.queued.length > 0 ? <QueuePanel queued={queue.queued} focus={queue.focus} editingRunId={queue.editingRunId} held={queue.queue?.held ?? false} width={width - listWidth - (detailsColumn ? DETAILS_WIDTH : 0) - 2} /> : null}
|
||||||
{mode !== "confirm" && pendingInput && questionDraft ? <QuestionPanel request={pendingInput} index={questionDraft.index} draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]} /> : null}
|
{mode !== "confirm" && pendingInput && questionDraft ? <QuestionPanel request={pendingInput} index={questionDraft.index} draft={questionDraft.answers[pendingInput.questions[questionDraft.index]?.id ?? ""]} /> : null}
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
import type { CliRenderer, KeyEvent } from "@opentui/core";
|
||||||
|
import type { OrchestrationProjectShell, OrchestrationV2ThreadShell, ServerConfig, ServerLifecycleStreamEvent, TerminalSummary, WorktreeSetupSnapshot } from "@t3tools/contracts";
|
||||||
|
import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
|
||||||
|
import { deriveLocalBranchNameFromRemoteRef, sanitizeNewRefName } from "@t3tools/shared/git";
|
||||||
|
import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
|
import type { FeedState, T3Session } from "../client/session.ts";
|
||||||
|
import type { PaletteCommand, Picker, PickerItem } from "../model/palette.ts";
|
||||||
|
import { newTerminalInput, preferredEditor, resolveBranchSelectionTarget, worktreeSetupNote } from "../model/workspace.ts";
|
||||||
|
import type { Confirmation } from "./ConfirmBar.tsx";
|
||||||
|
import { splitPatch, type DiffState } from "./DiffView.tsx";
|
||||||
|
import { attachTerminal } from "./terminalAttach.ts";
|
||||||
|
|
||||||
|
type Command = PaletteCommand & { readonly run: () => void };
|
||||||
|
|
||||||
|
/** Workspace controls stay out of the app's composer and navigation state. */
|
||||||
|
export function useWorkspace(input: {
|
||||||
|
readonly session: T3Session;
|
||||||
|
readonly renderer: CliRenderer;
|
||||||
|
readonly live: boolean;
|
||||||
|
readonly thread: OrchestrationV2ThreadShell | undefined;
|
||||||
|
readonly project: OrchestrationProjectShell | undefined;
|
||||||
|
readonly serverConfig: ServerConfig | null;
|
||||||
|
readonly draft: boolean;
|
||||||
|
readonly diff: DiffState | null;
|
||||||
|
readonly openPicker: (picker: Picker) => void;
|
||||||
|
readonly confirm: (confirmation: Confirmation) => void;
|
||||||
|
readonly run: (label: string, action: () => Promise<unknown>) => void;
|
||||||
|
readonly say: (message: string, bad?: boolean) => void;
|
||||||
|
}) {
|
||||||
|
const { session, renderer, live, thread, project, openPicker, confirm, run, say } = input;
|
||||||
|
const [terminals, setTerminals] = useState<FeedState<TerminalSummary> | null>(null);
|
||||||
|
const [setup, setSetup] = useState<WorktreeSetupSnapshot | null>(null);
|
||||||
|
const [setupError, setSetupError] = useState<string | null>(null);
|
||||||
|
const sayRef = useRef(say);
|
||||||
|
sayRef.current = say;
|
||||||
|
const activeThread = useRef(thread?.id);
|
||||||
|
activeThread.current = thread?.id;
|
||||||
|
const lastReady = useRef<string | null>(null);
|
||||||
|
useEffect(() => live ? session.watchTerminals(setTerminals) : undefined, [session, live]);
|
||||||
|
useEffect(() => {
|
||||||
|
setSetup(null);
|
||||||
|
setSetupError(null);
|
||||||
|
if (!live || !thread) return;
|
||||||
|
return session.watchWorktreeSetup(thread.id, (state) => {
|
||||||
|
setSetup(state.snapshot);
|
||||||
|
setSetupError(state.status === "error" ? state.error ?? "Could not load worktree setup." : null);
|
||||||
|
});
|
||||||
|
}, [session, live, thread?.id]);
|
||||||
|
useEffect(() => session.watchServerLifecycle((state) => {
|
||||||
|
const event: ServerLifecycleStreamEvent | null = state.event;
|
||||||
|
if (event?.type === "ready" && event.payload.at !== lastReady.current) {
|
||||||
|
const restarted = lastReady.current !== null;
|
||||||
|
lastReady.current = event.payload.at;
|
||||||
|
const outcome = event.payload.updateOutcome;
|
||||||
|
sayRef.current(outcome
|
||||||
|
? `Server update ${outcome.targetVersion}: ${outcome.status}${outcome.reason ? ` · ${outcome.reason}` : ""}`
|
||||||
|
: `Server ${restarted ? "restarted" : "ready"} · ${event.payload.environment.serverVersion}`, outcome !== undefined && outcome.status !== "committed");
|
||||||
|
} else if (event?.type === "legacyThreadMigration") {
|
||||||
|
sayRef.current(`Thread migration ${event.payload.status} · ${event.payload.totalThreadCount} threads`);
|
||||||
|
}
|
||||||
|
}), [session]);
|
||||||
|
|
||||||
|
const threadTerminals = (terminals?.items ?? []).filter((terminal) => terminal.threadId === thread?.id);
|
||||||
|
const cwd = thread?.worktreePath ?? project?.workspaceRoot;
|
||||||
|
const label = (terminal: TerminalSummary) => resolveTerminalSessionLabel(terminal.terminalId, terminal);
|
||||||
|
const enterTerminal = (terminal: Pick<TerminalSummary, "terminalId" | "cwd" | "worktreePath" | "label">) => {
|
||||||
|
if (!thread) return;
|
||||||
|
attachTerminal(renderer, session, { threadId: thread.id, ...terminal, label: resolveTerminalSessionLabel(terminal.terminalId, terminal) }, (message) => {
|
||||||
|
if (message) say(message);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const newTerminal = () => {
|
||||||
|
if (!thread || !project) return say("Open a thread with a project folder first.", true);
|
||||||
|
const request = newTerminalInput(thread.id, project.workspaceRoot, thread.worktreePath, threadTerminals, terminals?.status === "live");
|
||||||
|
run("Terminal opened", async () => {
|
||||||
|
await session.openTerminal(request);
|
||||||
|
enterTerminal({ terminalId: request.terminalId, cwd: request.cwd, worktreePath: thread.worktreePath, label: "" });
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const terminalMutation = (terminal: TerminalSummary, action: "close" | "clear") => {
|
||||||
|
if (!thread) return;
|
||||||
|
run(action === "close" ? "Terminal closed" : "Terminal cleared", () => action === "close" ? session.closeTerminal(thread.id, terminal.terminalId) : session.clearTerminal(thread.id, terminal.terminalId));
|
||||||
|
};
|
||||||
|
const terminalItems = (action: "close" | "clear"): PickerItem[] => threadTerminals.map((terminal) => ({
|
||||||
|
id: `terminal:${action}:${terminal.terminalId}`, title: `${action === "close" ? "Close" : "Clear"} › ${label(terminal)}`,
|
||||||
|
run: () => terminalMutation(terminal, action),
|
||||||
|
}));
|
||||||
|
const terminalPicker = () => {
|
||||||
|
if (!thread || input.draft) return say("Open a thread first.", true);
|
||||||
|
openPicker({ placeholder: "Terminals · type close or clear for actions", groups: [
|
||||||
|
{ label: "Terminals", items: threadTerminals.map((terminal) => ({ id: `terminal:${terminal.terminalId}`, title: label(terminal), hint: terminal.hasRunningSubprocess ? "busy" : terminal.status, run: () => enterTerminal(terminal) })) },
|
||||||
|
{ label: "Actions", items: [
|
||||||
|
{ id: "terminal:new", title: "New terminal", run: newTerminal },
|
||||||
|
...(["close", "clear"] as const).flatMap((action) => {
|
||||||
|
const items = terminalItems(action);
|
||||||
|
return items.length ? [
|
||||||
|
{ id: `terminal:${action}`, title: `${action === "close" ? "Close" : "Clear"} terminal…`, run: () => openPicker({ placeholder: `${action === "close" ? "Close" : "Clear"} terminal`, groups: [{ label: "Terminals", items }] }) },
|
||||||
|
...items.map((item) => ({ ...item, searchOnly: true })),
|
||||||
|
] : [];
|
||||||
|
}),
|
||||||
|
] },
|
||||||
|
] });
|
||||||
|
};
|
||||||
|
const openTerminal = () => {
|
||||||
|
if (!thread || input.draft) return say("Open a thread first.", true);
|
||||||
|
if (threadTerminals.length === 0) return newTerminal();
|
||||||
|
if (threadTerminals.length === 1) return enterTerminal(threadTerminals[0]!);
|
||||||
|
terminalPicker();
|
||||||
|
};
|
||||||
|
|
||||||
|
const branchPicker = () => {
|
||||||
|
if (!thread || !cwd || !project || input.draft) return say("Open a thread with a repository first.", true);
|
||||||
|
say("Loading refs…");
|
||||||
|
session.listRefs(cwd).then((refs) => {
|
||||||
|
if (activeThread.current !== thread.id) return;
|
||||||
|
const updateWorkspace = (branch: string | null, path: string | null) => session.setThreadWorkspace(thread.id, branch, path, thread.worktreePath);
|
||||||
|
const promptBranch = (worktree: boolean) => confirm({
|
||||||
|
title: worktree ? "Create a new worktree?" : "Create and switch ref",
|
||||||
|
detail: worktree ? `Based on ${thread.branch ?? "HEAD"}. The thread will move to the new worktree.` : cwd,
|
||||||
|
message: { placeholder: "New branch name" }, confirmLabel: "create",
|
||||||
|
run: (raw) => {
|
||||||
|
const name = sanitizeNewRefName(raw);
|
||||||
|
if (!name) return say("Enter a branch name.", true);
|
||||||
|
run(worktree ? "Worktree created" : "Branch created", async () => {
|
||||||
|
if (worktree) {
|
||||||
|
const result = await session.createWorktree(cwd, thread.branch ?? "HEAD", name);
|
||||||
|
await updateWorkspace(result.worktree.refName, result.worktree.path);
|
||||||
|
} else {
|
||||||
|
const result = await session.createRef(cwd, name);
|
||||||
|
await updateWorkspace(result.refName, thread.worktreePath);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
openPicker({ placeholder: "Select ref", groups: [
|
||||||
|
{ label: "Refs", items: refs.map((ref) => ({
|
||||||
|
id: `ref:${ref.isRemote ? "remote:" : ""}${ref.name}`, title: ref.name,
|
||||||
|
hint: ref.current ? "current" : ref.worktreePath ? "worktree" : ref.isRemote ? "remote" : ref.isDefault ? "default" : "local",
|
||||||
|
run: () => run("Ref selected", async () => {
|
||||||
|
const target = resolveBranchSelectionTarget({ activeProjectCwd: project.workspaceRoot, activeWorktreePath: thread.worktreePath, refName: ref });
|
||||||
|
const result = target.reuseExistingWorktree ? null : await session.switchRef(target.checkoutCwd, ref.name);
|
||||||
|
await updateWorkspace(ref.isRemote ? result?.refName ?? deriveLocalBranchNameFromRemoteRef(ref.name) : ref.name, target.nextWorktreePath);
|
||||||
|
}),
|
||||||
|
})) },
|
||||||
|
{ label: "Actions", items: [
|
||||||
|
{ id: "branch:create", title: "Create and switch ref…", run: () => promptBranch(false) },
|
||||||
|
{ id: "branch:pull", title: "Pull", run: () => run("Pulled", () => session.pull(cwd)) },
|
||||||
|
{ id: "worktree:create", title: "Create worktree…", run: () => promptBranch(true) },
|
||||||
|
...(thread.worktreePath ? [{ id: "worktree:remove", title: "Remove worktree…", run: () => confirm({
|
||||||
|
title: "Remove this worktree?", detail: `${thread.worktreePath} · Stops this thread's provider session. Refuses shared worktrees and uncommitted changes.`, confirmLabel: "remove",
|
||||||
|
run: () => run("Worktree removed", () => session.removeThreadWorktree(thread.id, project.workspaceRoot, thread.worktreePath!)),
|
||||||
|
}) }] : []),
|
||||||
|
] },
|
||||||
|
] });
|
||||||
|
}, (error) => say(`Could not list refs: ${messageOf(error)}`, true));
|
||||||
|
};
|
||||||
|
|
||||||
|
const openInEditor = () => {
|
||||||
|
if (!thread || !cwd || input.draft) return say("Open a thread first.", true);
|
||||||
|
const editor = preferredEditor(input.serverConfig?.availableEditors ?? []);
|
||||||
|
if (!editor) return say("No available editor on the server.", true);
|
||||||
|
const open = (path: string) => run("Opened in editor", () => session.openInEditor(path, editor));
|
||||||
|
if (!input.diff) return open(cwd);
|
||||||
|
const diff = input.diff;
|
||||||
|
if (diff.path) return open(resolvePathLinkTarget(diff.path, diff.cwd));
|
||||||
|
const files = splitPatch(diff.patch ?? "");
|
||||||
|
if (!files.length) return say("No file to open in this diff.", true);
|
||||||
|
openPicker({ placeholder: "Open diff file in editor", groups: [{ label: "Files", items: files.map((file) => ({ id: `editor:${file.path}`, title: file.path, run: () => open(resolvePathLinkTarget(file.path, diff.cwd)) })) }] });
|
||||||
|
};
|
||||||
|
const cancelSetup = () => {
|
||||||
|
if (!setup || setup.threadId !== thread?.id || setup.phase !== "running") return;
|
||||||
|
confirm({ title: "Cancel worktree setup?", detail: "Stops workspace preparation and its setup script.", confirmLabel: "cancel setup", run: () => run("Worktree setup cancellation requested", () => session.cancelWorktreeSetup(setup.threadId)) });
|
||||||
|
};
|
||||||
|
const commands: Command[] = thread && !input.draft ? [
|
||||||
|
{ id: "terminal", title: "Open terminal", shortcut: "ctrl+j", keywords: ["shell", "console"], run: openTerminal },
|
||||||
|
{ id: "terminal-picker", title: "Terminals…", shortcut: "T", keywords: ["shell", "close", "clear", "attach"], run: terminalPicker },
|
||||||
|
{ id: "terminal-new", title: "New terminal", keywords: ["shell", "open"], run: newTerminal },
|
||||||
|
...terminalItems("close"), ...terminalItems("clear"),
|
||||||
|
{ id: "branches", title: "Branches and worktrees…", shortcut: "b", keywords: ["git", "switch", "ref", "create", "remove", "pull"], run: branchPicker },
|
||||||
|
{ id: "workspace-editor", title: input.diff ? "Open diff file in editor" : "Open workspace in editor", shortcut: "E", keywords: ["folder", "code", "vscode", "cursor"], run: openInEditor },
|
||||||
|
...(setup?.threadId === thread.id && setup.phase === "running" ? [{ id: "setup-cancel", title: "Cancel worktree setup…", keywords: ["preparation", "stop"], run: cancelSetup }] : []),
|
||||||
|
] : [];
|
||||||
|
const key = (key: KeyEvent): boolean => {
|
||||||
|
if (key.ctrl || key.meta) return false;
|
||||||
|
if (key.name === "t" && key.shift) return terminalPicker(), true;
|
||||||
|
if (key.name === "b" && !key.shift) return branchPicker(), true;
|
||||||
|
if (key.name === "e" && key.shift) return openInEditor(), true;
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
return { commands, key, openTerminal, note: input.draft ? null : setupError ?? worktreeSetupNote(setup?.threadId === thread?.id ? setup : null), setupFailed: setup?.phase === "failed" || setupError !== null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const messageOf = (error: unknown) => error instanceof Error ? error.message : String(error);
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import { OrchestrationV2Command, ThreadId, TerminalOpenInput, TerminalCloseInput, TerminalClearInput, VcsSwitchRefInput, VcsCreateRefInput, VcsPullInput, VcsCreateWorktreeInput, VcsRemoveWorktreeInput, LaunchEditorInput, WorktreeSetupCancelInput, type TerminalSummary, type WorktreeSetupSnapshot } from "@t3tools/contracts";
|
||||||
|
import * as Effect from "effect/Effect";
|
||||||
|
import * as Schema from "effect/Schema";
|
||||||
|
|
||||||
|
import { T3Session } from "../src/client/session.ts";
|
||||||
|
import { newTerminalInput, preferredEditor, resolveBranchSelectionTarget, worktreeSetupNote } from "../src/model/workspace.ts";
|
||||||
|
|
||||||
|
const threadId = ThreadId.make("thread-1");
|
||||||
|
|
||||||
|
function capturingSession(results: Record<string, unknown> = {}) {
|
||||||
|
const sent: { method: string; input: unknown }[] = [];
|
||||||
|
const session = new T3Session();
|
||||||
|
const rpc = new Proxy({}, { get: (_, method: string) => (input: unknown) => {
|
||||||
|
sent.push({ method, input });
|
||||||
|
return Effect.succeed(results[method]);
|
||||||
|
} });
|
||||||
|
(session as unknown as { connection: unknown }).connection = { rpc };
|
||||||
|
return { session, sent };
|
||||||
|
}
|
||||||
|
|
||||||
|
const terminal = (id: string): TerminalSummary => ({ threadId, terminalId: id, cwd: "/repo", worktreePath: null, status: "running", pid: 1, exitCode: null, exitSignal: null, hasRunningSubprocess: false, label: "", updatedAt: "2026-11-01T00:00:00.000Z" });
|
||||||
|
|
||||||
|
describe("workspace logic", () => {
|
||||||
|
test("new terminals use the web's numbering, cwd and project environment", () => {
|
||||||
|
const request = newTerminalInput(threadId, "/repo", "/worktree", [terminal("term-1"), terminal("term-3")], true);
|
||||||
|
expect(Schema.is(TerminalOpenInput)(request)).toBe(true);
|
||||||
|
expect(request).toEqual({ threadId, terminalId: "term-2", cwd: "/worktree", worktreePath: "/worktree", env: { T3CODE_PROJECT_ROOT: "/repo", T3CODE_WORKTREE_PATH: "/worktree" } });
|
||||||
|
const local = newTerminalInput(threadId, "/repo", null, [], false);
|
||||||
|
expect(local.terminalId).toMatch(/^term-1-[a-f0-9-]+$/);
|
||||||
|
expect(local.cwd).toBe("/repo");
|
||||||
|
expect(local.env).toEqual({ T3CODE_PROJECT_ROOT: "/repo" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("editor preference falls back in the web's order, not the server list's order", () => {
|
||||||
|
expect(preferredEditor(["vscode", "cursor"])).toBe("cursor");
|
||||||
|
expect(preferredEditor(["vscode"])).toBe("vscode");
|
||||||
|
expect(preferredEditor([])).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("branch selection reuses worktrees and returns the default branch to the project", () => {
|
||||||
|
expect(resolveBranchSelectionTarget({ activeProjectCwd: "/repo", activeWorktreePath: "/old", refName: { isDefault: false, worktreePath: "/existing" } })).toEqual({ checkoutCwd: "/existing", nextWorktreePath: "/existing", reuseExistingWorktree: true });
|
||||||
|
expect(resolveBranchSelectionTarget({ activeProjectCwd: "/repo", activeWorktreePath: "/old", refName: { isDefault: true, worktreePath: null } })).toEqual({ checkoutCwd: "/repo", nextWorktreePath: null, reuseExistingWorktree: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("setup progress names the web's stage, percent, details and failures", () => {
|
||||||
|
const snapshot: WorktreeSetupSnapshot = { threadId, phase: "running", startedAt: "2026-11-01T00:00:00.000Z", endedAt: null, branch: "feature", baseRef: "main", worktreePath: null, setupScript: null, sequence: 1, error: null, stages: [{ id: "fetch", status: "running", percent: 42, detail: "Fetching origin", startedAt: null, endedAt: null, tail: [] }] };
|
||||||
|
expect(worktreeSetupNote(snapshot)).toBe("Worktree setup: running · Fetch base branch · 42% · Fetching origin");
|
||||||
|
expect(worktreeSetupNote({ ...snapshot, phase: "failed", error: "Fetch failed" })).toContain("Fetch failed");
|
||||||
|
expect(worktreeSetupNote({ ...snapshot, phase: "cancelled", stages: [] })).toBe("Worktree setup: cancelled");
|
||||||
|
expect(worktreeSetupNote({ ...snapshot, phase: "done" })).toBeNull();
|
||||||
|
expect(worktreeSetupNote(null)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("workspace RPC payloads (no live mutations)", () => {
|
||||||
|
test("terminal open, close and clear validate against the server contracts", async () => {
|
||||||
|
const { session, sent } = capturingSession();
|
||||||
|
await session.openTerminal(newTerminalInput(threadId, "/repo", null, [], true));
|
||||||
|
await session.closeTerminal(threadId, "term-1");
|
||||||
|
await session.clearTerminal(threadId, "term-1");
|
||||||
|
expect(sent.map((call) => call.method)).toEqual(["terminal.open", "terminal.close", "terminal.clear"]);
|
||||||
|
expect(Schema.is(TerminalOpenInput)(sent[0]!.input)).toBe(true);
|
||||||
|
expect(Schema.is(TerminalCloseInput)(sent[1]!.input)).toBe(true);
|
||||||
|
expect(sent[1]!.input).toMatchObject({ threadId, terminalId: "term-1", deleteHistory: true });
|
||||||
|
expect(Schema.is(TerminalClearInput)(sent[2]!.input)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("branch, worktree, editor and setup cancellation requests validate", async () => {
|
||||||
|
const { session, sent } = capturingSession();
|
||||||
|
await session.switchRef("/repo", "origin/feature");
|
||||||
|
await session.createRef("/repo", "feature");
|
||||||
|
await session.pull("/repo");
|
||||||
|
await session.createWorktree("/repo", "main", "new-work");
|
||||||
|
await session.removeWorktree("/repo", "/worktree");
|
||||||
|
await session.openInEditor("/worktree/src/index.ts", "vscode");
|
||||||
|
await session.cancelWorktreeSetup(threadId);
|
||||||
|
expect(sent.map((call) => call.method)).toEqual(["vcs.switchRef", "vcs.createRef", "vcs.pull", "vcs.createWorktree", "vcs.removeWorktree", "shell.openInEditor", "worktreeSetup.cancel"]);
|
||||||
|
const schemas = [VcsSwitchRefInput, VcsCreateRefInput, VcsPullInput, VcsCreateWorktreeInput, VcsRemoveWorktreeInput, LaunchEditorInput, WorktreeSetupCancelInput];
|
||||||
|
schemas.forEach((schema, index) => expect(Schema.is(schema)(sent[index]!.input)).toBe(true));
|
||||||
|
expect(sent[1]!.input).toMatchObject({ switchRef: true });
|
||||||
|
expect(sent[3]!.input).toEqual({ cwd: "/repo", refName: "main", newRefName: "new-work", path: null });
|
||||||
|
expect(sent[4]!.input).not.toHaveProperty("force");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("moving folders detaches provider sessions before persisting thread metadata", async () => {
|
||||||
|
const { session, sent } = capturingSession({ "orchestration.getThreadProjection": { providerSessions: [{ id: "session-1" }, { id: "session-2" }] } });
|
||||||
|
await session.setThreadWorkspace(threadId, "feature", "/worktree", null);
|
||||||
|
const commands = sent.filter((call) => call.method === "orchestration.dispatchCommand").map((call) => call.input);
|
||||||
|
expect(commands).toHaveLength(3);
|
||||||
|
expect(commands.every(Schema.is(OrchestrationV2Command))).toBe(true);
|
||||||
|
expect(commands[0]).toMatchObject({ type: "provider-session.detach", providerSessionId: "session-1", reason: "client-requested" });
|
||||||
|
expect(commands[2]).toMatchObject({ type: "thread.metadata.update", threadId, branch: "feature", worktreePath: "/worktree" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("switching branches within a workspace leaves provider sessions attached", async () => {
|
||||||
|
const { session, sent } = capturingSession();
|
||||||
|
await session.setThreadWorkspace(threadId, "feature", null, null);
|
||||||
|
expect(sent).toHaveLength(1);
|
||||||
|
expect(Schema.is(OrchestrationV2Command)(sent[0]!.input)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("worktree removal refuses shared folders before detaching or removing anything", async () => {
|
||||||
|
const { session, sent } = capturingSession({ "orchestration.getWorktreeThreadIds": { threadIds: [threadId, ThreadId.make("idle-child")] } });
|
||||||
|
await expect(session.removeThreadWorktree(threadId, "/repo", "/worktree")).rejects.toThrow("Other threads still use this worktree.");
|
||||||
|
expect(sent.map((call) => call.method)).toEqual(["orchestration.getWorktreeThreadIds"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("worktree removal checks occupants, detaches, removes and updates metadata in order", async () => {
|
||||||
|
const { session, sent } = capturingSession({ "orchestration.getWorktreeThreadIds": { threadIds: [threadId] }, "orchestration.getThreadProjection": { providerSessions: [{ id: "session-1" }] } });
|
||||||
|
await session.removeThreadWorktree(threadId, "/repo", "/worktree");
|
||||||
|
expect(sent.map((call) => call.method)).toEqual(["orchestration.getWorktreeThreadIds", "orchestration.getThreadProjection", "orchestration.dispatchCommand", "vcs.removeWorktree", "orchestration.dispatchCommand"]);
|
||||||
|
expect(sent[4]!.input).toMatchObject({ type: "thread.metadata.update", branch: null, worktreePath: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("branch listing reads all pages", async () => {
|
||||||
|
const { session, sent } = capturingSession();
|
||||||
|
(session as unknown as { connection: unknown }).connection = { rpc: { "vcs.listRefs": (input: { cursor: number }) => {
|
||||||
|
sent.push({ method: "vcs.listRefs", input });
|
||||||
|
return Effect.succeed({ isRepo: true, refs: [{ name: input.cursor === 0 ? "main" : "feature" }], nextCursor: input.cursor === 0 ? 1 : null });
|
||||||
|
} } };
|
||||||
|
expect((await session.listRefs("/repo")).map((ref) => ref.name)).toEqual(["main", "feature"]);
|
||||||
|
expect(sent.map((call) => call.input)).toEqual([{ cwd: "/repo", cursor: 0, refKind: "all", limit: 200 }, { cwd: "/repo", cursor: 1, refKind: "all", limit: 200 }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user