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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions electron/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,53 @@ function setupIpc() {
sessionWatcher.unwatch(sessionId);
});

// Validate that a session's JSONL file still exists on disk.
// Used before attempting --resume to avoid launching with a stale session ID.
ipcMain.handle(
"session:validate",
(_event, type: string, sessionId: string, cwd: string) => {
try {
if (type === "claude") {
const projectKey = cwd.replaceAll(/[/\\.:-]/g, "-");
const jsonlPath = path.join(
os.homedir(),
".claude",
"projects",
projectKey,
sessionId + ".jsonl",
);
const exists = fs.existsSync(jsonlPath);
dbg(`session:validate type=claude sid=${sessionId} file=${jsonlPath} exists=${exists}`);
return exists;
}
if (type === "codex") {
const sessionsDir = path.join(os.homedir(), ".codex", "sessions");
const now = new Date();
for (let d = 0; d < 7; d++) {
const date = new Date(now.getTime() - d * 86400000);
const yyyy = String(date.getFullYear());
const mm = String(date.getMonth() + 1).padStart(2, "0");
const dd = String(date.getDate()).padStart(2, "0");
const dayDir = path.join(sessionsDir, yyyy, mm, dd);
if (!fs.existsSync(dayDir)) continue;
const files = fs.readdirSync(dayDir);
if (files.find((f) => f.includes(sessionId))) {
dbg(`session:validate type=codex sid=${sessionId} found=true`);
return true;
}
}
dbg(`session:validate type=codex sid=${sessionId} found=false`);
return false;
}
// For other types (kimi, gemini, etc.), assume valid — no known file layout
return true;
} catch (err) {
dbg(`session:validate ERROR: ${err}`);
return false;
}
},
);

// State IPC
ipcMain.handle("state:load", () => {
return statePersistence.load();
Expand Down
2 changes: 2 additions & 0 deletions electron/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ contextBridge.exposeInMainWorld("termcanvas", {
>,
unwatch: (sessionId: string) =>
ipcRenderer.invoke("session:unwatch", sessionId),
validate: (type: string, sessionId: string, cwd: string) =>
ipcRenderer.invoke("session:validate", type, sessionId, cwd) as Promise<boolean>,
onTurnComplete: (callback: (sessionId: string) => void) => {
const listener = (
_event: Electron.IpcRendererEvent,
Expand Down
6 changes: 4 additions & 2 deletions src/stores/projectStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ export const useProjectStore = create<ProjectStore>((set) => ({
),
})),

updateTerminalSessionId: (projectId, worktreeId, terminalId, sessionId) =>
updateTerminalSessionId: (projectId, worktreeId, terminalId, sessionId) => {
set((state) => ({
projects: mapTerminals(
state.projects,
Expand All @@ -560,7 +560,9 @@ export const useProjectStore = create<ProjectStore>((set) => ({
terminalId,
(t) => ({ ...t, sessionId }),
),
})),
}));
markDirty();
},

updateTerminalType: (projectId, worktreeId, terminalId, type) =>
set((state) => ({
Expand Down
29 changes: 27 additions & 2 deletions src/terminal/TerminalTile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,8 @@ export function TerminalTile({

let ptyId: number | null = null;
const cliOverride = usePreferencesStore.getState().cliCommands[terminal.type] ?? undefined;
const wasResumeAttempt = !!terminal.sessionId && !!getTerminalLaunchOptions(terminal.type, terminal.sessionId, terminal.autoApprove);
let validatedSessionId: string | undefined = terminal.sessionId;
let wasResumeAttempt = !!terminal.sessionId && !!getTerminalLaunchOptions(terminal.type, terminal.sessionId, terminal.autoApprove);
let hasRespawned = false;
let inputDisposable: { dispose(): void } | null = null;
let resizeDisposable: { dispose(): void } | null = null;
Expand Down Expand Up @@ -502,7 +503,31 @@ export function TerminalTile({
});
};

spawnPty(terminal.sessionId);
// Validate session before attempting resume: if the CLI's session file
// was cleaned up (e.g. after force-kill during app update), start fresh
// immediately instead of launching with a stale --resume that will fail.
if (terminal.sessionId && (terminal.type === "claude" || terminal.type === "codex")) {
window.termcanvas.session
.validate(terminal.type, terminal.sessionId, worktreePath)
.then((valid) => {
if (valid) {
spawnPty(terminal.sessionId);
} else {
console.log(`[TermCanvas] Session ${terminal.sessionId} no longer valid, starting fresh`);
validatedSessionId = undefined;
wasResumeAttempt = false;
updateTerminalSessionId(projectId, worktreeId, terminal.id, undefined);
xterm.write("\x1b[33m[Previous session no longer available, starting fresh…]\x1b[0m\r\n");
spawnPty(undefined);
}
})
.catch(() => {
// Validation failed (IPC error), attempt resume anyway
spawnPty(terminal.sessionId);
});
} else {
spawnPty(terminal.sessionId);
}

let currentStatus: string = "running";
let waitingTimer: ReturnType<typeof setTimeout> | null = null;
Expand Down
1 change: 1 addition & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ export interface TermCanvasAPI {
getKimiLatest: (cwd: string) => Promise<string | null>;
watch: (type: string, sessionId: string, cwd: string) => Promise<{ ok: boolean; reason?: string }>;
unwatch: (sessionId: string) => Promise<void>;
validate: (type: string, sessionId: string, cwd: string) => Promise<boolean>;
onTurnComplete: (callback: (sessionId: string) => void) => () => void;
};
project: {
Expand Down