Compare commits

...
Author SHA1 Message Date
Julius Marminge 93d0ac444c Clear terminal history on close and prefer git cwd
- Pass `deleteHistory: true` when closing a terminal
- Fallback path now clears terminal before sending `exit`
- Use `gitCwd` as terminal cwd when available
2026-02-12 21:22:30 -08:00
Julius Marminge 383f61c7ad Use terminal close API with exit fallback in ChatView
- Call `api.terminal.close` when available when closing a terminal tab
- Fall back to writing `exit\n` to preserve compatibility with older/uninitialized terminals
2026-02-12 21:22:30 -08:00
Julius Marmingeandmacroscopeapp[bot] 7e8a9389d5 Update apps/web/src/components/ThreadTerminalDrawer.tsx
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
2026-02-12 21:11:58 -08:00
Julius Marminge a435fa5a21 Migrate thread terminals to grouped layout model
- Replace `terminalLayout`/`splitTerminalIds` with `terminalGroups` and `activeTerminalGroupId`
- Update terminal drawer UI to render grouped splits with a terminal sidebar
- Bump persisted web state to v7 with legacy v6 migration coverage in tests
2026-02-12 21:06:03 -08:00
Julius Marminge 817c5e633d Add close-terminal actions and state handling in thread drawer
- Add terminal close controls in tab and split terminal views
- Send `exit` before closing and update active terminal/focus in chat state
- Add reducer support and tests for closing tabs, split fallback, and final-terminal drawer hide
2026-02-12 20:27:16 -08:00
Julius Marminge d9ab1bfa4a Add per-thread multi-terminal sessions and UI state
- Support multiple terminal IDs per thread across contracts, server manager, and WS handling
- Persist terminal history per terminal ID and allow closing all terminals for a thread
- Update web thread state and terminal drawer to create, split, and switch active terminals
- Expand tests for multi-terminal behavior and terminal ID propagation
2026-02-12 20:13:10 -08:00
15 changed files with 1647 additions and 294 deletions

No files matched your search

