Fix terminal attach session launch context

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-05-03 20:56:44 -07:00
1 parent b4615a847a
commit 93ec45eb3c
9 files changed
+249 -63

No files matched your search

@@ -509,6 +509,7 @@ export function ThreadTerminalRouteScreen() {
cols: lastGridSize.cols,
rows: lastGridSize.rows,
env: pendingLaunch?.env,
...(pendingLaunch ? { restartIfNotRunning: true } : {}),
},
onEvent: logAttachStreamEvent,
onSnapshot: () => {
@@ -312,6 +312,85 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
}),
);
it.effect("attaches to exited sessions without restarting them", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, getEvents } = yield* createManager();
yield* manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitExit({ exitCode: 0, signal: 0 });
yield* waitFor(
Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")),
"1200 millis",
);
const scope = yield* Effect.scope;
const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
const unsubscribe = yield* manager.attachStream(
openInput({
env: {
T3CODE_WORKTREE_PATH: "/tmp/should-not-restart",
},
worktreePath: "/tmp/should-not-restart",
}),
(event) => Ref.update(attachEvents, (events) => [...events, event]),
);
yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe));
const snapshot = (yield* Ref.get(attachEvents)).find((event) => event.type === "snapshot");
expect(snapshot).toBeDefined();
if (!snapshot || snapshot.type !== "snapshot") return;
assert.equal(snapshot.snapshot.status, "exited");
assert.equal(snapshot.snapshot.worktreePath, null);
expect(ptyAdapter.spawnInputs).toHaveLength(1);
}),
);
it.effect("restarts inactive sessions from attach only when requested", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, getEvents } = yield* createManager();
yield* manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitExit({ exitCode: 0, signal: 0 });
yield* waitFor(
Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")),
"1200 millis",
);
const scope = yield* Effect.scope;
const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
const unsubscribe = yield* manager.attachStream(
{
...openInput({
env: {
T3CODE_WORKTREE_PATH: "/tmp/restart-requested",
},
worktreePath: "/tmp/restart-requested",
}),
restartIfNotRunning: true,
},
(event) => Ref.update(attachEvents, (events) => [...events, event]),
);
yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe));
const snapshot = (yield* Ref.get(attachEvents)).find((event) => event.type === "snapshot");
expect(snapshot).toBeDefined();
if (!snapshot || snapshot.type !== "snapshot") return;
assert.equal(snapshot.snapshot.status, "running");
assert.equal(snapshot.snapshot.worktreePath, "/tmp/restart-requested");
expect(ptyAdapter.spawnInputs).toHaveLength(2);
}),
);
const makeDirectory = (filePath: string) =>
Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
fs.makeDirectory(filePath, { recursive: true }),
+1 -1
View File
@@ -1995,7 +1995,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
const targetCols = input.cols ?? session.cols;
const targetRows = input.rows ?? session.rows;
if (!session.process && input.cwd) {
if (!session.process && input.cwd && input.restartIfNotRunning === true) {
return yield* openLocked({
...input,
terminalId,
+6 -6
View File
@@ -1811,9 +1811,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.terminalOpen,
) as
const attachRequest = wsRequests
.toReversed()
.find((request) => request._tag === WS_METHODS.terminalAttach) as
| {
_tag: string;
cwd?: string;
@@ -1821,15 +1821,15 @@ describe("ChatView timeline estimator parity (full app)", () => {
env?: Record<string, string>;
}
| undefined;
expect(openRequest).toMatchObject({
_tag: WS_METHODS.terminalOpen,
expect(attachRequest).toMatchObject({
_tag: WS_METHODS.terminalAttach,
cwd: "/repo/project",
worktreePath: null,
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
},
});
expect(openRequest?.env?.T3CODE_WORKTREE_PATH).toBeUndefined();
expect(attachRequest?.env?.T3CODE_WORKTREE_PATH).toBeUndefined();
},
{ timeout: 8_000, interval: 16 },
);
+33
View File
@@ -501,6 +501,38 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
}
return next;
}, [knownTerminalSessions]);
const terminalLaunchLocationsById = useMemo(() => {
const next = new Map<
string,
{
readonly cwd: string;
readonly worktreePath: string | null;
readonly runtimeEnv: Record<string, string>;
}
>();
if (!project) {
return next;
}
for (const session of knownTerminalSessions) {
const summary = session.state.summary;
if (!summary) {
continue;
}
const worktreePathForLaunch =
launchContext !== null ? launchContext.worktreePath : summary.worktreePath;
next.set(session.target.terminalId, {
cwd: launchContext?.cwd ?? summary.cwd,
worktreePath: worktreePathForLaunch,
runtimeEnv: projectScriptRuntimeEnv({
project: { cwd: project.cwd },
worktreePath: worktreePathForLaunch,
}),
});
}
return next;
}, [knownTerminalSessions, launchContext, project]);
const serverOrderedTerminalIds = useMemo(
() => knownTerminalSessions.map((session) => session.target.terminalId),
[knownTerminalSessions],
@@ -709,6 +741,7 @@ const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDra
onHeightChange={setTerminalHeight}
onAddTerminalContext={handleAddTerminalContext}
terminalLabelsById={terminalLabelsById}
terminalLaunchLocationsById={terminalLaunchLocationsById}
/>
</div>
);
@@ -1,7 +1,7 @@
import "../index.css";
import { scopeThreadRef } from "@t3tools/client-runtime";
import { ThreadId } from "@t3tools/contracts";
import { ThreadId, type TerminalAttachStreamEvent } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
@@ -18,7 +18,17 @@ const {
terminalDisposeSpy: vi.fn(),
fitAddonFitSpy: vi.fn(),
fitAddonLoadSpy: vi.fn(),
environmentApiById: new Map<string, { terminal: { open: ReturnType<typeof vi.fn> } }>(),
environmentApiById: new Map<
string,
{
terminal: {
open: ReturnType<typeof vi.fn>;
attach: ReturnType<typeof vi.fn>;
write: ReturnType<typeof vi.fn>;
resize: ReturnType<typeof vi.fn>;
};
}
>(),
readEnvironmentApiMock: vi.fn((environmentId: string) => environmentApiById.get(environmentId)),
readLocalApiMock: vi.fn<
() =>
@@ -124,21 +134,33 @@ import { TerminalViewport } from "./ThreadTerminalDrawer";
const THREAD_ID = ThreadId.make("thread-terminal-browser");
function createEnvironmentApi() {
const snapshot = {
threadId: THREAD_ID,
terminalId: "term-1",
cwd: "/repo/project",
worktreePath: null,
status: "running" as const,
pid: 123,
history: "",
exitCode: null,
exitSignal: null,
label: "Terminal 1",
updatedAt: "2026-04-07T00:00:00.000Z",
};
return {
terminal: {
open: vi.fn(async () => ({
threadId: THREAD_ID,
terminalId: "term-1",
cwd: "/repo/project",
worktreePath: null,
status: "running" as const,
pid: 123,
history: "",
exitCode: null,
exitSignal: null,
label: "Terminal 1",
updatedAt: "2026-04-07T00:00:00.000Z",
})),
open: vi.fn(async () => snapshot),
attach: vi.fn(
(
_input: unknown,
listener: (event: TerminalAttachStreamEvent) => void,
_options?: unknown,
) => {
listener({ type: "snapshot", snapshot });
return vi.fn();
},
),
write: vi.fn(async () => undefined),
resize: vi.fn(async () => undefined),
},
@@ -237,7 +259,7 @@ describe("TerminalViewport", () => {
}
});
it("reopens the terminal when the scoped thread reference changes", async () => {
it("reattaches the terminal when the scoped thread reference changes", async () => {
const environmentA = createEnvironmentApi();
const environmentB = createEnvironmentApi();
environmentApiById.set("environment-a", environmentA);
@@ -249,7 +271,7 @@ describe("TerminalViewport", () => {
try {
await vi.waitFor(() => {
expect(environmentA.terminal.open).toHaveBeenCalledTimes(1);
expect(environmentA.terminal.attach).toHaveBeenCalledTimes(1);
});
await mounted.rerender({
@@ -257,7 +279,7 @@ describe("TerminalViewport", () => {
});
await vi.waitFor(() => {
expect(environmentB.terminal.open).toHaveBeenCalledTimes(1);
expect(environmentB.terminal.attach).toHaveBeenCalledTimes(1);
});
expect(terminalDisposeSpy).toHaveBeenCalledTimes(1);
} finally {
@@ -265,7 +287,7 @@ describe("TerminalViewport", () => {
}
});
it("does not reopen the terminal when the scoped thread reference values stay the same", async () => {
it("does not reattach the terminal when the scoped thread reference values stay the same", async () => {
const environment = createEnvironmentApi();
environmentApiById.set("environment-a", environment);
@@ -275,7 +297,7 @@ describe("TerminalViewport", () => {
try {
await vi.waitFor(() => {
expect(environment.terminal.open).toHaveBeenCalledTimes(1);
expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
});
await mounted.rerender({
@@ -283,7 +305,7 @@ describe("TerminalViewport", () => {
});
await vi.waitFor(() => {
expect(environment.terminal.open).toHaveBeenCalledTimes(1);
expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
});
expect(terminalDisposeSpy).not.toHaveBeenCalled();
} finally {
@@ -250,6 +250,12 @@ interface TerminalViewportProps {
keybindings: ResolvedKeybindingsConfig;
}
interface TerminalLaunchLocation {
readonly cwd: string;
readonly worktreePath?: string | null;
readonly runtimeEnv?: Record<string, string>;
}
export function TerminalViewport({
threadRef,
threadId,
@@ -694,7 +700,7 @@ export function TerminalViewport({
// autoFocus is intentionally omitted;
// it is only read at mount time and must not trigger terminal teardown/recreation.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cwd, environmentId, runtimeEnv, terminalId, threadId]);
}, [cwd, environmentId, runtimeEnv, terminalId, threadId, worktreePath]);
useEffect(() => {
if (!autoFocus) return;
@@ -765,6 +771,8 @@ interface ThreadTerminalDrawerProps {
keybindings: ResolvedKeybindingsConfig;
/** Prefer server-provided tab titles when present (e.g. active subprocess name). */
terminalLabelsById?: ReadonlyMap<string, string>;
/** Prefer per-session launch locations when the server already knows a terminal. */
terminalLaunchLocationsById?: ReadonlyMap<string, TerminalLaunchLocation>;
}
interface TerminalActionButtonProps {
@@ -820,6 +828,7 @@ export default function ThreadTerminalDrawer({
onAddTerminalContext,
keybindings,
terminalLabelsById,
terminalLaunchLocationsById,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
const [resizeEpoch, setResizeEpoch] = useState(0);
@@ -938,6 +947,18 @@ export default function ThreadTerminalDrawer({
}
return next;
}, [normalizedTerminalIds, terminalLabelsById]);
const resolveTerminalLaunchLocation = useCallback(
(terminalId: string): TerminalLaunchLocation => {
return (
terminalLaunchLocationsById?.get(terminalId) ?? {
cwd,
...(worktreePath !== undefined ? { worktreePath } : {}),
...(runtimeEnv ? { runtimeEnv } : {}),
}
);
},
[cwd, runtimeEnv, terminalLaunchLocationsById, worktreePath],
);
const splitTerminalActionLabel = hasReachedSplitLimit
? `Split Terminal (max ${MAX_TERMINALS_PER_GROUP} per group)`
: splitShortcutLabel
@@ -1086,6 +1107,8 @@ export default function ThreadTerminalDrawer({
);
}
const activeTerminalLaunchLocation = resolveTerminalLaunchLocation(resolvedActiveTerminalId);
return (
<aside
className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
@@ -1143,38 +1166,47 @@ export default function ThreadTerminalDrawer({
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
}}
>
{visibleTerminalIds.map((terminalId) => (
<div
key={terminalId}
className={`min-h-0 min-w-0 border-l first:border-l-0 ${
terminalId === resolvedActiveTerminalId ? "border-border" : "border-border/70"
}`}
onMouseDown={() => {
if (terminalId !== resolvedActiveTerminalId) {
onActiveTerminalChange(terminalId);
}
}}
>
<div className="h-full p-1">
<TerminalViewport
threadRef={threadRef}
threadId={threadId}
terminalId={terminalId}
terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
cwd={cwd}
{...(worktreePath !== undefined ? { worktreePath } : {})}
{...(runtimeEnv ? { runtimeEnv } : {})}
onSessionExited={() => onCloseTerminal(terminalId)}
onAddTerminalContext={onAddTerminalContext}
focusRequestId={focusRequestId}
autoFocus={terminalId === resolvedActiveTerminalId}
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
keybindings={keybindings}
/>
{visibleTerminalIds.map((terminalId) => {
const terminalLaunchLocation = resolveTerminalLaunchLocation(terminalId);
return (
<div
key={terminalId}
className={`min-h-0 min-w-0 border-l first:border-l-0 ${
terminalId === resolvedActiveTerminalId
? "border-border"
: "border-border/70"
}`}
onMouseDown={() => {
if (terminalId !== resolvedActiveTerminalId) {
onActiveTerminalChange(terminalId);
}
}}
>
<div className="h-full p-1">
<TerminalViewport
threadRef={threadRef}
threadId={threadId}
terminalId={terminalId}
terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
cwd={terminalLaunchLocation.cwd}
{...(terminalLaunchLocation.worktreePath !== undefined
? { worktreePath: terminalLaunchLocation.worktreePath }
: {})}
{...(terminalLaunchLocation.runtimeEnv
? { runtimeEnv: terminalLaunchLocation.runtimeEnv }
: {})}
onSessionExited={() => onCloseTerminal(terminalId)}
onAddTerminalContext={onAddTerminalContext}
focusRequestId={focusRequestId}
autoFocus={terminalId === resolvedActiveTerminalId}
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
keybindings={keybindings}
/>
</div>
</div>
</div>
))}
);
})}
</div>
) : (
<div className="h-full p-1">
@@ -1184,9 +1216,13 @@ export default function ThreadTerminalDrawer({
threadId={threadId}
terminalId={resolvedActiveTerminalId}
terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
cwd={cwd}
{...(worktreePath !== undefined ? { worktreePath } : {})}
{...(runtimeEnv ? { runtimeEnv } : {})}
cwd={activeTerminalLaunchLocation.cwd}
{...(activeTerminalLaunchLocation.worktreePath !== undefined
? { worktreePath: activeTerminalLaunchLocation.worktreePath }
: {})}
{...(activeTerminalLaunchLocation.runtimeEnv
? { runtimeEnv: activeTerminalLaunchLocation.runtimeEnv }
: {})}
onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
onAddTerminalContext={onAddTerminalContext}
focusRequestId={focusRequestId}
+14
View File
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
import {
DEFAULT_TERMINAL_ID,
TerminalAttachInput,
TerminalClearInput,
TerminalCloseInput,
TerminalEvent,
@@ -109,6 +110,19 @@ describe("TerminalOpenInput", () => {
});
});
describe("TerminalAttachInput", () => {
it("accepts explicit inactive-session restart intent", () => {
const parsed = decodeSync(TerminalAttachInput, {
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
cwd: "/tmp/project",
restartIfNotRunning: true,
});
expect(parsed.restartIfNotRunning).toBe(true);
});
});
describe("TerminalWriteInput", () => {
it("accepts non-empty data", () => {
expect(
+1
View File
@@ -53,6 +53,7 @@ export const TerminalAttachInput = Schema.Struct({
cols: Schema.optional(TerminalColsSchema),
rows: Schema.optional(TerminalRowsSchema),
env: Schema.optional(TerminalEnvSchema),
restartIfNotRunning: Schema.optional(Schema.Boolean),
});
export type TerminalAttachInput = Schema.Codec.Encoded<typeof TerminalAttachInput>;