Compare commits

..
Author SHA1 Message Date
Cursor Agent 87caa1b78f Fix three-byte escape sequences leaking final byte into history
Handle ECMA-48 escape sequences with intermediate bytes (0x20-0x2F)
such as ESC ( B (select ASCII for G0), ESC ) 0 (select DEC Special
Graphics for G1), and ESC # 8 (DECALN). These are commonly emitted by
ncurses programs (vim, less, htop) on exit. Previously only 2 bytes
were consumed, causing the final byte to leak into visibleText.
2026-03-24 17:02:14 +00:00
Julius Marminge b71705580a Preserve terminal history across ANSI control sequences
- sanitize PTY output before persisting transcript history
- handle chunk-split control sequences and reset pending state on restart/exit
- add regression tests for reopened sessions
2026-03-24 09:49:41 -07:00
13 changed files with 266 additions and 327 deletions

No files matched your search

+1 -2
View File
@@ -18,5 +18,4 @@ apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
__screenshots__/
@@ -469,6 +469,46 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("persists only displayable transcript content when PTY emits ANSI control sequences", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("prompt ");
process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007");
process.emitData("\u001b[1;1R");
process.emitData("done\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("prompt done\n");
manager.dispose();
});
it("drops chunk-split terminal control sequences from persisted history", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("prompt ");
process.emitData("\u001b]11;");
process.emitData("rgb:ffff/ffff/ffff\u0007\u001b[1;1");
process.emitData("Rdone\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("prompt done\n");
manager.dispose();
});
it("deletes history file when close(deleteHistory=true)", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput());
+143 -2
View File
@@ -254,6 +254,132 @@ function capHistory(history: string, maxLines: number): string {
return hasTrailingNewline ? `${capped}\n` : capped;
}
function isPrintableTerminalCharacter(codePoint: number): boolean {
return codePoint >= 0x20 && codePoint !== 0x7f;
}
function isCsiFinalByte(codePoint: number): boolean {
return codePoint >= 0x40 && codePoint <= 0x7e;
}
function findStringTerminatorIndex(input: string, start: number): number | null {
for (let index = start; index < input.length; index += 1) {
const codePoint = input.charCodeAt(index);
if (codePoint === 0x07 || codePoint === 0x9c) {
return index + 1;
}
if (codePoint === 0x1b && input.charCodeAt(index + 1) === 0x5c) {
return index + 2;
}
}
return null;
}
function sanitizeTerminalHistoryChunk(
pendingControlSequence: string,
data: string,
): { visibleText: string; pendingControlSequence: string } {
const input = `${pendingControlSequence}${data}`;
let visibleText = "";
let index = 0;
while (index < input.length) {
const codePoint = input.charCodeAt(index);
if (codePoint === 0x1b) {
const nextCodePoint = input.charCodeAt(index + 1);
if (Number.isNaN(nextCodePoint)) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
if (nextCodePoint === 0x5b) {
let cursor = index + 2;
while (cursor < input.length) {
if (isCsiFinalByte(input.charCodeAt(cursor))) {
index = cursor + 1;
break;
}
cursor += 1;
}
if (cursor >= input.length) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
continue;
}
if (
nextCodePoint === 0x5d ||
nextCodePoint === 0x50 ||
nextCodePoint === 0x5e ||
nextCodePoint === 0x5f
) {
const terminatorIndex = findStringTerminatorIndex(input, index + 2);
if (terminatorIndex === null) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
index = terminatorIndex;
continue;
}
if (nextCodePoint >= 0x20 && nextCodePoint <= 0x2f) {
let cursor = index + 2;
while (
cursor < input.length &&
input.charCodeAt(cursor) >= 0x20 &&
input.charCodeAt(cursor) <= 0x2f
) {
cursor++;
}
if (cursor >= input.length) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
index = cursor + 1;
continue;
}
index += 2;
continue;
}
if (codePoint === 0x9b) {
let cursor = index + 1;
while (cursor < input.length) {
if (isCsiFinalByte(input.charCodeAt(cursor))) {
index = cursor + 1;
break;
}
cursor += 1;
}
if (cursor >= input.length) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
continue;
}
if (codePoint === 0x9d || codePoint === 0x90 || codePoint === 0x9e || codePoint === 0x9f) {
const terminatorIndex = findStringTerminatorIndex(input, index + 1);
if (terminatorIndex === null) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
index = terminatorIndex;
continue;
}
if (
codePoint === 0x0a ||
codePoint === 0x0d ||
codePoint === 0x09 ||
isPrintableTerminalCharacter(codePoint)
) {
visibleText += input[index];
}
index += 1;
}
return { visibleText, pendingControlSequence: "" };
}
function legacySafeThreadId(threadId: string): string {
return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
}
@@ -378,6 +504,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
status: "starting",
pid: null,
history,
pendingHistoryControlSequence: "",
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
@@ -407,10 +534,12 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
existing.cwd = input.cwd;
existing.runtimeEnv = nextRuntimeEnv;
existing.history = "";
existing.pendingHistoryControlSequence = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (existing.status === "exited" || existing.status === "error") {
existing.runtimeEnv = nextRuntimeEnv;
existing.history = "";
existing.pendingHistoryControlSequence = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (currentRuntimeEnv !== nextRuntimeEnv) {
existing.runtimeEnv = nextRuntimeEnv;
@@ -469,6 +598,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
await this.runWithThreadLock(input.threadId, async () => {
const session = this.requireSession(input.threadId, input.terminalId);
session.history = "";
session.pendingHistoryControlSequence = "";
session.updatedAt = new Date().toISOString();
await this.persistHistory(input.threadId, input.terminalId, session.history);
this.emitEvent({
@@ -497,6 +627,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
status: "starting",
pid: null,
history: "",
pendingHistoryControlSequence: "",
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
@@ -520,6 +651,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
const rows = input.rows ?? session.rows;
session.history = "";
session.pendingHistoryControlSequence = "";
await this.persistHistory(input.threadId, input.terminalId, session.history);
await this.startSession(session, { ...input, cols, rows }, "restarted");
return this.snapshot(session);
@@ -694,9 +826,16 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
}
private onProcessData(session: TerminalSessionState, data: string): void {
session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
const sanitized = sanitizeTerminalHistoryChunk(session.pendingHistoryControlSequence, data);
session.pendingHistoryControlSequence = sanitized.pendingControlSequence;
if (sanitized.visibleText.length > 0) {
session.history = capHistory(
`${session.history}${sanitized.visibleText}`,
this.historyLineLimit,
);
this.queuePersist(session.threadId, session.terminalId, session.history);
}
session.updatedAt = new Date().toISOString();
this.queuePersist(session.threadId, session.terminalId, session.history);
this.emitEvent({
type: "output",
threadId: session.threadId,
@@ -713,6 +852,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
session.updatedAt = new Date().toISOString();
@@ -736,6 +876,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.updatedAt = new Date().toISOString();
this.killProcessWithEscalation(process, session.threadId, session.terminalId);
this.evictInactiveSessionsIfNeeded();
@@ -32,6 +32,7 @@ export interface TerminalSessionState {
status: TerminalSessionStatus;
pid: number | null;
history: string;
pendingHistoryControlSequence: string;
exitCode: number | null;
exitSignal: number | null;
updatedAt: string;
+37 -219
View File
@@ -24,7 +24,6 @@ import { useComposerDraftStore } from "../composerDraftStore";
import {
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
type TerminalContextDraft,
removeInlineTerminalContextPlaceholder,
} from "../lib/terminalContext";
import { isMacPlatform } from "../lib/utils";
import { getRouter } from "../router";
@@ -325,18 +324,6 @@ function createDraftOnlySnapshot(): OrchestrationReadModel {
};
}
function withProjectScripts(
snapshot: OrchestrationReadModel,
scripts: OrchestrationReadModel["projects"][number]["scripts"],
): OrchestrationReadModel {
return {
...snapshot,
projects: snapshot.projects.map((project) =>
project.id === PROJECT_ID ? { ...project, scripts: Array.from(scripts) } : project,
),
};
}
function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-plan-target" as MessageId,
@@ -588,58 +575,6 @@ async function waitForInteractionModeButton(
);
}
async function waitForServerConfigToApply(): Promise<void> {
await vi.waitFor(
() => {
expect(wsRequests.some((request) => request._tag === WS_METHODS.serverGetConfig)).toBe(true);
},
{ timeout: 8_000, interval: 16 },
);
await waitForLayout();
}
function dispatchChatNewShortcut(): void {
const useMetaForMod = isMacPlatform(navigator.platform);
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "o",
shiftKey: true,
metaKey: useMetaForMod,
ctrlKey: !useMetaForMod,
bubbles: true,
cancelable: true,
}),
);
}
async function triggerChatNewShortcutUntilPath(
router: ReturnType<typeof getRouter>,
predicate: (pathname: string) => boolean,
errorMessage: string,
): Promise<string> {
let pathname = router.state.location.pathname;
const deadline = Date.now() + 8_000;
while (Date.now() < deadline) {
dispatchChatNewShortcut();
await waitForLayout();
pathname = router.state.location.pathname;
if (predicate(pathname)) {
return pathname;
}
}
throw new Error(`${errorMessage} Last path: ${pathname}`);
}
async function waitForNewThreadShortcutLabel(): Promise<void> {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await newThreadButton.hover();
const shortcutLabel = isMacPlatform(navigator.platform)
? "New thread (⇧⌘O)"
: "New thread (Ctrl+Shift+O)";
await expect.element(page.getByText(shortcutLabel)).toBeInTheDocument();
}
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
const images = Array.from(scope.querySelectorAll("img"));
if (images.length === 0) {
@@ -1045,145 +980,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("runs project scripts from local draft threads at the project cwd", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
projectId: PROJECT_ID,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
envMode: "local",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
{
id: "lint",
name: "Lint",
command: "bun run lint",
icon: "lint",
runOnWorktreeCreate: false,
},
]),
});
try {
const runButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.title === "Run Lint",
) as HTMLButtonElement | null,
"Unable to find Run Lint button.",
);
runButton.click();
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.terminalOpen,
);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.terminalOpen,
threadId: THREAD_ID,
cwd: "/repo/project",
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
},
});
},
{ timeout: 8_000, interval: 16 },
);
await vi.waitFor(
() => {
const writeRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.terminalWrite,
);
expect(writeRequest).toMatchObject({
_tag: WS_METHODS.terminalWrite,
threadId: THREAD_ID,
data: "bun run lint\r",
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("runs project scripts from worktree draft threads at the worktree cwd", async () => {
useComposerDraftStore.setState({
draftThreadsByThreadId: {
[THREAD_ID]: {
projectId: PROJECT_ID,
createdAt: NOW_ISO,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/draft",
worktreePath: "/repo/worktrees/feature-draft",
envMode: "worktree",
},
},
projectDraftThreadIdByProjectId: {
[PROJECT_ID]: THREAD_ID,
},
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
{
id: "test",
name: "Test",
command: "bun run test",
icon: "test",
runOnWorktreeCreate: false,
},
]),
});
try {
const runButton = await waitForElement(
() =>
Array.from(document.querySelectorAll("button")).find(
(button) => button.title === "Run Test",
) as HTMLButtonElement | null,
"Unable to find Run Test button.",
);
runButton.click();
await vi.waitFor(
() => {
const openRequest = wsRequests.find(
(request) => request._tag === WS_METHODS.terminalOpen,
);
expect(openRequest).toMatchObject({
_tag: WS_METHODS.terminalOpen,
threadId: THREAD_ID,
cwd: "/repo/worktrees/feature-draft",
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
T3CODE_WORKTREE_PATH: "/repo/worktrees/feature-draft",
},
});
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("toggles plan mode with Shift+Tab only while the composer is focused", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -1249,7 +1045,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("keeps removed terminal context pills removed when a new one is added", async () => {
it("keeps backspaced terminal context pills removed when a new one is added", async () => {
const removedLabel = "Terminal 1 lines 1-2";
const addedLabel = "Terminal 2 lines 9-10";
useComposerDraftStore.getState().addTerminalContext(
@@ -1279,11 +1075,15 @@ describe("ChatView timeline estimator parity (full app)", () => {
{ timeout: 8_000, interval: 16 },
);
const store = useComposerDraftStore.getState();
const currentPrompt = store.draftsByThreadId[THREAD_ID]?.prompt ?? "";
const nextPrompt = removeInlineTerminalContextPlaceholder(currentPrompt, 0);
store.setPrompt(THREAD_ID, nextPrompt.prompt);
store.removeTerminalContext(THREAD_ID, "ctx-removed");
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
composerEditor.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Backspace",
bubbles: true,
cancelable: true,
}),
);
await vi.waitFor(
() => {
@@ -1705,12 +1505,19 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
await waitForNewThreadShortcutLabel();
await waitForServerConfigToApply();
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
await waitForLayout();
await triggerChatNewShortcutUntilPath(
const useMetaForMod = isMacPlatform(navigator.platform);
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "o",
shiftKey: true,
metaKey: useMetaForMod,
ctrlKey: !useMetaForMod,
bubbles: true,
cancelable: true,
}),
);
await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path),
"Route should have changed to a new draft thread UUID from the shortcut.",
@@ -1719,6 +1526,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await mounted.cleanup();
}
});
it("creates a fresh draft after the previous draft thread is promoted", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -1753,8 +1561,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
try {
const newThreadButton = page.getByTestId("new-thread-button");
await expect.element(newThreadButton).toBeInTheDocument();
await waitForNewThreadShortcutLabel();
await waitForServerConfigToApply();
await newThreadButton.click();
const promotedThreadPath = await waitForURL(
@@ -1768,7 +1574,19 @@ describe("ChatView timeline estimator parity (full app)", () => {
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
const freshThreadPath = await triggerChatNewShortcutUntilPath(
const useMetaForMod = isMacPlatform(navigator.platform);
window.dispatchEvent(
new KeyboardEvent("keydown", {
key: "o",
shiftKey: true,
metaKey: useMetaForMod,
ctrlKey: !useMetaForMod,
bubbles: true,
cancelable: true,
}),
);
const freshThreadPath = await waitForURL(
mounted.router,
(path) => UUID_ROUTE_RE.test(path) && path !== promotedThreadPath,
"Shortcut should create a fresh draft instead of reusing the promoted thread.",
+6 -8
View File
@@ -112,7 +112,6 @@ import { type NewProjectScriptInput } from "./ProjectScriptsControl";
import {
commandForProjectScript,
nextProjectScriptId,
projectScriptCwd,
projectScriptRuntimeEnv,
projectScriptIdFromCommand,
setupProjectScript,
@@ -995,12 +994,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
latestTurnSettled,
timelineEntries,
]);
const gitCwd = activeProject
? projectScriptCwd({
project: { cwd: activeProject.cwd },
worktreePath: activeThread?.worktreePath ?? null,
})
: null;
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
const composerTriggerKind = composerTrigger?.kind ?? null;
const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
const isPathTrigger = composerTriggerKind === "path";
@@ -1309,10 +1303,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
worktreePath?: string | null;
preferNewTerminal?: boolean;
rememberAsLastInvoked?: boolean;
allowLocalDraftThread?: boolean;
},
) => {
const api = readNativeApi();
if (!api || !activeThreadId || !activeProject || !activeThread) return;
if (!isServerThread && !options?.allowLocalDraftThread) return;
if (options?.rememberAsLastInvoked !== false) {
setLastInvokedScriptByProjectId((current) => {
if (current[activeProject.id] === script.id) return current;
@@ -1381,6 +1377,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeThread,
activeThreadId,
gitCwd,
isServerThread,
setTerminalOpen,
setThreadError,
storeNewTerminal,
@@ -2569,6 +2566,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const setupScriptOptions: Parameters<typeof runProjectScript>[1] = {
worktreePath: nextThreadWorktreePath,
rememberAsLastInvoked: false,
allowLocalDraftThread: createdServerThreadForLocalDraft,
};
if (nextThreadWorktreePath) {
setupScriptOptions.cwd = nextThreadWorktreePath;
@@ -3467,7 +3465,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeThreadTitle={activeThread.title}
activeProjectName={activeProject?.name}
isGitRepo={isGitRepo}
openInCwd={gitCwd}
openInCwd={activeThread.worktreePath ?? activeProject?.cwd ?? null}
activeProjectScripts={activeProject?.scripts}
preferredScriptId={
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
+1 -1
View File
@@ -258,7 +258,7 @@ export default function Sidebar() {
const markThreadUnread = useStore((store) => store.markThreadUnread);
const toggleProject = useStore((store) => store.toggleProject);
const reorderProjects = useStore((store) => store.reorderProjects);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
const getDraftThreadByProjectId = useComposerDraftStore(
(store) => store.getDraftThreadByProjectId,
);
-2
View File
@@ -517,11 +517,9 @@ describe("composerDraftStore project draft thread mapping", () => {
it("clears draft registration independently", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "remove me");
store.clearDraftThread(threadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("updates branch context on an existing draft thread", () => {
+37 -11
View File
@@ -219,6 +219,7 @@ interface ComposerDraftStoreState {
attachments: PersistedComposerImageAttachment[],
) => void;
clearComposerContent: (threadId: ThreadId) => void;
clearThreadDraft: (threadId: ThreadId) => void;
}
const EMPTY_PROVIDER_MODEL_OPTIONS = Object.freeze<ProviderModelOptions>({});
@@ -1188,19 +1189,12 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
if (threadId.length === 0) {
return;
}
const existing = get().draftsByThreadId[threadId];
if (existing) {
for (const image of existing.images) {
revokeObjectPreviewUrl(image.previewUrl);
}
}
set((state) => {
const hasDraftThread = state.draftThreadsByThreadId[threadId] !== undefined;
const hasProjectMapping = Object.values(state.projectDraftThreadIdByProjectId).includes(
threadId,
);
const hasComposerDraft = state.draftsByThreadId[threadId] !== undefined;
if (!hasDraftThread && !hasProjectMapping && !hasComposerDraft) {
if (!hasDraftThread && !hasProjectMapping) {
return state;
}
const nextProjectDraftThreadIdByProjectId = Object.fromEntries(
@@ -1210,10 +1204,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
) as Record<ProjectId, ThreadId>;
const { [threadId]: _removedDraftThread, ...restDraftThreadsByThreadId } =
state.draftThreadsByThreadId;
const { [threadId]: _removedComposerDraft, ...restDraftsByThreadId } =
state.draftsByThreadId;
return {
draftsByThreadId: restDraftsByThreadId,
draftThreadsByThreadId: restDraftThreadsByThreadId,
projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId,
};
@@ -1747,6 +1738,41 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
return { draftsByThreadId: nextDraftsByThreadId };
});
},
clearThreadDraft: (threadId) => {
if (threadId.length === 0) {
return;
}
const existing = get().draftsByThreadId[threadId];
if (existing) {
for (const image of existing.images) {
revokeObjectPreviewUrl(image.previewUrl);
}
}
set((state) => {
const hasComposerDraft = state.draftsByThreadId[threadId] !== undefined;
const hasDraftThread = state.draftThreadsByThreadId[threadId] !== undefined;
const hasProjectMapping = Object.values(state.projectDraftThreadIdByProjectId).includes(
threadId,
);
if (!hasComposerDraft && !hasDraftThread && !hasProjectMapping) {
return state;
}
const { [threadId]: _removedComposerDraft, ...restComposerDraftsByThreadId } =
state.draftsByThreadId;
const { [threadId]: _removedDraftThread, ...restDraftThreadsByThreadId } =
state.draftThreadsByThreadId;
const nextProjectDraftThreadIdByProjectId = Object.fromEntries(
Object.entries(state.projectDraftThreadIdByProjectId).filter(
([, draftThreadId]) => draftThreadId !== threadId,
),
) as Record<ProjectId, ThreadId>;
return {
draftsByThreadId: restComposerDraftsByThreadId,
draftThreadsByThreadId: restDraftThreadsByThreadId,
projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId,
};
});
},
}),
{
name: COMPOSER_DRAFT_STORAGE_KEY,
-56
View File
@@ -1,56 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { isTerminalFocused } from "./terminalFocus";
class MockHTMLElement {
isConnected = false;
className = "";
readonly classList = {
contains: (value: string) => this.className.split(/\s+/).includes(value),
};
closest(selector: string): MockHTMLElement | null {
return selector === ".thread-terminal-drawer .xterm" && this.isConnected ? this : null;
}
}
const originalDocument = globalThis.document;
const originalHTMLElement = globalThis.HTMLElement;
afterEach(() => {
if (originalDocument === undefined) {
delete (globalThis as { document?: Document }).document;
} else {
globalThis.document = originalDocument;
}
if (originalHTMLElement === undefined) {
delete (globalThis as { HTMLElement?: typeof HTMLElement }).HTMLElement;
} else {
globalThis.HTMLElement = originalHTMLElement;
}
});
describe("isTerminalFocused", () => {
it("returns false for detached xterm helper textareas", () => {
const detached = new MockHTMLElement();
detached.className = "xterm-helper-textarea";
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement: detached } as Document;
expect(isTerminalFocused()).toBe(false);
});
it("returns true for connected xterm helper textareas", () => {
const attached = new MockHTMLElement();
attached.className = "xterm-helper-textarea";
attached.isConnected = true;
globalThis.HTMLElement = MockHTMLElement as unknown as typeof HTMLElement;
globalThis.document = { activeElement: attached } as Document;
expect(isTerminalFocused()).toBe(true);
});
});
-1
View File
@@ -1,7 +1,6 @@
export function isTerminalFocused(): boolean {
const activeElement = document.activeElement;
if (!(activeElement instanceof HTMLElement)) return false;
if (!activeElement.isConnected) return false;
if (activeElement.classList.contains("xterm-helper-textarea")) return true;
return activeElement.closest(".thread-terminal-drawer .xterm") !== null;
}
-16
View File
@@ -4,7 +4,6 @@ import {
commandForProjectScript,
nextProjectScriptId,
primaryProjectScript,
projectScriptCwd,
projectScriptRuntimeEnv,
projectScriptIdFromCommand,
setupProjectScript,
@@ -71,19 +70,4 @@ describe("projectScripts helpers", () => {
expect(env.CUSTOM_FLAG).toBe("1");
expect(env.T3CODE_WORKTREE_PATH).toBeUndefined();
});
it("prefers the worktree path for script cwd resolution", () => {
expect(
projectScriptCwd({
project: { cwd: "/repo" },
worktreePath: "/repo/worktree-a",
}),
).toBe("/repo/worktree-a");
expect(
projectScriptCwd({
project: { cwd: "/repo" },
worktreePath: null,
}),
).toBe("/repo");
});
});
-9
View File
@@ -63,15 +63,6 @@ interface ProjectScriptRuntimeEnvInput {
extraEnv?: Record<string, string>;
}
export function projectScriptCwd(input: {
project: {
cwd: string;
};
worktreePath?: string | null;
}): string {
return input.worktreePath ?? input.project.cwd;
}
export function projectScriptRuntimeEnv(
input: ProjectScriptRuntimeEnvInput,
): Record<string, string> {