+76 -4
View File
@@ -2,10 +2,7 @@ import fs from "node:fs";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import type { import { DEFAULT_TERMINAL_ID, type TerminalEvent, type TerminalOpenInput } from "@t3tools/contracts";
TerminalEvent,
TerminalOpenInput,
} from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest"; import { afterEach, describe, expect, it } from "vitest";
import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter"; import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter";
@@ -109,10 +106,26 @@ function historyLogName(threadId: string): string {
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}.log`; return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}.log`;
} }
function multiTerminalHistoryLogName(threadId: string, terminalId: string): string {
const threadPart = `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
if (terminalId === DEFAULT_TERMINAL_ID) {
return `${threadPart}.log`;
}
return `${threadPart}_${Buffer.from(terminalId, "utf8").toString("base64url")}.log`;
}
function historyLogPath(logsDir: string, threadId = "thread-1"): string { function historyLogPath(logsDir: string, threadId = "thread-1"): string {
return path.join(logsDir, historyLogName(threadId)); return path.join(logsDir, historyLogName(threadId));
} }
function multiTerminalHistoryLogPath(
logsDir: string,
threadId = "thread-1",
terminalId = "default",
): string {
return path.join(logsDir, multiTerminalHistoryLogName(threadId, terminalId));
}
describe("TerminalManager", () => { describe("TerminalManager", () => {
const tempDirs: string[] = []; const tempDirs: string[] = [];
@@ -144,6 +157,7 @@ describe("TerminalManager", () => {
const third = await manager.open(openInput()); const third = await manager.open(openInput());
expect(first.threadId).toBe("thread-1"); expect(first.threadId).toBe("thread-1");
expect(first.terminalId).toBe("default");
expect(second.threadId).toBe("thread-1"); expect(second.threadId).toBe("thread-1");
expect(third.threadId).toBe("thread-1"); expect(third.threadId).toBe("thread-1");
expect(ptyAdapter.spawnInputs).toHaveLength(1); expect(ptyAdapter.spawnInputs).toHaveLength(1);
@@ -167,6 +181,27 @@ describe("TerminalManager", () => {
manager.dispose(); manager.dispose();
}); });
it("supports multiple terminals per thread with isolated sessions", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput({ terminalId: "default" }));
await manager.open(openInput({ terminalId: "term-2" }));
const first = ptyAdapter.processes[0];
const second = ptyAdapter.processes[1];
expect(first).toBeDefined();
expect(second).toBeDefined();
if (!first || !second) return;
await manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" });
await manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" });
expect(first.writes).toEqual(["pwd\n"]);
expect(second.writes).toEqual(["ls\n"]);
expect(ptyAdapter.spawnInputs).toHaveLength(2);
manager.dispose();
});
it("clears transcript and emits cleared event", async () => { it("clears transcript and emits cleared event", async () => {
const { manager, ptyAdapter, logsDir } = makeManager(); const { manager, ptyAdapter, logsDir } = makeManager();
const events: TerminalEvent[] = []; const events: TerminalEvent[] = [];
@@ -184,6 +219,14 @@ describe("TerminalManager", () => {
await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === ""); await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === "");
expect(events.some((event) => event.type === "cleared")).toBe(true); expect(events.some((event) => event.type === "cleared")).toBe(true);
expect(
events.some(
(event) =>
event.type === "cleared" &&
event.threadId === "thread-1" &&
event.terminalId === "default",
),
).toBe(true);
manager.dispose(); manager.dispose();
}); });
@@ -262,6 +305,35 @@ describe("TerminalManager", () => {
manager.dispose(); manager.dispose();
}); });
it("closes all terminals for a thread when close omits terminalId", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput({ terminalId: "default" }));
await manager.open(openInput({ terminalId: "sidecar" }));
const defaultProcess = ptyAdapter.processes[0];
const sidecarProcess = ptyAdapter.processes[1];
expect(defaultProcess).toBeDefined();
expect(sidecarProcess).toBeDefined();
if (!defaultProcess || !sidecarProcess) return;
defaultProcess.emitData("default\n");
sidecarProcess.emitData("sidecar\n");
await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default")));
await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar")));
await manager.close({ threadId: "thread-1", deleteHistory: true });
expect(defaultProcess.killed).toBe(true);
expect(sidecarProcess.killed).toBe(true);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(
false,
);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(
false,
);
manager.dispose();
});
it("loads existing legacy transcript filenames and keeps new naming for writes", async () => { it("loads existing legacy transcript filenames and keeps new naming for writes", async () => {
const { manager, logsDir } = makeManager(); const { manager, logsDir } = makeManager();
const legacyPath = path.join(logsDir, "thread-1.log"); const legacyPath = path.join(logsDir, "thread-1.log");
+185 -71
View File
@@ -3,17 +3,19 @@ import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { import {
DEFAULT_TERMINAL_ID,
type TerminalClearInput,
type TerminalCloseInput, type TerminalCloseInput,
type TerminalEvent, type TerminalEvent,
type TerminalOpenInput, type TerminalOpenInput,
type TerminalResizeInput,
type TerminalSessionSnapshot, type TerminalSessionSnapshot,
type TerminalSessionStatus, type TerminalSessionStatus,
type TerminalThreadInput,
type TerminalWriteInput, type TerminalWriteInput,
terminalClearInputSchema,
terminalCloseInputSchema, terminalCloseInputSchema,
terminalOpenInputSchema, terminalOpenInputSchema,
terminalResizeInputSchema, terminalResizeInputSchema,
terminalThreadInputSchema,
terminalWriteInputSchema, terminalWriteInputSchema,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
@@ -36,6 +38,7 @@ export interface TerminalManagerOptions {
interface TerminalSessionState { interface TerminalSessionState {
threadId: string; threadId: string;
terminalId: string;
cwd: string; cwd: string;
status: TerminalSessionStatus; status: TerminalSessionStatus;
pid: number | null; pid: number | null;
@@ -139,6 +142,14 @@ function toSafeThreadId(threadId: string): string {
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`; return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
} }
function toSafeTerminalId(terminalId: string): string {
return Buffer.from(terminalId, "utf8").toString("base64url");
}
function toSessionKey(threadId: string, terminalId: string): string {
return `${threadId}\u0000${terminalId}`;
}
export class TerminalManager extends EventEmitter<TerminalManagerEvents> { export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private readonly sessions = new Map<string, TerminalSessionState>(); private readonly sessions = new Map<string, TerminalSessionState>();
private readonly logsDir: string; private readonly logsDir: string;
@@ -167,12 +178,14 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
return this.runWithThreadLock(input.threadId, async () => { return this.runWithThreadLock(input.threadId, async () => {
await this.assertValidCwd(input.cwd); await this.assertValidCwd(input.cwd);
const existing = this.sessions.get(input.threadId); const sessionKey = toSessionKey(input.threadId, input.terminalId);
const existing = this.sessions.get(sessionKey);
if (!existing) { if (!existing) {
await this.flushPersistQueue(input.threadId); await this.flushPersistQueue(input.threadId, input.terminalId);
const history = await this.readHistory(input.threadId); const history = await this.readHistory(input.threadId, input.terminalId);
const session: TerminalSessionState = { const session: TerminalSessionState = {
threadId: input.threadId, threadId: input.threadId,
terminalId: input.terminalId,
cwd: input.cwd, cwd: input.cwd,
status: "starting", status: "starting",
pid: null, pid: null,
@@ -186,7 +199,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
unsubscribeData: null, unsubscribeData: null,
unsubscribeExit: null, unsubscribeExit: null,
}; };
this.sessions.set(input.threadId, session); this.sessions.set(sessionKey, session);
this.startSession(session, input, "started"); this.startSession(session, input, "started");
return this.snapshot(session); return this.snapshot(session);
} }
@@ -195,10 +208,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.stopProcess(existing); this.stopProcess(existing);
existing.cwd = input.cwd; existing.cwd = input.cwd;
existing.history = ""; existing.history = "";
await this.persistHistory(existing.threadId, existing.history); await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (existing.status === "exited" || existing.status === "error") { } else if (existing.status === "exited" || existing.status === "error") {
existing.history = ""; existing.history = "";
await this.persistHistory(existing.threadId, existing.history); await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} }
if (!existing.process) { if (!existing.process) {
@@ -219,18 +232,22 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
async write(raw: TerminalWriteInput): Promise<void> { async write(raw: TerminalWriteInput): Promise<void> {
const input = terminalWriteInputSchema.parse(raw); const input = terminalWriteInputSchema.parse(raw);
const session = this.requireSession(input.threadId); const session = this.requireSession(input.threadId, input.terminalId);
if (!session.process || session.status !== "running") { if (!session.process || session.status !== "running") {
throw new Error(`Terminal is not running for thread: ${input.threadId}`); throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
} }
session.process.write(input.data); session.process.write(input.data);
} }
async resize(raw: TerminalThreadInput & { cols: number; rows: number }): Promise<void> { async resize(raw: TerminalResizeInput): Promise<void> {
const input = terminalResizeInputSchema.parse(raw); const input = terminalResizeInputSchema.parse(raw);
const session = this.requireSession(input.threadId); const session = this.requireSession(input.threadId, input.terminalId);
if (!session.process || session.status !== "running") { if (!session.process || session.status !== "running") {
throw new Error(`Terminal is not running for thread: ${input.threadId}`); throw new Error(
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
);
} }
session.cols = input.cols; session.cols = input.cols;
session.rows = input.rows; session.rows = input.rows;
@@ -238,16 +255,17 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
session.process.resize(input.cols, input.rows); session.process.resize(input.cols, input.rows);
} }
async clear(raw: TerminalThreadInput): Promise<void> { async clear(raw: TerminalClearInput): Promise<void> {
const input = terminalThreadInputSchema.parse(raw); const input = terminalClearInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => { await this.runWithThreadLock(input.threadId, async () => {
const session = this.requireSession(input.threadId); const session = this.requireSession(input.threadId, input.terminalId);
session.history = ""; session.history = "";
session.updatedAt = new Date().toISOString(); session.updatedAt = new Date().toISOString();
await this.persistHistory(input.threadId, session.history); await this.persistHistory(input.threadId, input.terminalId, session.history);
this.emitEvent({ this.emitEvent({
type: "cleared", type: "cleared",
threadId: input.threadId, threadId: input.threadId,
terminalId: input.terminalId,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
}); });
}); });
@@ -258,10 +276,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
return this.runWithThreadLock(input.threadId, async () => { return this.runWithThreadLock(input.threadId, async () => {
await this.assertValidCwd(input.cwd); await this.assertValidCwd(input.cwd);
let session = this.sessions.get(input.threadId); const sessionKey = toSessionKey(input.threadId, input.terminalId);
let session = this.sessions.get(sessionKey);
if (!session) { if (!session) {
session = { session = {
threadId: input.threadId, threadId: input.threadId,
terminalId: input.terminalId,
cwd: input.cwd, cwd: input.cwd,
status: "starting", status: "starting",
pid: null, pid: null,
@@ -275,14 +295,14 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
unsubscribeData: null, unsubscribeData: null,
unsubscribeExit: null, unsubscribeExit: null,
}; };
this.sessions.set(input.threadId, session); this.sessions.set(sessionKey, session);
} else { } else {
this.stopProcess(session); this.stopProcess(session);
session.cwd = input.cwd; session.cwd = input.cwd;
} }
session.history = ""; session.history = "";
await this.persistHistory(input.threadId, session.history); await this.persistHistory(input.threadId, input.terminalId, session.history);
this.startSession(session, input, "restarted"); this.startSession(session, input, "restarted");
return this.snapshot(session); return this.snapshot(session);
}); });
@@ -291,14 +311,28 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
async close(raw: TerminalCloseInput): Promise<void> { async close(raw: TerminalCloseInput): Promise<void> {
const input = terminalCloseInputSchema.parse(raw); const input = terminalCloseInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => { await this.runWithThreadLock(input.threadId, async () => {
const session = this.sessions.get(input.threadId); if (input.terminalId) {
if (session) { await this.closeSession(
this.stopProcess(session); input.threadId,
this.sessions.delete(input.threadId); input.terminalId,
input.deleteHistory === true,
);
return;
} }
await this.flushPersistQueue(input.threadId);
const threadSessions = this.sessionsForThread(input.threadId);
for (const session of threadSessions) {
this.stopProcess(session);
this.sessions.delete(toSessionKey(session.threadId, session.terminalId));
}
await Promise.all(
threadSessions.map((session) =>
this.flushPersistQueue(session.threadId, session.terminalId),
),
);
if (input.deleteHistory) { if (input.deleteHistory) {
await this.deleteHistory(input.threadId); await this.deleteAllHistoryForThread(input.threadId);
} }
}); });
} }
@@ -382,6 +416,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.emitEvent({ this.emitEvent({
type: eventType, type: eventType,
threadId: session.threadId, threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
snapshot: this.snapshot(session), snapshot: this.snapshot(session),
}); });
@@ -401,11 +436,13 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.emitEvent({ this.emitEvent({
type: "error", type: "error",
threadId: session.threadId, threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
message, message,
}); });
this.logger.error("failed to start terminal", { this.logger.error("failed to start terminal", {
threadId: session.threadId, threadId: session.threadId,
terminalId: session.terminalId,
error: message, error: message,
...(startedShell ? { shell: startedShell } : {}), ...(startedShell ? { shell: startedShell } : {}),
}); });
@@ -415,10 +452,11 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private onProcessData(session: TerminalSessionState, data: string): void { private onProcessData(session: TerminalSessionState, data: string): void {
session.history = capHistory(`${session.history}${data}`, this.historyLineLimit); session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
session.updatedAt = new Date().toISOString(); session.updatedAt = new Date().toISOString();
this.queuePersist(session.threadId, session.history); this.queuePersist(session.threadId, session.terminalId, session.history);
this.emitEvent({ this.emitEvent({
type: "output", type: "output",
threadId: session.threadId, threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
data, data,
}); });
@@ -435,6 +473,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.emitEvent({ this.emitEvent({
type: "exited", type: "exited",
threadId: session.threadId, threadId: session.threadId,
terminalId: session.terminalId,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
exitCode: session.exitCode, exitCode: session.exitCode,
exitSignal: session.exitSignal, exitSignal: session.exitSignal,
@@ -455,6 +494,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
const message = error instanceof Error ? error.message : String(error); const message = error instanceof Error ? error.message : String(error);
this.logger.warn("failed to kill terminal process", { this.logger.warn("failed to kill terminal process", {
threadId: session.threadId, threadId: session.threadId,
terminalId: session.terminalId,
error: message, error: message,
}); });
} }
@@ -467,69 +507,87 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
session.unsubscribeExit = null; session.unsubscribeExit = null;
} }
private queuePersist(threadId: string, history: string): void { private queuePersist(threadId: string, terminalId: string, history: string): void {
this.pendingPersistHistory.set(threadId, history); const persistenceKey = toSessionKey(threadId, terminalId);
this.schedulePersist(threadId); this.pendingPersistHistory.set(persistenceKey, history);
this.schedulePersist(threadId, terminalId);
} }
private async persistHistory(threadId: string, history: string): Promise<void> { private async persistHistory(
this.clearPersistTimer(threadId); threadId: string,
this.pendingPersistHistory.delete(threadId); terminalId: string,
await this.enqueuePersistWrite(threadId, history); history: string,
): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
this.clearPersistTimer(threadId, terminalId);
this.pendingPersistHistory.delete(persistenceKey);
await this.enqueuePersistWrite(threadId, terminalId, history);
} }
private enqueuePersistWrite(threadId: string, history: string): Promise<void> { private enqueuePersistWrite(
threadId: string,
terminalId: string,
history: string,
): Promise<void> {
const persistenceKey = toSessionKey(threadId, terminalId);
const task = async () => { const task = async () => {
await fs.promises.writeFile(this.historyPath(threadId), history, "utf8"); await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8");
}; };
const previous = this.persistQueues.get(threadId) ?? Promise.resolve(); const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve();
const next = previous const next = previous
.catch(() => undefined) .catch(() => undefined)
.then(task) .then(task)
.catch((error) => { .catch((error) => {
this.logger.warn("failed to persist terminal history", { this.logger.warn("failed to persist terminal history", {
threadId, threadId,
terminalId,
error: error instanceof Error ? error.message : String(error), error: error instanceof Error ? error.message : String(error),
}); });
}); });
this.persistQueues.set(threadId, next); this.persistQueues.set(persistenceKey, next);
const finalized = next.finally(() => { const finalized = next.finally(() => {
if (this.persistQueues.get(threadId) === next) { if (this.persistQueues.get(persistenceKey) === next) {
this.persistQueues.delete(threadId); this.persistQueues.delete(persistenceKey);
} }
if (this.pendingPersistHistory.has(threadId) && !this.persistTimers.has(threadId)) { if (
this.schedulePersist(threadId); this.pendingPersistHistory.has(persistenceKey) &&
!this.persistTimers.has(persistenceKey)
) {
this.schedulePersist(threadId, terminalId);
} }
}); });
void finalized.catch(() => undefined); void finalized.catch(() => undefined);
return finalized; return finalized;
} }
private schedulePersist(threadId: string): void { private schedulePersist(threadId: string, terminalId: string): void {
if (this.persistTimers.has(threadId)) return; const persistenceKey = toSessionKey(threadId, terminalId);
if (this.persistTimers.has(persistenceKey)) return;
const timer = setTimeout(() => { const timer = setTimeout(() => {
this.persistTimers.delete(threadId); this.persistTimers.delete(persistenceKey);
const pendingHistory = this.pendingPersistHistory.get(threadId); const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
if (pendingHistory === undefined) return; if (pendingHistory === undefined) return;
this.pendingPersistHistory.delete(threadId); this.pendingPersistHistory.delete(persistenceKey);
void this.enqueuePersistWrite(threadId, pendingHistory); void this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
}, this.persistDebounceMs); }, this.persistDebounceMs);
this.persistTimers.set(threadId, timer); this.persistTimers.set(persistenceKey, timer);
} }
private clearPersistTimer(threadId: string): void { private clearPersistTimer(threadId: string, terminalId: string): void {
const timer = this.persistTimers.get(threadId); const persistenceKey = toSessionKey(threadId, terminalId);
const timer = this.persistTimers.get(persistenceKey);
if (!timer) return; if (!timer) return;
clearTimeout(timer); clearTimeout(timer);
this.persistTimers.delete(threadId); this.persistTimers.delete(persistenceKey);
} }
private async readHistory(threadId: string): Promise<string> { private async readHistory(threadId: string, terminalId: string): Promise<string> {
const historyPath = this.historyPath(threadId, terminalId);
try { try {
const raw = await fs.promises.readFile(this.historyPath(threadId), "utf8"); const raw = await fs.promises.readFile(historyPath, "utf8");
const capped = capHistory(raw, this.historyLineLimit); const capped = capHistory(raw, this.historyLineLimit);
if (capped !== raw) { if (capped !== raw) {
await fs.promises.writeFile(this.historyPath(threadId), capped, "utf8"); await fs.promises.writeFile(historyPath, capped, "utf8");
} }
return capped; return capped;
} catch (error) { } catch (error) {
@@ -538,6 +596,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
} }
} }
if (terminalId !== DEFAULT_TERMINAL_ID) {
return "";
}
try { try {
const raw = await fs.promises.readFile(this.legacyHistoryPath(threadId), "utf8"); const raw = await fs.promises.readFile(this.legacyHistoryPath(threadId), "utf8");
const capped = capHistory(raw, this.historyLineLimit); const capped = capHistory(raw, this.historyLineLimit);
@@ -553,31 +615,34 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
} }
} }
private async deleteHistory(threadId: string): Promise<void> { private async deleteHistory(threadId: string, terminalId: string): Promise<void> {
const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })];
if (terminalId === DEFAULT_TERMINAL_ID) {
deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }));
}
try { try {
await Promise.all([ await Promise.all(deletions);
fs.promises.rm(this.historyPath(threadId), { force: true }),
fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }),
]);
} catch (error) { } catch (error) {
this.logger.warn("failed to delete terminal history", { this.logger.warn("failed to delete terminal history", {
threadId, threadId,
terminalId,
error: error instanceof Error ? error.message : String(error), error: error instanceof Error ? error.message : String(error),
}); });
} }
} }
private async flushPersistQueue(threadId: string): Promise<void> { private async flushPersistQueue(threadId: string, terminalId: string): Promise<void> {
this.clearPersistTimer(threadId); const persistenceKey = toSessionKey(threadId, terminalId);
this.clearPersistTimer(threadId, terminalId);
while (true) { while (true) {
const pendingHistory = this.pendingPersistHistory.get(threadId); const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
if (pendingHistory !== undefined) { if (pendingHistory !== undefined) {
this.pendingPersistHistory.delete(threadId); this.pendingPersistHistory.delete(persistenceKey);
await this.enqueuePersistWrite(threadId, pendingHistory); await this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
} }
const pending = this.persistQueues.get(threadId); const pending = this.persistQueues.get(persistenceKey);
if (!pending) { if (!pending) {
return; return;
} }
@@ -600,10 +665,54 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
} }
} }
private requireSession(threadId: string): TerminalSessionState { private async closeSession(
const session = this.sessions.get(threadId); threadId: string,
terminalId: string,
deleteHistory: boolean,
): Promise<void> {
const key = toSessionKey(threadId, terminalId);
const session = this.sessions.get(key);
if (session) {
this.stopProcess(session);
this.sessions.delete(key);
}
await this.flushPersistQueue(threadId, terminalId);
if (deleteHistory) {
await this.deleteHistory(threadId, terminalId);
}
}
private sessionsForThread(threadId: string): TerminalSessionState[] {
return [...this.sessions.values()].filter((session) => session.threadId === threadId);
}
private async deleteAllHistoryForThread(threadId: string): Promise<void> {
const threadPrefix = `${toSafeThreadId(threadId)}_`;
try {
const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true });
const removals = entries
.filter((entry) => entry.isFile())
.map((entry) => entry.name)
.filter(
(name) =>
name === `${toSafeThreadId(threadId)}.log` ||
name === `${legacySafeThreadId(threadId)}.log` ||
name.startsWith(threadPrefix),
)
.map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true }));
await Promise.all(removals);
} catch (error) {
this.logger.warn("failed to delete terminal histories for thread", {
threadId,
error: error instanceof Error ? error.message : String(error),
});
}
}
private requireSession(threadId: string, terminalId: string): TerminalSessionState {
const session = this.sessions.get(toSessionKey(threadId, terminalId));
if (!session) { if (!session) {
throw new Error(`Unknown terminal thread: ${threadId}`); throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`);
} }
return session; return session;
} }
@@ -611,6 +720,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
private snapshot(session: TerminalSessionState): TerminalSessionSnapshot { private snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
return { return {
threadId: session.threadId, threadId: session.threadId,
terminalId: session.terminalId,
cwd: session.cwd, cwd: session.cwd,
status: session.status, status: session.status,
pid: session.pid, pid: session.pid,
@@ -625,8 +735,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
this.emit("event", event); this.emit("event", event);
} }
private historyPath(threadId: string): string { private historyPath(threadId: string, terminalId: string): string {
return path.join(this.logsDir, `${toSafeThreadId(threadId)}.log`); const threadPart = toSafeThreadId(threadId);
if (terminalId === DEFAULT_TERMINAL_ID) {
return path.join(this.logsDir, `${threadPart}.log`);
}
return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`);
} }
private legacyHistoryPath(threadId: string): string { private legacyHistoryPath(threadId: string): string {
+39 -8
View File
@@ -7,14 +7,21 @@ import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer"; import { createServer } from "./wsServer";
import WebSocket from "ws"; import WebSocket from "ws";
import { WS_CHANNELS, WS_METHODS, type WsPush, type WsResponse } from "@t3tools/contracts"; import {
DEFAULT_TERMINAL_ID,
WS_CHANNELS,
WS_METHODS,
type WsPush,
type WsResponse,
} from "@t3tools/contracts";
import { ProjectRegistry } from "./projectRegistry"; import { ProjectRegistry } from "./projectRegistry";
import type { import type {
TerminalClearInput,
TerminalCloseInput, TerminalCloseInput,
TerminalEvent, TerminalEvent,
TerminalOpenInput, TerminalOpenInput,
TerminalResizeInput,
TerminalSessionSnapshot, TerminalSessionSnapshot,
TerminalThreadInput,
TerminalWriteInput, TerminalWriteInput,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import type { TerminalManager } from "./terminalManager"; import type { TerminalManager } from "./terminalManager";
@@ -29,10 +36,16 @@ const pendingBySocket = new WeakMap<WebSocket, PendingMessages>();
class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }> { class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }> {
private readonly sessions = new Map<string, TerminalSessionSnapshot>(); private readonly sessions = new Map<string, TerminalSessionSnapshot>();
private key(threadId: string, terminalId: string): string {
return `${threadId}\u0000${terminalId}`;
}
async open(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> { async open(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const now = new Date().toISOString(); const now = new Date().toISOString();
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const snapshot: TerminalSessionSnapshot = { const snapshot: TerminalSessionSnapshot = {
threadId: input.threadId, threadId: input.threadId,
terminalId,
cwd: input.cwd, cwd: input.cwd,
status: "running", status: "running",
pid: 4242, pid: 4242,
@@ -41,11 +54,12 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
exitSignal: null, exitSignal: null,
updatedAt: now, updatedAt: now,
}; };
this.sessions.set(input.threadId, snapshot); this.sessions.set(this.key(input.threadId, terminalId), snapshot);
queueMicrotask(() => { queueMicrotask(() => {
this.emit("event", { this.emit("event", {
type: "started", type: "started",
threadId: input.threadId, threadId: input.threadId,
terminalId,
createdAt: now, createdAt: now,
snapshot, snapshot,
}); });
@@ -54,7 +68,8 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
} }
async write(input: TerminalWriteInput): Promise<void> { async write(input: TerminalWriteInput): Promise<void> {
const existing = this.sessions.get(input.threadId); const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const existing = this.sessions.get(this.key(input.threadId, terminalId));
if (!existing) { if (!existing) {
throw new Error(`Unknown terminal thread: ${input.threadId}`); throw new Error(`Unknown terminal thread: ${input.threadId}`);
} }
@@ -62,19 +77,22 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
this.emit("event", { this.emit("event", {
type: "output", type: "output",
threadId: input.threadId, threadId: input.threadId,
terminalId,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
data: input.data, data: input.data,
}); });
}); });
} }
async resize(_input: TerminalThreadInput & { cols: number; rows: number }): Promise<void> {} async resize(_input: TerminalResizeInput): Promise<void> {}
async clear(input: TerminalThreadInput): Promise<void> { async clear(input: TerminalClearInput): Promise<void> {
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
queueMicrotask(() => { queueMicrotask(() => {
this.emit("event", { this.emit("event", {
type: "cleared", type: "cleared",
threadId: input.threadId, threadId: input.threadId,
terminalId,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
}); });
}); });
@@ -82,8 +100,10 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
async restart(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> { async restart(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
const now = new Date().toISOString(); const now = new Date().toISOString();
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const snapshot: TerminalSessionSnapshot = { const snapshot: TerminalSessionSnapshot = {
threadId: input.threadId, threadId: input.threadId,
terminalId,
cwd: input.cwd, cwd: input.cwd,
status: "running", status: "running",
pid: 5252, pid: 5252,
@@ -92,11 +112,12 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
exitSignal: null, exitSignal: null,
updatedAt: now, updatedAt: now,
}; };
this.sessions.set(input.threadId, snapshot); this.sessions.set(this.key(input.threadId, terminalId), snapshot);
queueMicrotask(() => { queueMicrotask(() => {
this.emit("event", { this.emit("event", {
type: "restarted", type: "restarted",
threadId: input.threadId, threadId: input.threadId,
terminalId,
createdAt: now, createdAt: now,
snapshot, snapshot,
}); });
@@ -105,7 +126,15 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
} }
async close(input: TerminalCloseInput): Promise<void> { async close(input: TerminalCloseInput): Promise<void> {
this.sessions.delete(input.threadId); if (input.terminalId) {
this.sessions.delete(this.key(input.threadId, input.terminalId));
return;
}
for (const key of [...this.sessions.keys()]) {
if (key.startsWith(`${input.threadId}\u0000`)) {
this.sessions.delete(key);
}
}
} }
dispose(): void {} dispose(): void {}
@@ -340,6 +369,7 @@ describe("WebSocket Server", () => {
}); });
expect(open.error).toBeUndefined(); expect(open.error).toBeUndefined();
expect((open.result as TerminalSessionSnapshot).threadId).toBe("thread-1"); expect((open.result as TerminalSessionSnapshot).threadId).toBe("thread-1");
expect((open.result as TerminalSessionSnapshot).terminalId).toBe(DEFAULT_TERMINAL_ID);
const write = await sendRequest(ws, WS_METHODS.terminalWrite, { const write = await sendRequest(ws, WS_METHODS.terminalWrite, {
threadId: "thread-1", threadId: "thread-1",
@@ -376,6 +406,7 @@ describe("WebSocket Server", () => {
const manualEvent: TerminalEvent = { const manualEvent: TerminalEvent = {
type: "output", type: "output",
threadId: "thread-1", threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
data: "manual test output\n", data: "manual test output\n",
}; };
+10 -13
View File
@@ -7,7 +7,7 @@ import Sidebar from "./components/Sidebar";
import { isElectron } from "./env"; import { isElectron } from "./env";
import { DEFAULT_MODEL } from "./model-logic"; import { DEFAULT_MODEL } from "./model-logic";
import { StoreProvider, useStore } from "./store"; import { StoreProvider, useStore } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import { onServerWelcome } from "./wsNativeApi"; import { onServerWelcome } from "./wsNativeApi";
import { useNativeApi } from "./hooks/useNativeApi"; import { useNativeApi } from "./hooks/useNativeApi";
@@ -27,18 +27,6 @@ function EventRouter() {
}); });
}, [api, dispatch]); }, [api, dispatch]);
useEffect(() => {
if (!api) return;
return api.terminal.onEvent((event) => {
if (event.type !== "exited") return;
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: event.threadId,
open: false,
});
});
}, [api, dispatch]);
return null; return null;
} }
@@ -93,6 +81,15 @@ function AutoProjectBootstrap() {
model: DEFAULT_MODEL, model: DEFAULT_MODEL,
terminalOpen: false, terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT, terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null, session: null,
messages: [], messages: [],
events: [], events: [],
+68 -8
View File
@@ -269,6 +269,65 @@ export default function ChatView() {
open: !isOpen, open: !isOpen,
}); });
}, [activeThread?.terminalOpen, activeThreadId, dispatch]); }, [activeThread?.terminalOpen, activeThreadId, dispatch]);
const splitTerminal = useCallback(() => {
if (!activeThreadId) return;
dispatch({
type: "SPLIT_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch]);
const createNewTerminal = useCallback(() => {
if (!activeThreadId) return;
dispatch({
type: "NEW_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId: `terminal-${crypto.randomUUID()}`,
});
setTerminalFocusRequestId((value) => value + 1);
}, [activeThreadId, dispatch]);
const activateTerminal = useCallback(
(terminalId: string) => {
if (!activeThreadId) return;
dispatch({
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: activeThreadId,
terminalId,
});
setTerminalFocusRequestId((value) => value + 1);
},
[activeThreadId, dispatch],
);
const closeTerminal = useCallback(
(terminalId: string) => {
if (!activeThreadId || !api) return;
const fallbackExitWrite = () =>
api.terminal
.write({ threadId: activeThreadId, terminalId, data: "exit\n" })
.catch(() => undefined);
const fallbackClearAndExit = () =>
api.terminal
.clear({ threadId: activeThreadId, terminalId })
.catch(() => undefined)
.then(() => fallbackExitWrite())
.catch(() => undefined);
if ("close" in api.terminal && typeof api.terminal.close === "function") {
void api.terminal
.close({ threadId: activeThreadId, terminalId, deleteHistory: true })
.catch(() => fallbackClearAndExit());
} else {
void fallbackClearAndExit();
}
dispatch({
type: "CLOSE_THREAD_TERMINAL",
threadId: activeThreadId,
terminalId,
});
setTerminalFocusRequestId((value) => value + 1);
},
[activeThreadId, api, dispatch],
);
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => { const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
if (mode === state.runtimeMode) return; if (mode === state.runtimeMode) return;
@@ -1449,9 +1508,17 @@ export default function ChatView() {
key={activeThread.id} key={activeThread.id}
api={api} api={api}
threadId={activeThread.id} threadId={activeThread.id}
cwd={activeProject.cwd} cwd={gitCwd ?? activeProject.cwd}
height={activeThread.terminalHeight} height={activeThread.terminalHeight}
terminalIds={activeThread.terminalIds}
activeTerminalId={activeThread.activeTerminalId}
terminalGroups={activeThread.terminalGroups}
activeTerminalGroupId={activeThread.activeTerminalGroupId}
focusRequestId={terminalFocusRequestId} focusRequestId={terminalFocusRequestId}
onSplitTerminal={splitTerminal}
onNewTerminal={createNewTerminal}
onActiveTerminalChange={activateTerminal}
onCloseTerminal={closeTerminal}
onHeightChange={(height) => onHeightChange={(height) =>
dispatch({ dispatch({
type: "SET_THREAD_TERMINAL_HEIGHT", type: "SET_THREAD_TERMINAL_HEIGHT",
@@ -1459,13 +1526,6 @@ export default function ChatView() {
height, height,
}) })
} }
onThreadExited={() =>
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThread.id,
open: false,
})
}
/> />
)} )}
+15 -1
View File
@@ -5,7 +5,12 @@ import { useTheme } from "../hooks/useTheme";
import { DEFAULT_MODEL } from "../model-logic"; import { DEFAULT_MODEL } from "../model-logic";
import { derivePendingApprovals } from "../session-logic"; import { derivePendingApprovals } from "../session-logic";
import { useStore } from "../store"; import { useStore } from "../store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, type Project, type Thread } from "../types"; import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
type Project,
type Thread,
} from "../types";
import { useNativeApi } from "../hooks/useNativeApi"; import { useNativeApi } from "../hooks/useNativeApi";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const; const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
@@ -112,6 +117,15 @@ export default function Sidebar() {
model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL, model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL,
terminalOpen: false, terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT, terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null, session: null,
messages: [], messages: [],
events: [], events: [],
+502 -165
View File
@@ -1,10 +1,12 @@
import { FitAddon } from "@xterm/addon-fit"; import { FitAddon } from "@xterm/addon-fit";
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
import { type NativeApi } from "@t3tools/contracts"; import { type NativeApi } from "@t3tools/contracts";
import { Terminal, type ITheme } from "@xterm/xterm"; import { Terminal, type ITheme } from "@xterm/xterm";
import { import {
type PointerEvent as ReactPointerEvent, type PointerEvent as ReactPointerEvent,
useCallback, useCallback,
useEffect, useEffect,
useMemo,
useRef, useRef,
useState, useState,
} from "react"; } from "react";
@@ -15,7 +17,11 @@ import {
resolvePathLinkTarget, resolvePathLinkTarget,
} from "../terminal-links"; } from "../terminal-links";
import { isTerminalClearShortcut } from "../terminal-shortcuts"; import { isTerminalClearShortcut } from "../terminal-shortcuts";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "../types"; import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
type ThreadTerminalGroup,
} from "../types";
const MIN_DRAWER_HEIGHT = 180; const MIN_DRAWER_HEIGHT = 180;
const MAX_DRAWER_HEIGHT_RATIO = 0.75; const MAX_DRAWER_HEIGHT_RATIO = 0.75;
@@ -103,162 +109,30 @@ function terminalThemeFromApp(): ITheme {
}; };
} }
interface ThreadTerminalDrawerProps { interface TerminalViewportProps {
api: NativeApi; api: NativeApi;
threadId: string; threadId: string;
terminalId: string;
cwd: string; cwd: string;
height: number;
focusRequestId: number; focusRequestId: number;
onHeightChange: (height: number) => void; autoFocus: boolean;
onThreadExited: () => void; resizeEpoch: number;
drawerHeight: number;
} }
export default function ThreadTerminalDrawer({ function TerminalViewport({
api, api,
threadId, threadId,
terminalId,
cwd, cwd,
height,
focusRequestId, focusRequestId,
onHeightChange, autoFocus,
onThreadExited, resizeEpoch,
}: ThreadTerminalDrawerProps) { drawerHeight,
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height)); }: TerminalViewportProps) {
const containerRef = useRef<HTMLDivElement>(null); const containerRef = useRef<HTMLDivElement>(null);
const terminalRef = useRef<Terminal | null>(null); const terminalRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null); const fitAddonRef = useRef<FitAddon | null>(null);
const drawerHeightRef = useRef(drawerHeight);
const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
const onHeightChangeRef = useRef(onHeightChange);
const onThreadExitedRef = useRef(onThreadExited);
const resizeStateRef = useRef<{
pointerId: number;
startY: number;
startHeight: number;
} | null>(null);
const didResizeDuringDragRef = useRef(false);
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
}, [onHeightChange]);
useEffect(() => {
onThreadExitedRef.current = onThreadExited;
}, [onThreadExited]);
useEffect(() => {
drawerHeightRef.current = drawerHeight;
}, [drawerHeight]);
const syncHeight = useCallback(
(nextHeight: number) => {
const clampedHeight = clampDrawerHeight(nextHeight);
if (lastSyncedHeightRef.current === clampedHeight) return;
lastSyncedHeightRef.current = clampedHeight;
onHeightChangeRef.current(clampedHeight);
},
[],
);
const fitAndResizeTerminal = useCallback((preserveBottom = false) => {
const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
const wasAtBottom =
preserveBottom &&
activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
activeFitAddon.fit();
if (wasAtBottom) {
activeTerminal.scrollToBottom();
}
void api.terminal
.resize({
threadId,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
})
.catch(() => undefined);
}, [api, threadId]);
useEffect(() => {
const clampedHeight = clampDrawerHeight(height);
setDrawerHeight(clampedHeight);
lastSyncedHeightRef.current = clampedHeight;
}, [height, threadId]);
const handleResizePointerDown = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
didResizeDuringDragRef.current = false;
resizeStateRef.current = {
pointerId: event.pointerId,
startY: event.clientY,
startHeight: drawerHeightRef.current,
};
},
[],
);
const handleResizePointerMove = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
event.preventDefault();
const clampedHeight = clampDrawerHeight(
resizeState.startHeight + (resizeState.startY - event.clientY),
);
if (clampedHeight === drawerHeightRef.current) {
return;
}
didResizeDuringDragRef.current = true;
drawerHeightRef.current = clampedHeight;
setDrawerHeight(clampedHeight);
},
[],
);
const handleResizePointerEnd = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
resizeStateRef.current = null;
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
if (!didResizeDuringDragRef.current) {
return;
}
syncHeight(drawerHeightRef.current);
fitAndResizeTerminal(true);
},
[fitAndResizeTerminal, syncHeight],
);
useEffect(() => {
const onWindowResize = () => {
const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
const changed = clampedHeight !== drawerHeightRef.current;
if (changed) {
setDrawerHeight(clampedHeight);
} else {
fitAndResizeTerminal(true);
}
if (!resizeStateRef.current) {
syncHeight(clampedHeight);
}
};
window.addEventListener("resize", onWindowResize);
return () => {
window.removeEventListener("resize", onWindowResize);
};
}, [fitAndResizeTerminal, syncHeight]);
useEffect(() => {
return () => {
syncHeight(drawerHeightRef.current);
};
}, [syncHeight]);
useEffect(() => { useEffect(() => {
const mount = containerRef.current; const mount = containerRef.current;
@@ -287,7 +161,7 @@ export default function ThreadTerminalDrawer({
const activeTerminal = terminalRef.current; const activeTerminal = terminalRef.current;
if (!activeTerminal) return; if (!activeTerminal) return;
try { try {
await api.terminal.write({ threadId, data: "\u000c" }); await api.terminal.write({ threadId, terminalId, data: "\u000c" });
} catch (error) { } catch (error) {
writeSystemMessage( writeSystemMessage(
activeTerminal, activeTerminal,
@@ -367,7 +241,7 @@ export default function ThreadTerminalDrawer({
const inputDisposable = terminal.onData((data) => { const inputDisposable = terminal.onData((data) => {
void api.terminal void api.terminal
.write({ threadId, data }) .write({ threadId, terminalId, data })
.catch((err) => .catch((err) =>
writeSystemMessage( writeSystemMessage(
terminal, terminal,
@@ -395,6 +269,7 @@ export default function ThreadTerminalDrawer({
activeFitAddon.fit(); activeFitAddon.fit();
const snapshot = await api.terminal.open({ const snapshot = await api.terminal.open({
threadId, threadId,
terminalId,
cwd, cwd,
cols: activeTerminal.cols, cols: activeTerminal.cols,
rows: activeTerminal.rows, rows: activeTerminal.rows,
@@ -404,9 +279,11 @@ export default function ThreadTerminalDrawer({
if (snapshot.history.length > 0) { if (snapshot.history.length > 0) {
activeTerminal.write(snapshot.history); activeTerminal.write(snapshot.history);
} }
window.requestAnimationFrame(() => { if (autoFocus) {
activeTerminal.focus(); window.requestAnimationFrame(() => {
}); activeTerminal.focus();
});
}
} catch (err) { } catch (err) {
if (disposed) return; if (disposed) return;
writeSystemMessage( writeSystemMessage(
@@ -417,7 +294,7 @@ export default function ThreadTerminalDrawer({
}; };
const unsubscribe = api.terminal.onEvent((event) => { const unsubscribe = api.terminal.onEvent((event) => {
if (event.threadId !== threadId) return; if (event.threadId !== threadId || event.terminalId !== terminalId) return;
const activeTerminal = terminalRef.current; const activeTerminal = terminalRef.current;
if (!activeTerminal) return; if (!activeTerminal) return;
@@ -446,12 +323,37 @@ export default function ThreadTerminalDrawer({
} }
if (event.type === "exited") { if (event.type === "exited") {
onThreadExitedRef.current(); const details = [
typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
]
.filter((value): value is string => value !== null)
.join(", ");
writeSystemMessage(
activeTerminal,
details.length > 0 ? `Process exited (${details})` : "Process exited",
);
} }
}); });
const fitTimer = window.setTimeout(() => { const fitTimer = window.setTimeout(() => {
fitAndResizeTerminal(true); const activeTerminal = terminalRef.current;
const activeFitAddon = fitAddonRef.current;
if (!activeTerminal || !activeFitAddon) return;
const wasAtBottom =
activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
activeFitAddon.fit();
if (wasAtBottom) {
activeTerminal.scrollToBottom();
}
void api.terminal
.resize({
threadId,
terminalId,
cols: activeTerminal.cols,
rows: activeTerminal.rows,
})
.catch(() => undefined);
}, 30); }, 30);
void openTerminal(); void openTerminal();
@@ -466,9 +368,10 @@ export default function ThreadTerminalDrawer({
fitAddonRef.current = null; fitAddonRef.current = null;
terminal.dispose(); terminal.dispose();
}; };
}, [api, cwd, fitAndResizeTerminal, threadId]); }, [api, cwd, terminalId, threadId]);
useEffect(() => { useEffect(() => {
if (!autoFocus) return;
const terminal = terminalRef.current; const terminal = terminalRef.current;
if (!terminal) return; if (!terminal) return;
const frame = window.requestAnimationFrame(() => { const frame = window.requestAnimationFrame(() => {
@@ -477,7 +380,7 @@ export default function ThreadTerminalDrawer({
return () => { return () => {
window.cancelAnimationFrame(frame); window.cancelAnimationFrame(frame);
}; };
}, [focusRequestId]); }, [autoFocus, focusRequestId]);
useEffect(() => { useEffect(() => {
const terminal = terminalRef.current; const terminal = terminalRef.current;
@@ -492,6 +395,7 @@ export default function ThreadTerminalDrawer({
void api.terminal void api.terminal
.resize({ .resize({
threadId, threadId,
terminalId,
cols: terminal.cols, cols: terminal.cols,
rows: terminal.rows, rows: terminal.rows,
}) })
@@ -500,27 +404,460 @@ export default function ThreadTerminalDrawer({
return () => { return () => {
window.cancelAnimationFrame(frame); window.cancelAnimationFrame(frame);
}; };
}, [api, cwd, drawerHeight, threadId]); }, [api, drawerHeight, resizeEpoch, terminalId, threadId]);
return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
}
interface ThreadTerminalDrawerProps {
api: NativeApi;
threadId: string;
cwd: string;
height: number;
terminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
focusRequestId: number;
onSplitTerminal: () => void;
onNewTerminal: () => void;
onActiveTerminalChange: (terminalId: string) => void;
onCloseTerminal: (terminalId: string) => void;
onHeightChange: (height: number) => void;
}
export default function ThreadTerminalDrawer({
api,
threadId,
cwd,
height,
terminalIds,
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
focusRequestId,
onSplitTerminal,
onNewTerminal,
onActiveTerminalChange,
onCloseTerminal,
onHeightChange,
}: ThreadTerminalDrawerProps) {
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
const [resizeEpoch, setResizeEpoch] = useState(0);
const drawerHeightRef = useRef(drawerHeight);
const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
const onHeightChangeRef = useRef(onHeightChange);
const resizeStateRef = useRef<{
pointerId: number;
startY: number;
startHeight: number;
} | null>(null);
const didResizeDuringDragRef = useRef(false);
const normalizedTerminalIds = useMemo(() => {
const cleaned = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
return cleaned.length > 0 ? cleaned : [DEFAULT_THREAD_TERMINAL_ID];
}, [terminalIds]);
const resolvedActiveTerminalId = normalizedTerminalIds.includes(activeTerminalId)
? activeTerminalId
: (normalizedTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const resolvedTerminalGroups = useMemo(() => {
const validTerminalIdSet = new Set(normalizedTerminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const nextGroups: ThreadTerminalGroup[] = [];
const assignUniqueGroupId = (groupId: string): string => {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
};
for (const terminalGroup of terminalGroups) {
const nextTerminalIds = [
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
].filter((terminalId) => {
if (!validTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (nextTerminalIds.length === 0) continue;
for (const terminalId of nextTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
terminalGroup.id.trim().length > 0
? terminalGroup.id.trim()
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
nextGroups.push({
id: assignUniqueGroupId(baseGroupId),
terminalIds: nextTerminalIds,
});
}
for (const terminalId of normalizedTerminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
nextGroups.push({
id: assignUniqueGroupId(`group-${terminalId}`),
terminalIds: [terminalId],
});
}
if (nextGroups.length > 0) {
return nextGroups;
}
return [
{
id: `group-${resolvedActiveTerminalId}`,
terminalIds: [resolvedActiveTerminalId],
},
];
}, [normalizedTerminalIds, resolvedActiveTerminalId, terminalGroups]);
const resolvedActiveGroupIndex = useMemo(() => {
const indexById = resolvedTerminalGroups.findIndex(
(terminalGroup) => terminalGroup.id === activeTerminalGroupId,
);
if (indexById >= 0) return indexById;
const indexByTerminal = resolvedTerminalGroups.findIndex((terminalGroup) =>
terminalGroup.terminalIds.includes(resolvedActiveTerminalId),
);
return indexByTerminal >= 0 ? indexByTerminal : 0;
}, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
const visibleTerminalIds =
resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [resolvedActiveTerminalId];
const hasTerminalSidebar = normalizedTerminalIds.length > 1;
const isSplitView = visibleTerminalIds.length > 1;
const showGroupHeaders =
resolvedTerminalGroups.length > 1 ||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
const terminalLabelById = useMemo(
() =>
new Map(
normalizedTerminalIds.map((terminalId, index) => [terminalId, `Terminal ${index + 1}`]),
),
[normalizedTerminalIds],
);
useEffect(() => {
onHeightChangeRef.current = onHeightChange;
}, [onHeightChange]);
useEffect(() => {
drawerHeightRef.current = drawerHeight;
}, [drawerHeight]);
const syncHeight = useCallback((nextHeight: number) => {
const clampedHeight = clampDrawerHeight(nextHeight);
if (lastSyncedHeightRef.current === clampedHeight) return;
lastSyncedHeightRef.current = clampedHeight;
onHeightChangeRef.current(clampedHeight);
}, []);
useEffect(() => {
const clampedHeight = clampDrawerHeight(height);
setDrawerHeight(clampedHeight);
drawerHeightRef.current = clampedHeight;
lastSyncedHeightRef.current = clampedHeight;
}, [height, threadId]);
const handleResizePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
if (event.button !== 0) return;
event.preventDefault();
event.currentTarget.setPointerCapture(event.pointerId);
didResizeDuringDragRef.current = false;
resizeStateRef.current = {
pointerId: event.pointerId,
startY: event.clientY,
startHeight: drawerHeightRef.current,
};
}, []);
const handleResizePointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
event.preventDefault();
const clampedHeight = clampDrawerHeight(
resizeState.startHeight + (resizeState.startY - event.clientY),
);
if (clampedHeight === drawerHeightRef.current) {
return;
}
didResizeDuringDragRef.current = true;
drawerHeightRef.current = clampedHeight;
setDrawerHeight(clampedHeight);
}, []);
const handleResizePointerEnd = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const resizeState = resizeStateRef.current;
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
resizeStateRef.current = null;
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
if (!didResizeDuringDragRef.current) {
return;
}
syncHeight(drawerHeightRef.current);
setResizeEpoch((value) => value + 1);
},
[syncHeight],
);
useEffect(() => {
const onWindowResize = () => {
const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
const changed = clampedHeight !== drawerHeightRef.current;
if (changed) {
setDrawerHeight(clampedHeight);
drawerHeightRef.current = clampedHeight;
}
if (!resizeStateRef.current) {
syncHeight(clampedHeight);
}
setResizeEpoch((value) => value + 1);
};
window.addEventListener("resize", onWindowResize);
return () => {
window.removeEventListener("resize", onWindowResize);
};
}, [syncHeight]);
useEffect(() => {
return () => {
syncHeight(drawerHeightRef.current);
};
}, [syncHeight]);
return ( return (
<aside <aside
className="thread-terminal-drawer flex shrink-0 flex-col border-t border-border/80 bg-background" className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
style={{ height: `${drawerHeight}px` }} style={{ height: `${drawerHeight}px` }}
> >
<div <div
className="flex h-2 cursor-row-resize items-center justify-center" className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
onPointerDown={handleResizePointerDown} onPointerDown={handleResizePointerDown}
onPointerMove={handleResizePointerMove} onPointerMove={handleResizePointerMove}
onPointerUp={handleResizePointerEnd} onPointerUp={handleResizePointerEnd}
onPointerCancel={handleResizePointerEnd} onPointerCancel={handleResizePointerEnd}
> />
<div className="h-px w-10 rounded-full bg-border/80" />
</div> {!hasTerminalSidebar && (
<div className="min-h-0 w-full flex-1 px-1.5 pb-1"> <div className="pointer-events-none absolute right-2 top-2 z-20">
<div <div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
ref={containerRef} <button
className="h-full w-full overflow-hidden rounded-[4px]" type="button"
/> className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onSplitTerminal}
aria-label="Split Terminal"
title="Split Terminal"
>
<SquareSplitHorizontal className="size-3.25" />
</button>
<div className="h-4 w-px bg-border/80" />
<button
type="button"
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={onNewTerminal}
aria-label="New Terminal"
title="New Terminal"
>
<Plus className="size-3.25" />
</button>
<div className="h-4 w-px bg-border/80" />
<button
type="button"
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
aria-label="Close Terminal"
title="Close Terminal"
>
<Trash2 className="size-3.25" />
</button>
</div>
</div>
)}
<div className="min-h-0 w-full flex-1">
<div className={`flex h-full min-h-0 ${hasTerminalSidebar ? "gap-1.5" : ""}`}>
<div className="min-w-0 flex-1">
{isSplitView ? (
<div
className="grid h-full w-full gap-0 overflow-x-auto"
style={{
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 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
api={api}
threadId={threadId}
terminalId={terminalId}
cwd={cwd}
focusRequestId={focusRequestId}
autoFocus={terminalId === resolvedActiveTerminalId}
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
/>
</div>
</div>
))}
</div>
) : (
<div className="h-full p-1">
<TerminalViewport
key={resolvedActiveTerminalId}
api={api}
threadId={threadId}
terminalId={resolvedActiveTerminalId}
cwd={cwd}
focusRequestId={focusRequestId}
autoFocus
resizeEpoch={resizeEpoch}
drawerHeight={drawerHeight}
/>
</div>
)}
</div>
{hasTerminalSidebar && (
<aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
<div className="inline-flex h-full items-stretch">
<button
type="button"
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onSplitTerminal}
aria-label="Split Terminal"
title="Split Terminal"
>
<SquareSplitHorizontal className="size-3.25" />
</button>
<button
type="button"
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={onNewTerminal}
aria-label="New Terminal"
title="New Terminal"
>
<Plus className="size-3.25" />
</button>
<button
type="button"
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
aria-label="Close Terminal"
title="Close Terminal"
>
<Trash2 className="size-3.25" />
</button>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
{resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
const isGroupActive = terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
const groupActiveTerminalId = isGroupActive
? resolvedActiveTerminalId
: (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
return (
<div key={terminalGroup.id} className="pb-0.5">
{showGroupHeaders && (
<button
type="button"
className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
isGroupActive
? "bg-accent/70 text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
}`}
onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
>
{terminalGroup.terminalIds.length > 1
? `Split ${groupIndex + 1}`
: `Terminal ${groupIndex + 1}`}
</button>
)}
<div className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
return (
<div
key={terminalId}
className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
isActive
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
}`}
>
{showGroupHeaders && (
<span className="text-[10px] text-muted-foreground/80">└</span>
)}
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-1 text-left"
onClick={() => onActiveTerminalChange(terminalId)}
>
<TerminalSquare className="size-3 shrink-0" />
<span className="truncate">
{terminalLabelById.get(terminalId) ?? "Terminal"}
</span>
</button>
{normalizedTerminalIds.length > 1 && (
<button
type="button"
className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
onClick={(event) => {
event.stopPropagation();
onCloseTerminal(terminalId);
}}
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
>
×
</button>
)}
</div>
);
})}
</div>
</div>
);
})}
</div>
</aside>
)}
</div>
</div> </div>
</aside> </aside>
); );
+99 -4
View File
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import { DEFAULT_MODEL } from "./model-logic"; import { DEFAULT_MODEL } from "./model-logic";
import { hydratePersistedState, toPersistedState } from "./persistenceSchema"; import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import type { Thread } from "./types"; import type { Thread } from "./types";
describe("hydratePersistedState", () => { describe("hydratePersistedState", () => {
@@ -50,6 +50,14 @@ describe("hydratePersistedState", () => {
expect(hydrated?.threads[0]?.codexThreadId).toBeNull(); expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.threads[0]?.terminalOpen).toBe(false); expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT); expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false); expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
expect(hydrated?.runtimeMode).toBe("full-access"); expect(hydrated?.runtimeMode).toBe("full-access");
}); });
@@ -92,6 +100,14 @@ describe("hydratePersistedState", () => {
expect(hydrated?.threads[0]?.codexThreadId).toBeNull(); expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
expect(hydrated?.threads[0]?.terminalOpen).toBe(false); expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT); expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
expect(hydrated?.activeThreadId).toBe("t-1"); expect(hydrated?.activeThreadId).toBe("t-1");
expect(hydrated?.runtimeMode).toBe("full-access"); expect(hydrated?.runtimeMode).toBe("full-access");
}); });
@@ -117,7 +133,7 @@ describe("hydratePersistedState", () => {
expect(hydrated?.runtimeMode).toBe("approval-required"); expect(hydrated?.runtimeMode).toBe("approval-required");
}); });
it("hydrates terminal fields from v6 payload", () => { it("hydrates terminal fields from legacy v6 payload", () => {
const payload = JSON.stringify({ const payload = JSON.stringify({
version: 6, version: 6,
runtimeMode: "full-access", runtimeMode: "full-access",
@@ -139,6 +155,10 @@ describe("hydratePersistedState", () => {
model: "gpt-5.3-codex", model: "gpt-5.3-codex",
terminalOpen: true, terminalOpen: true,
terminalHeight: 360, terminalHeight: 360,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalLayout: "tabs",
splitTerminalIds: [],
messages: [], messages: [],
createdAt: "2026-02-08T10:00:00.000Z", createdAt: "2026-02-08T10:00:00.000Z",
lastVisitedAt: "2026-02-08T10:01:00.000Z", lastVisitedAt: "2026-02-08T10:01:00.000Z",
@@ -150,9 +170,62 @@ describe("hydratePersistedState", () => {
const hydrated = hydratePersistedState(payload, false); const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalOpen).toBe(true); expect(hydrated?.threads[0]?.terminalOpen).toBe(true);
expect(hydrated?.threads[0]?.terminalHeight).toBe(360); expect(hydrated?.threads[0]?.terminalHeight).toBe(360);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe("term-2");
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
expect(hydrated?.threads[0]?.lastVisitedAt).toBe("2026-02-08T10:01:00.000Z"); expect(hydrated?.threads[0]?.lastVisitedAt).toBe("2026-02-08T10:01:00.000Z");
}); });
it("hydrates legacy split layout into a grouped split", () => {
const payload = JSON.stringify({
version: 6,
runtimeMode: "full-access",
projects: [
{
id: "p-1",
name: "Project",
cwd: "/tmp/project",
model: "gpt-5.3-codex",
expanded: true,
},
],
threads: [
{
id: "t-1",
codexThreadId: null,
projectId: "p-1",
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: true,
terminalHeight: 360,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: "term-2",
terminalLayout: "split",
splitTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
messages: [],
createdAt: "2026-02-08T10:00:00.000Z",
},
],
activeThreadId: "t-1",
});
const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
});
it("defaults terminalHeight when hydrating v5 payloads", () => { it("defaults terminalHeight when hydrating v5 payloads", () => {
const payload = JSON.stringify({ const payload = JSON.stringify({
version: 5, version: 5,
@@ -183,11 +256,19 @@ describe("hydratePersistedState", () => {
const hydrated = hydratePersistedState(payload, false); const hydrated = hydratePersistedState(payload, false);
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT); expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
}); });
}); });
describe("toPersistedState", () => { describe("toPersistedState", () => {
it("writes v6 payload and strips non-persisted thread fields", () => { it("writes v7 payload and strips non-persisted thread fields", () => {
const thread: Thread = { const thread: Thread = {
id: "t-1", id: "t-1",
codexThreadId: "thr_1", codexThreadId: "thr_1",
@@ -196,6 +277,13 @@ describe("toPersistedState", () => {
model: "gpt-5.3-codex", model: "gpt-5.3-codex",
terminalOpen: true, terminalOpen: true,
terminalHeight: 320, terminalHeight: 320,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
],
activeTerminalGroupId: "group-term-2",
session: null, session: null,
messages: [ messages: [
{ {
@@ -239,7 +327,7 @@ describe("toPersistedState", () => {
runtimeMode: "full-access", runtimeMode: "full-access",
}); });
expect(persisted.version).toBe(6); expect(persisted.version).toBe(7);
expect(persisted.runtimeMode).toBe("full-access"); expect(persisted.runtimeMode).toBe("full-access");
expect(persisted.threads[0]).toEqual({ expect(persisted.threads[0]).toEqual({
id: "t-1", id: "t-1",
@@ -249,6 +337,13 @@ describe("toPersistedState", () => {
model: "gpt-5.3-codex", model: "gpt-5.3-codex",
terminalOpen: true, terminalOpen: true,
terminalHeight: 320, terminalHeight: 320,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
{ id: "group-term-2", terminalIds: ["term-2"] },
],
activeTerminalGroupId: "group-term-2",
messages: [ messages: [
{ {
id: "m-1", id: "m-1",
+115 -2
View File
@@ -3,10 +3,12 @@ import { z } from "zod";
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic"; import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
import { import {
DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE, DEFAULT_RUNTIME_MODE,
type Project, type Project,
type RuntimeMode, type RuntimeMode,
type Thread, type Thread,
type ThreadTerminalGroup,
} from "./types"; } from "./types";
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex"; const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
@@ -38,6 +40,11 @@ const persistedMessageSchema = z.object({
streaming: z.boolean(), streaming: z.boolean(),
}); });
const persistedTerminalGroupSchema = z.object({
id: z.string().trim().min(1),
terminalIds: z.array(z.string().trim().min(1)),
});
const persistedThreadSchema = z.object({ const persistedThreadSchema = z.object({
id: z.string().min(1), id: z.string().min(1),
codexThreadId: z.string().min(1).nullable().default(null), codexThreadId: z.string().min(1).nullable().default(null),
@@ -48,6 +55,13 @@ const persistedThreadSchema = z.object({
terminalHeight: z.number().int().min(120).max(4_096).default( terminalHeight: z.number().int().min(120).max(4_096).default(
DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_HEIGHT,
), ),
terminalIds: z.array(z.string().trim().min(1)).default([DEFAULT_THREAD_TERMINAL_ID]),
activeTerminalId: z.string().trim().min(1).default(DEFAULT_THREAD_TERMINAL_ID),
terminalGroups: z.array(persistedTerminalGroupSchema).default([]),
activeTerminalGroupId: z.string().trim().min(1).optional(),
// Legacy v6 and older fields retained for migration.
terminalLayout: z.enum(["single", "split", "tabs"]).optional(),
splitTerminalIds: z.array(z.string().trim().min(1)).optional(),
messages: z.array(persistedMessageSchema), messages: z.array(persistedMessageSchema),
createdAt: z.string().min(1), createdAt: z.string().min(1),
lastVisitedAt: z.string().min(1).optional(), lastVisitedAt: z.string().min(1).optional(),
@@ -86,12 +100,18 @@ export const persistedStateV6Schema = persistedStateBodySchema.extend({
version: z.literal(6).optional(), version: z.literal(6).optional(),
}); });
export const persistedStateV7Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(7).optional(),
});
export const persistedStateV5Schema = persistedStateBodySchema.extend({ export const persistedStateV5Schema = persistedStateBodySchema.extend({
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE), runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
version: z.literal(5).optional(), version: z.literal(5).optional(),
}); });
const persistedStateSchema = z.union([ const persistedStateSchema = z.union([
persistedStateV7Schema,
persistedStateV6Schema, persistedStateV6Schema,
persistedStateV5Schema, persistedStateV5Schema,
persistedStateV4Schema, persistedStateV4Schema,
@@ -129,6 +149,91 @@ function hydrateThread(
thread: z.infer<typeof persistedThreadSchema>, thread: z.infer<typeof persistedThreadSchema>,
isLegacyPayload: boolean, isLegacyPayload: boolean,
): Thread { ): Thread {
const terminalIds = [...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
const safeTerminalIds =
terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId
: (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const safeTerminalIdSet = new Set(safeTerminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const normalizedGroups: ThreadTerminalGroup[] = [];
const assignUniqueGroupId = (groupId: string): string => {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
};
for (const terminalGroup of thread.terminalGroups) {
const nextTerminalIds = [
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
].filter((terminalId) => {
if (!safeTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (nextTerminalIds.length === 0) continue;
for (const terminalId of nextTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
terminalGroup.id.trim().length > 0
? terminalGroup.id.trim()
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
normalizedGroups.push({
id: assignUniqueGroupId(baseGroupId),
terminalIds: nextTerminalIds,
});
}
if (normalizedGroups.length === 0 && thread.terminalLayout === "split") {
const splitTerminalIds = [
...new Set((thread.splitTerminalIds ?? []).map((id) => id.trim()).filter((id) => id.length > 0)),
].filter((terminalId) => safeTerminalIdSet.has(terminalId));
if (splitTerminalIds.length >= 2) {
const splitGroupTerminalIds = splitTerminalIds.slice(0, 2);
for (const terminalId of splitGroupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
normalizedGroups.push({
id: assignUniqueGroupId(`group-${splitGroupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`),
terminalIds: splitGroupTerminalIds,
});
}
}
for (const terminalId of safeTerminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
normalizedGroups.push({
id: assignUniqueGroupId(`group-${terminalId}`),
terminalIds: [terminalId],
});
}
const activeGroupIndexFromId = normalizedGroups.findIndex(
(terminalGroup) => terminalGroup.id === thread.activeTerminalGroupId,
);
const activeGroupIndexFromTerminal = normalizedGroups.findIndex((terminalGroup) =>
terminalGroup.terminalIds.includes(activeTerminalId),
);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: (activeGroupIndexFromTerminal >= 0 ? activeGroupIndexFromTerminal : 0);
const activeTerminalGroupId =
normalizedGroups[activeGroupIndex]?.id ??
normalizedGroups[0]?.id ??
`group-${DEFAULT_THREAD_TERMINAL_ID}`;
return { return {
id: thread.id, id: thread.id,
codexThreadId: thread.codexThreadId, codexThreadId: thread.codexThreadId,
@@ -137,6 +242,10 @@ function hydrateThread(
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)), model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
terminalOpen: thread.terminalOpen ?? false, terminalOpen: thread.terminalOpen ?? false,
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT, terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: safeTerminalIds,
activeTerminalId,
terminalGroups: normalizedGroups,
activeTerminalGroupId,
session: null, session: null,
messages: thread.messages.map((message) => { messages: thread.messages.map((message) => {
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment })); const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
@@ -199,9 +308,9 @@ export function hydratePersistedState(
export function toPersistedState( export function toPersistedState(
state: PersistedStoreSnapshot, state: PersistedStoreSnapshot,
): z.infer<typeof persistedStateV6Schema> { ): z.infer<typeof persistedStateV7Schema> {
return { return {
version: 6, version: 7,
projects: state.projects, projects: state.projects,
threads: state.threads.map((thread) => ({ threads: state.threads.map((thread) => ({
id: thread.id, id: thread.id,
@@ -211,6 +320,10 @@ export function toPersistedState(
model: thread.model, model: thread.model,
terminalOpen: thread.terminalOpen, terminalOpen: thread.terminalOpen,
terminalHeight: thread.terminalHeight, terminalHeight: thread.terminalHeight,
terminalIds: thread.terminalIds,
activeTerminalId: thread.activeTerminalId,
terminalGroups: thread.terminalGroups,
activeTerminalGroupId: thread.activeTerminalGroupId,
messages: thread.messages.map((message) => ({ messages: thread.messages.map((message) => ({
id: message.id, id: message.id,
role: message.role, role: message.role,
+164 -1
View File
@@ -2,7 +2,7 @@ import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { type AppState, reducer } from "./store"; import { type AppState, reducer } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
import type { Thread } from "./types"; import type { Thread } from "./types";
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession { function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
@@ -37,6 +37,15 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
model: "gpt-5.3-codex", model: "gpt-5.3-codex",
terminalOpen: false, terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT, terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: makeSession(), session: makeSession(),
messages: [], messages: [],
events: [], events: [],
@@ -111,6 +120,160 @@ describe("store reducer thread continuity", () => {
expect(next.threads[0]?.terminalHeight).toBe(360); expect(next.threads[0]?.terminalHeight).toBe(360);
}); });
it("splits the active terminal into side-by-side mode", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SPLIT_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
]);
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("creates a new full-width terminal and switches to tab mode", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "NEW_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{ id: "group-term-2", terminalIds: ["term-2"] },
]);
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
});
it("switches the active terminal and restores its owning group", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
],
activeTerminalGroupId: "group-term-3",
}),
);
const next = reducer(state, {
type: "SET_THREAD_ACTIVE_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("supports splitting beyond two terminals in the same group", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "SPLIT_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-3",
});
expect(next.threads[0]?.terminalIds).toEqual([
DEFAULT_THREAD_TERMINAL_ID,
"term-2",
"term-3",
]);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
},
]);
expect(next.threads[0]?.activeTerminalId).toBe("term-3");
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("closes a terminal and keeps grouped layout coherent", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
activeTerminalId: "term-2",
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
}),
);
const next = reducer(state, {
type: "CLOSE_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: "term-2",
});
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-3"]);
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
{ id: "group-term-3", terminalIds: ["term-3"] },
]);
});
it("closes the final terminal and hides the drawer", () => {
const state = makeState(
makeThread({
terminalOpen: true,
}),
);
const next = reducer(state, {
type: "CLOSE_THREAD_TERMINAL",
threadId: "thread-local-1",
terminalId: DEFAULT_THREAD_TERMINAL_ID,
});
expect(next.threads[0]?.terminalOpen).toBe(false);
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
]);
});
it("backfills codexThreadId from routed provider events", () => { it("backfills codexThreadId from routed provider events", () => {
const state = makeState(makeThread({ codexThreadId: null })); const state = makeState(makeThread({ codexThreadId: null }));
const next = reducer(state, { const next = reducer(state, {
+321 -12
View File
@@ -14,10 +14,12 @@ import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic"; import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
import { import {
type ChatAttachment, type ChatAttachment,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE, DEFAULT_RUNTIME_MODE,
type Project, type Project,
type RuntimeMode, type RuntimeMode,
type Thread, type Thread,
type ThreadTerminalGroup,
} from "./types"; } from "./types";
// ── Actions ────────────────────────────────────────────────────────── // ── Actions ──────────────────────────────────────────────────────────
@@ -31,6 +33,10 @@ type Action =
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: string } | { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: string; open: boolean } | { type: "SET_THREAD_TERMINAL_OPEN"; threadId: string; open: boolean }
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: string; height: number } | { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: string; height: number }
| { type: "SPLIT_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "NEW_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
| { type: "TOGGLE_DIFF" } | { type: "TOGGLE_DIFF" }
| { | {
type: "APPLY_EVENT"; type: "APPLY_EVENT";
@@ -67,8 +73,9 @@ export interface AppState {
diffOpen: boolean; diffOpen: boolean;
} }
const PERSISTED_STATE_KEY = "t3code:renderer-state:v6"; const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
const LEGACY_PERSISTED_STATE_KEYS = [ const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v6",
"t3code:renderer-state:v5", "t3code:renderer-state:v5",
"t3code:renderer-state:v4", "t3code:renderer-state:v4",
"t3code:renderer-state:v3", "t3code:renderer-state:v3",
@@ -133,6 +140,180 @@ function updateThread(
return threads.map((t) => (t.id === threadId ? updater(t) : t)); return threads.map((t) => (t.id === threadId ? updater(t) : t));
} }
function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
const unique = [...new Set(ids)];
if (unique.length > 0) {
return unique;
}
return [DEFAULT_THREAD_TERMINAL_ID];
}
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
}
function fallbackGroupId(terminalId: string): string {
return `group-${terminalId}`;
}
function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
}
function normalizeTerminalGroups(
thread: Thread,
terminalIds: string[],
): ThreadTerminalGroup[] {
const validTerminalIdSet = new Set(terminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const groups: ThreadTerminalGroup[] = [];
for (const group of thread.terminalGroups) {
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
if (!validTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (groupTerminalIds.length === 0) continue;
for (const terminalId of groupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
group.id.trim().length > 0
? group.id.trim()
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
groups.push({
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
terminalIds: groupTerminalIds,
});
}
for (const terminalId of terminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
groups.push({
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
terminalIds: [terminalId],
});
}
if (groups.length > 0) {
return groups;
}
return [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
];
}
function findGroupIndexByTerminalId(
terminalGroups: ThreadTerminalGroup[],
terminalId: string,
): number {
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
}
function normalizeThreadTerminals(thread: Thread): Thread {
const terminalIds = normalizeTerminalIds(thread.terminalIds);
const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId
: (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
const activeGroupIndexFromId = terminalGroups.findIndex(
(group) => group.id === thread.activeTerminalGroupId,
);
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(
terminalGroups,
activeTerminalId,
);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: (activeGroupIndexFromTerminal >= 0 ? activeGroupIndexFromTerminal : 0);
const activeTerminalGroupId =
terminalGroups[activeGroupIndex]?.id ??
terminalGroups[0]?.id ??
fallbackGroupId(activeTerminalId);
return {
...thread,
terminalIds,
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
};
}
function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
if (!thread.terminalIds.includes(terminalId)) {
return thread;
}
const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
if (remainingTerminalIds.length === 0) {
return normalizeThreadTerminals({
...thread,
terminalOpen: false,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
});
}
const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
const closedTerminalGroup = thread.terminalGroups.find((group) =>
group.terminalIds.includes(terminalId),
);
const closedTerminalGroupIndex = closedTerminalGroup
? closedTerminalGroup.terminalIds.indexOf(terminalId)
: -1;
const remainingTerminalsInClosedGroup = (
closedTerminalGroup?.terminalIds ?? []
).filter((id) => id !== terminalId);
const nextActiveTerminalId =
thread.activeTerminalId === terminalId
? (remainingTerminalsInClosedGroup[
Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
] ??
remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
remainingTerminalIds[0] ??
DEFAULT_THREAD_TERMINAL_ID)
: thread.activeTerminalId;
const nextTerminalGroups = thread.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
return normalizeThreadTerminals({
...thread,
terminalIds: remainingTerminalIds,
activeTerminalId: nextActiveTerminalId,
terminalGroups: nextTerminalGroups,
});
}
function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined { function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
return threads.find((t) => t.session?.sessionId === sessionId); return threads.find((t) => t.session?.sessionId === sessionId);
} }
@@ -259,10 +440,10 @@ export function reducer(state: AppState, action: Action): AppState {
if (!previousProject) return null; if (!previousProject) return null;
const mappedProjectId = nextProjectIdByCwd.get(previousProject.cwd); const mappedProjectId = nextProjectIdByCwd.get(previousProject.cwd);
if (!mappedProjectId) return null; if (!mappedProjectId) return null;
return { return normalizeThreadTerminals({
...thread, ...thread,
projectId: mappedProjectId, projectId: mappedProjectId,
}; });
}) })
.filter((thread): thread is Thread => thread !== null); .filter((thread): thread is Thread => thread !== null);
const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId) const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId)
@@ -285,19 +466,18 @@ export function reducer(state: AppState, action: Action): AppState {
), ),
}; };
case "ADD_THREAD": case "ADD_THREAD": {
const nextThread = normalizeThreadTerminals({
...action.thread,
model: resolveModelSlug(action.thread.model),
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
});
return { return {
...state, ...state,
threads: [ threads: [...state.threads, nextThread],
...state.threads,
{
...action.thread,
model: resolveModelSlug(action.thread.model),
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
},
],
activeThreadId: action.thread.id, activeThreadId: action.thread.id,
}; };
}
case "SET_ACTIVE_THREAD": { case "SET_ACTIVE_THREAD": {
const visitedAt = new Date().toISOString(); const visitedAt = new Date().toISOString();
@@ -338,6 +518,135 @@ export function reducer(state: AppState, action: Action): AppState {
})), })),
}; };
case "SPLIT_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
...group,
terminalIds: [...group.terminalIds],
}));
let activeGroupIndex = terminalGroups.findIndex(
(group) => group.id === normalizedThread.activeTerminalGroupId,
);
if (activeGroupIndex < 0) {
activeGroupIndex = findGroupIndexByTerminalId(
terminalGroups,
normalizedThread.activeTerminalId,
);
}
if (activeGroupIndex < 0) {
terminalGroups.push({
id: fallbackGroupId(normalizedThread.activeTerminalId),
terminalIds: [normalizedThread.activeTerminalId],
});
activeGroupIndex = terminalGroups.length - 1;
}
const existingGroupIndex = findGroupIndexByTerminalId(
terminalGroups,
action.terminalId,
);
if (existingGroupIndex >= 0) {
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
existingGroupIndex
]!.terminalIds.filter((id) => id !== action.terminalId);
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
terminalGroups.splice(existingGroupIndex, 1);
if (existingGroupIndex < activeGroupIndex) {
activeGroupIndex -= 1;
}
}
}
const destinationGroup = terminalGroups[activeGroupIndex];
if (!destinationGroup) {
return normalizedThread;
}
if (!destinationGroup.terminalIds.includes(action.terminalId)) {
const anchorIndex = destinationGroup.terminalIds.indexOf(
normalizedThread.activeTerminalId,
);
if (anchorIndex >= 0) {
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
} else {
destinationGroup.terminalIds.push(action.terminalId);
}
}
return normalizeThreadTerminals({
...normalizedThread,
terminalIds,
activeTerminalId: action.terminalId,
activeTerminalGroupId: destinationGroup.id,
terminalGroups,
});
}),
};
case "NEW_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
const terminalGroups = normalizedThread.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
const nextGroupId = fallbackGroupId(action.terminalId);
terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
return normalizeThreadTerminals({
...normalizedThread,
terminalIds,
activeTerminalId: action.terminalId,
activeTerminalGroupId: nextGroupId,
terminalGroups,
});
}),
};
case "SET_THREAD_ACTIVE_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
if (!normalizedThread.terminalIds.includes(action.terminalId)) {
return thread;
}
const nextActiveGroupIndex = findGroupIndexByTerminalId(
normalizedThread.terminalGroups,
action.terminalId,
);
const activeTerminalGroupId =
nextActiveGroupIndex >= 0
? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
normalizedThread.activeTerminalGroupId)
: normalizedThread.activeTerminalGroupId;
return normalizeThreadTerminals({
...normalizedThread,
activeTerminalId: action.terminalId,
activeTerminalGroupId,
});
}),
};
case "CLOSE_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
closeThreadTerminal(thread, action.terminalId),
),
};
case "TOGGLE_DIFF": case "TOGGLE_DIFF":
return { ...state, diffOpen: !state.diffOpen }; return { ...state, diffOpen: !state.diffOpen };
+10
View File
@@ -4,6 +4,12 @@ export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
export type RuntimeMode = "approval-required" | "full-access"; export type RuntimeMode = "approval-required" | "full-access";
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access"; export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280; export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
export const DEFAULT_THREAD_TERMINAL_ID = "default";
export interface ThreadTerminalGroup {
id: string;
terminalIds: string[];
}
export interface ChatImageAttachment { export interface ChatImageAttachment {
type: "image"; type: "image";
@@ -41,6 +47,10 @@ export interface Thread {
model: string; model: string;
terminalOpen: boolean; terminalOpen: boolean;
terminalHeight: number; terminalHeight: number;
terminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
session: ProviderSession | null; session: ProviderSession | null;
messages: ChatMessage[]; messages: ChatMessage[];
events: ProviderEvent[]; events: ProviderEvent[];
+2 -2
View File
@@ -30,12 +30,12 @@ import type {
ProjectRemoveInput, ProjectRemoveInput,
} from "./project"; } from "./project";
import type { import type {
TerminalClearInput,
TerminalCloseInput, TerminalCloseInput,
TerminalEvent, TerminalEvent,
TerminalOpenInput, TerminalOpenInput,
TerminalResizeInput, TerminalResizeInput,
TerminalSessionSnapshot, TerminalSessionSnapshot,
TerminalThreadInput,
TerminalWriteInput, TerminalWriteInput,
} from "./terminal"; } from "./terminal";
import type { NewTodoInput, Todo } from "./todo"; import type { NewTodoInput, Todo } from "./todo";
@@ -61,7 +61,7 @@ export interface NativeApi {
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>; open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
write: (input: TerminalWriteInput) => Promise<void>; write: (input: TerminalWriteInput) => Promise<void>;
resize: (input: TerminalResizeInput) => Promise<void>; resize: (input: TerminalResizeInput) => Promise<void>;
clear: (input: TerminalThreadInput) => Promise<void>; clear: (input: TerminalClearInput) => Promise<void>;
restart: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>; restart: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
close: (input: TerminalCloseInput) => Promise<void>; close: (input: TerminalCloseInput) => Promise<void>;
onEvent: (callback: (event: TerminalEvent) => void) => () => void; onEvent: (callback: (event: TerminalEvent) => void) => () => void;
+24
View File
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { import {
DEFAULT_TERMINAL_ID,
terminalClearInputSchema,
terminalCloseInputSchema, terminalCloseInputSchema,
terminalEventSchema, terminalEventSchema,
terminalOpenInputSchema, terminalOpenInputSchema,
@@ -30,6 +32,16 @@ describe("terminalOpenInputSchema", () => {
}); });
expect(result.success).toBe(false); expect(result.success).toBe(false);
}); });
it("defaults terminalId when missing", () => {
const parsed = terminalOpenInputSchema.parse({
threadId: "thread-1",
cwd: "/tmp/project",
cols: 100,
rows: 24,
});
expect(parsed.terminalId).toBe(DEFAULT_TERMINAL_ID);
});
}); });
describe("terminalWriteInputSchema", () => { describe("terminalWriteInputSchema", () => {
@@ -68,6 +80,15 @@ describe("terminalResizeInputSchema", () => {
}); });
}); });
describe("terminalClearInputSchema", () => {
it("defaults terminal id", () => {
const parsed = terminalClearInputSchema.parse({
threadId: "thread-1",
});
expect(parsed.terminalId).toBe(DEFAULT_TERMINAL_ID);
});
});
describe("terminalCloseInputSchema", () => { describe("terminalCloseInputSchema", () => {
it("accepts optional deleteHistory", () => { it("accepts optional deleteHistory", () => {
const result = terminalCloseInputSchema.safeParse({ const result = terminalCloseInputSchema.safeParse({
@@ -82,6 +103,7 @@ describe("terminalSessionSnapshotSchema", () => {
it("accepts running snapshots", () => { it("accepts running snapshots", () => {
const result = terminalSessionSnapshotSchema.safeParse({ const result = terminalSessionSnapshotSchema.safeParse({
threadId: "thread-1", threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
cwd: "/tmp/project", cwd: "/tmp/project",
status: "running", status: "running",
pid: 1234, pid: 1234,
@@ -99,6 +121,7 @@ describe("terminalEventSchema", () => {
const result = terminalEventSchema.safeParse({ const result = terminalEventSchema.safeParse({
type: "output", type: "output",
threadId: "thread-1", threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
data: "line\n", data: "line\n",
}); });
@@ -109,6 +132,7 @@ describe("terminalEventSchema", () => {
const result = terminalEventSchema.safeParse({ const result = terminalEventSchema.safeParse({
type: "exited", type: "exited",
threadId: "thread-1", threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
exitCode: 0, exitCode: 0,
exitSignal: null, exitSignal: null,
+17 -3
View File
@@ -1,28 +1,38 @@
import { z } from "zod"; import { z } from "zod";
export const DEFAULT_TERMINAL_ID = "default";
const terminalColsSchema = z.number().int().min(20).max(400); const terminalColsSchema = z.number().int().min(20).max(400);
const terminalRowsSchema = z.number().int().min(5).max(200); const terminalRowsSchema = z.number().int().min(5).max(200);
const terminalIdSchema = z.string().trim().min(1).max(128);
export const terminalThreadInputSchema = z.object({ export const terminalThreadInputSchema = z.object({
threadId: z.string().trim().min(1), threadId: z.string().trim().min(1),
}); });
export const terminalOpenInputSchema = terminalThreadInputSchema.extend({ export const terminalSessionInputSchema = terminalThreadInputSchema.extend({
terminalId: terminalIdSchema.default(DEFAULT_TERMINAL_ID),
});
export const terminalOpenInputSchema = terminalSessionInputSchema.extend({
cwd: z.string().trim().min(1), cwd: z.string().trim().min(1),
cols: terminalColsSchema, cols: terminalColsSchema,
rows: terminalRowsSchema, rows: terminalRowsSchema,
}); });
export const terminalWriteInputSchema = terminalThreadInputSchema.extend({ export const terminalWriteInputSchema = terminalSessionInputSchema.extend({
data: z.string().min(1).max(65_536), data: z.string().min(1).max(65_536),
}); });
export const terminalResizeInputSchema = terminalThreadInputSchema.extend({ export const terminalResizeInputSchema = terminalSessionInputSchema.extend({
cols: terminalColsSchema, cols: terminalColsSchema,
rows: terminalRowsSchema, rows: terminalRowsSchema,
}); });
export const terminalClearInputSchema = terminalSessionInputSchema;
export const terminalCloseInputSchema = terminalThreadInputSchema.extend({ export const terminalCloseInputSchema = terminalThreadInputSchema.extend({
terminalId: terminalIdSchema.optional(),
deleteHistory: z.boolean().optional(), deleteHistory: z.boolean().optional(),
}); });
@@ -35,6 +45,7 @@ export const terminalSessionStatusSchema = z.enum([
export const terminalSessionSnapshotSchema = z.object({ export const terminalSessionSnapshotSchema = z.object({
threadId: z.string().min(1), threadId: z.string().min(1),
terminalId: z.string().min(1),
cwd: z.string().min(1), cwd: z.string().min(1),
status: terminalSessionStatusSchema, status: terminalSessionStatusSchema,
pid: z.number().int().positive().nullable(), pid: z.number().int().positive().nullable(),
@@ -46,6 +57,7 @@ export const terminalSessionSnapshotSchema = z.object({
const terminalEventBaseSchema = z.object({ const terminalEventBaseSchema = z.object({
threadId: z.string().min(1), threadId: z.string().min(1),
terminalId: z.string().min(1),
createdAt: z.string().datetime(), createdAt: z.string().datetime(),
}); });
@@ -89,9 +101,11 @@ export const terminalEventSchema = z.discriminatedUnion("type", [
]); ]);
export type TerminalThreadInput = z.input<typeof terminalThreadInputSchema>; export type TerminalThreadInput = z.input<typeof terminalThreadInputSchema>;
export type TerminalSessionInput = z.input<typeof terminalSessionInputSchema>;
export type TerminalOpenInput = z.input<typeof terminalOpenInputSchema>; export type TerminalOpenInput = z.input<typeof terminalOpenInputSchema>;
export type TerminalWriteInput = z.input<typeof terminalWriteInputSchema>; export type TerminalWriteInput = z.input<typeof terminalWriteInputSchema>;
export type TerminalResizeInput = z.input<typeof terminalResizeInputSchema>; export type TerminalResizeInput = z.input<typeof terminalResizeInputSchema>;
export type TerminalClearInput = z.input<typeof terminalClearInputSchema>;
export type TerminalCloseInput = z.input<typeof terminalCloseInputSchema>; export type TerminalCloseInput = z.input<typeof terminalCloseInputSchema>;
export type TerminalSessionStatus = z.infer<typeof terminalSessionStatusSchema>; export type TerminalSessionStatus = z.infer<typeof terminalSessionStatusSchema>;
export type TerminalSessionSnapshot = z.infer<typeof terminalSessionSnapshotSchema>; export type TerminalSessionSnapshot = z.infer<typeof terminalSessionSnapshotSchema>;