From 7a1be1d65c852d71a77f270ba9d632fd6a1561e5 Mon Sep 17 00:00:00 2001 From: binjamshid <143622128+binjamshid@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:34:06 +0400 Subject: [PATCH] fix(server): import Codex Desktop chats assigned to a local project When Codex Desktop moves a scratch chat into a local project it can record the move only in .codex-global-state.json, leaving threads.project_id NULL in state_5.sqlite. Fall back to that explicit local assignment when the state database has no project for the thread. --- .../src/project/AgentSessionScanner.test.ts | 160 ++++++++++++++++++ .../server/src/project/AgentSessionScanner.ts | 64 ++++++- 2 files changed, 223 insertions(+), 1 deletion(-) diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 956a65976369f..f0275cf1806c8 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -1512,6 +1512,166 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect( + "imports Codex Desktop chats assigned to a local project when the state database has none", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const nowMs = Date.parse("2026-11-11T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const homeDir = yield* makeTempDir("t3code-home-"); + const projectDir = path.join(homeDir, "code", "my-project"); + const scratchRoot = path.join(homeDir, "Documents", "Codex", "2026-11-11"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + + const projectId = "local-project-1"; + const chats = [ + { + id: "019a6000-0000-7000-8000-00000000000a", + cwd: path.join(scratchRoot, "new-chat"), + message: "Moved in Codex Desktop", + assignment: { projectKind: "local", projectId }, + }, + { + id: "019a6000-0000-7000-8000-00000000000b", + cwd: path.join(scratchRoot, "new-chat-2"), + message: "Still with no project", + assignment: undefined, + }, + { + id: "019a6000-0000-7000-8000-00000000000c", + cwd: path.join(scratchRoot, "new-chat-3"), + message: "Assigned to a remote project", + assignment: { projectKind: "remote", projectId }, + }, + ]; + const rolloutPaths: Array = []; + for (const [index, chat] of chats.entries()) { + yield* fileSystem.makeDirectory(chat.cwd, { recursive: true }); + const filePath = path.join( + codexHomePath, + "sessions", + "2026", + "11", + "11", + `rollout-2026-11-11T08-0${index}-00-${chat.id}.jsonl`, + ); + rolloutPaths.push(filePath); + yield* writeTranscript({ + filePath, + contents: [ + encodeTranscriptRecord({ + type: "session_meta", + payload: { id: chat.id, cwd: chat.cwd }, + }), + encodeTranscriptRecord({ type: "turn_context", payload: { cwd: chat.cwd } }), + encodeTranscriptRecord({ + type: "event_msg", + payload: { type: "user_message", message: chat.message }, + }), + ].join("\n"), + mtimeMs: nowMs - 60_000 + index, + }); + } + // The state database has the threads but no project for any of them. + yield* Effect.sync(() => { + const db = new NodeSqlite.DatabaseSync(path.join(codexHomePath, "state_5.sqlite")); + try { + db.exec(` + CREATE TABLE projects (id TEXT PRIMARY KEY, name TEXT NOT NULL); + CREATE TABLE project_roots ( + project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + position INTEGER NOT NULL, + path TEXT NOT NULL, + PRIMARY KEY (project_id, position) + ); + CREATE TABLE threads ( + id TEXT PRIMARY KEY, + rollout_path TEXT NOT NULL, + cwd TEXT NOT NULL, + project_id TEXT REFERENCES projects(id) ON DELETE SET NULL + ); + `); + const insertThread = db.prepare("INSERT INTO threads VALUES (?, ?, ?, NULL)"); + for (const [index, chat] of chats.entries()) { + insertThread.run(chat.id, rolloutPaths[index]!, chat.cwd); + } + } finally { + db.close(); + } + }); + // Codex Desktop records the move only in its global state. + yield* fileSystem.writeFileString( + path.join(codexHomePath, ".codex-global-state.json"), + JSON.stringify({ + "thread-project-assignments": Object.fromEntries( + chats.flatMap((chat) => + chat.assignment === undefined ? [] : [[chat.id, chat.assignment]], + ), + ), + "local-projects": { + [projectId]: { + id: projectId, + name: "my-project", + rootPaths: [projectDir], + createdAt: nowMs, + updatedAt: nowMs, + }, + }, + }), + ); + + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + workspaceRoot: projectDir, + }).pipe(Effect.provideService(HostProcess.HomeDirectory, homeDir)); + expect(threads.map((thread) => thread.title)).toEqual(["Moved in Codex Desktop"]); + + const result = yield* runScan({ claudeHomePath, codexHomePath }).pipe( + Effect.provideService(HostProcess.HomeDirectory, homeDir), + ); + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual( + [{ path: projectDir, threadCount: 1 }], + ); + }), + ); + + it.effect("keeps Codex rollout cwds when the Codex Desktop global state is malformed", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + yield* writeTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "05", + "03", + "rollout-2026-05-03T00-00-00-019a5f00-0000-7000-8000-00000000000a.jsonl", + ), + contents: codexRolloutLine(workspace), + mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"), + }); + yield* fileSystem.writeFileString( + path.join(codexHomePath, ".codex-global-state.json"), + '{"thread-project-assignments": {"019a5f00-0000-7000-8000-00000000000a": ', + ); + + const result = yield* runScan({ claudeHomePath, codexHomePath }); + + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ + { path: workspace, threadCount: 1 }, + ]); + }), + ); + it.effect("imports a rewound Codex thread with the history its new rollout inherits", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 6c8410241a3f5..1f5affdfcb3d3 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -173,6 +173,45 @@ const CODEX_ROLLOUT_ID_PATTERN = /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))?\.jsonl$/i; // Codex records a chat's project only here; moving a chat leaves its rollout cwd unchanged. const CODEX_STATE_DATABASE = "state_5.sqlite"; +// Codex Desktop can record a move only in its global state, leaving `threads.project_id` NULL. +const CODEX_DESKTOP_GLOBAL_STATE = ".codex-global-state.json"; +const MAX_CODEX_DESKTOP_GLOBAL_STATE_BYTES = 32 * 1024 * 1024; + +const isRecord = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +// Thread ID → root paths of the local Codex Desktop project the thread is explicitly assigned to. +const parseCodexDesktopProjectRoots = ( + contents: string, +): ReadonlyMap> => { + const rootsByThread = new Map>(); + let state: unknown; + try { + state = JSON.parse(contents); + } catch { + return rootsByThread; + } + if (!isRecord(state)) return rootsByThread; + const assignments = state["thread-project-assignments"]; + const projects = state["local-projects"]; + if (!isRecord(assignments) || !isRecord(projects)) return rootsByThread; + for (const [threadId, assignment] of Object.entries(assignments)) { + if ( + !isRecord(assignment) || + assignment.projectKind !== "local" || + typeof assignment.projectId !== "string" + ) { + continue; + } + const project = projects[assignment.projectId]; + if (!isRecord(project) || !Array.isArray(project.rootPaths)) continue; + const roots = project.rootPaths.filter( + (root): root is string => typeof root === "string" && root.trim().length > 0, + ); + if (roots.length > 0) rootsByThread.set(threadId, roots); + } + return rootsByThread; +}; const decodeCodexSessionIndexEntry = Schema.decodeUnknownOption( Schema.fromJsonString(CodexSessionIndexEntry), ); @@ -1319,6 +1358,24 @@ export const make = Effect.gen(function* () { }).pipe(Effect.orElseSucceed((): ReadonlyMap> => new Map())); }); + const readCodexDesktopProjectRoots = Effect.fn( + "AgentSessionScanner.readCodexDesktopProjectRoots", + )(function* (homePath: string) { + const statePath = path.join(homePath, CODEX_DESKTOP_GLOBAL_STATE); + const stats = yield* statOption(statePath); + if ( + Option.isNone(stats) || + stats.value.type !== "File" || + Number(stats.value.size) > MAX_CODEX_DESKTOP_GLOBAL_STATE_BYTES + ) { + return new Map>(); + } + return yield* fileSystem.readFileString(statePath).pipe( + Effect.map(parseCodexDesktopProjectRoots), + Effect.orElseSucceed((): ReadonlyMap> => new Map()), + ); + }); + // Only chats left in an excluded folder, such as Codex's scratch folder, take their project's root. const projectCwd = (cwd: string, projectRoots: ReadonlyArray | undefined) => projectRoots !== undefined && @@ -1388,10 +1445,15 @@ export const make = Effect.gen(function* () { } } const projectRoots = yield* readCodexProjectRoots(homePath); + const desktopProjectRoots = yield* readCodexDesktopProjectRoots(homePath); return { transcripts: transcripts.map((transcript) => { const threadId = CODEX_ROLLOUT_ID_PATTERN.exec(transcript.filePath)?.[1]; - const roots = threadId === undefined ? undefined : projectRoots.get(threadId); + // The state database wins; Desktop assignments only fill threads it has no project for. + const roots = + threadId === undefined + ? undefined + : (projectRoots.get(threadId) ?? desktopProjectRoots.get(threadId)); return roots === undefined ? transcript : { ...transcript, projectRoots: roots }; }), truncated,