Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(importers): surface Codex 250-file scan cap
vastsacc0f78db0372
diff --git a/apps/desktop/electron/main/importers/codex.ts b/apps/desktop/electron/main/importers/codex.tsindex 7fcd794b3..b9a42c9b3 100644--- a/apps/desktop/electron/main/importers/codex.ts+++ b/apps/desktop/electron/main/importers/codex.ts@@ -156,11 +156,20 @@ async function parseFile(filePath: string): Promise<ParsedCodexFile | null> {return parsed.items.length > 0 ? parsed : null;}+export const CODEX_SCAN_FULL_PARSE_MAX_BYTES = 5 * 1024 * 1024;+// Newest-first walk of ~/.codex/sessions/YYYY/MM/DD. Reverse path sort is a+// creation-date proxy, not mtime or the session's updatedAt — a January+// session still being appended to can fall outside this cap.+export const CODEX_SCAN_MAX_FILES = 250;+const CODEX_SCAN_HEAD_BYTES = 1024 * 1024;+const CODEX_SCAN_TAIL_BYTES = 256 * 1024;+async function listSessionFiles(dir: string = SESSIONS_DIR,maxFiles: number = CODEX_SCAN_MAX_FILES,-): Promise<string[]> {+): Promise<{ files: string[]; truncated: boolean }> {const out: string[] = [];+ let truncated = false;const walk = async (dir: string, depth: number) => {let entries: string[] = [];try {@@ -170,7 +179,10 @@ async function listSessionFiles(}entries.sort().reverse();for (const entry of entries) {- if (out.length >= maxFiles) return;+ if (out.length >= maxFiles) {+ truncated = true;+ return;+ }const full = path.join(dir, entry);if (entry.endsWith(".jsonl")) {out.push(full);@@ -180,7 +192,7 @@ async function listSessionFiles(}};await walk(dir, 0);- return out;+ return { files: out, truncated };}// ---------- Scan (#264): sampled metadata extraction for large archives ----------@@ -199,10 +211,6 @@ async function listSessionFiles(// - messageCount: null (the UI shows "—" — counting items exactly would// require reading the whole file, which sampling exists to avoid).-export const CODEX_SCAN_FULL_PARSE_MAX_BYTES = 5 * 1024 * 1024;-export const CODEX_SCAN_MAX_FILES = 250;-const CODEX_SCAN_HEAD_BYTES = 1024 * 1024;-const CODEX_SCAN_TAIL_BYTES = 256 * 1024;interface CodexScanMeta {externalId: string;@@ -401,12 +409,17 @@ async function scanFile(filePath: string): Promise<CodexScanMeta | null> {}}-export async function scanCodexSessions(+export interface CodexScanResult {+ sessions: ExternalSessionSummary[];+ truncated: boolean;+}++export async function scanCodexSessionsResult(dir: string = SESSIONS_DIR,maxFiles: number = CODEX_SCAN_MAX_FILES,-): Promise<ExternalSessionSummary[]> {- const files = await listSessionFiles(dir, maxFiles);- const summaries: ExternalSessionSummary[] = [];+): Promise<CodexScanResult> {+ const { files, truncated } = await listSessionFiles(dir, maxFiles);+ const sessions: ExternalSessionSummary[] = [];for (const filePath of files) {const meta = await scanFile(filePath);if (!meta || meta.firstUserText === null) continue;@@ -414,7 +427,7 @@ export async function scanCodexSessions(// session's history to the import moment (#265): the file's own mtime is// the honest fallback for both ends.const fileTime = toIso(meta.mtimeMs);- summaries.push({+ sessions.push({source: "codex",externalId: meta.externalId,title: truncateTitle(meta.firstUserText) || meta.externalId,@@ -426,9 +439,17 @@ export async function scanCodexSessions(filePath,});}- return summaries;+ return { sessions, truncated };+}++export async function scanCodexSessions(+ dir: string = SESSIONS_DIR,+ maxFiles: number = CODEX_SCAN_MAX_FILES,+): Promise<ExternalSessionSummary[]> {+ return (await scanCodexSessionsResult(dir, maxFiles)).sessions;}+export const codexImporter: SessionImporter = {source: "codex",diff --git a/apps/desktop/electron/main/importers/index.ts b/apps/desktop/electron/main/importers/index.tsindex 523ef3f20..f78fe8e9e 100644--- a/apps/desktop/electron/main/importers/index.ts+++ b/apps/desktop/electron/main/importers/index.ts@@ -1,5 +1,5 @@import { claudeImporter } from "./claude";-import { codexImporter } from "./codex";+import { CODEX_SCAN_MAX_FILES, codexImporter, scanCodexSessionsResult } from "./codex";import { opencodeImporter } from "./opencode";import { piImporter } from "./pi";import type {@@ -19,19 +19,29 @@ const importers: SessionImporter[] = [piImporter,];-export async function scanAllSources(): Promise<ExternalSessionSummary[]> {+export async function scanAllSources(): Promise<{+ sessions: ExternalSessionSummary[];+ truncated: Partial<Record<ExternalSource, number>>;+}> {+ const truncated: Partial<Record<ExternalSource, number>> = {};const results = await Promise.all(importers.map(async (imp) => {try {+ if (imp.source === "codex") {+ const result = await scanCodexSessionsResult();+ if (result.truncated) truncated.codex = CODEX_SCAN_MAX_FILES;+ return result.sessions;+ }return await imp.scan();} catch {return [];}}),);- return results- .flat()- .sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1));+ return {+ sessions: results.flat().sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1)),+ truncated,+ };}export async function convertSession(@@ -41,3 +51,4 @@ export async function convertSession(if (!importer) throw new Error(`unknown import source: ${summary.source}`);return importer.convert(summary);}+diff --git a/apps/desktop/electron/main/ipc/session-ipc.ts b/apps/desktop/electron/main/ipc/session-ipc.tsindex 1ced88424..c63162b7c 100644--- a/apps/desktop/electron/main/ipc/session-ipc.ts+++ b/apps/desktop/electron/main/ipc/session-ipc.ts@@ -567,14 +567,16 @@ export function registerSessionIpc({);handle(IPC.invoke.sessionImportScan, async () => {- const sessions = await scanAllSources();+ const { sessions, truncated } = await scanAllSources();scannedImportSessions = new Map(sessions.map((session) => [`${session.source}:${session.externalId}`, session]),);return {sessions: sessions.map(({ filePath: _filePath, ...candidate }) => candidate),+ ...(Object.keys(truncated).length > 0 ? { truncated } : {}),};});+handle(IPC.invoke.sessionImportRun,async (selections: unknown) => {diff --git a/apps/desktop/src/features/settings/import-page.tsx b/apps/desktop/src/features/settings/import-page.tsxindex 3fefcfd4b..c7f8ab542 100644--- a/apps/desktop/src/features/settings/import-page.tsx+++ b/apps/desktop/src/features/settings/import-page.tsx@@ -414,6 +414,8 @@ export function SessionImportPanel() {const disclosure = useGroupDisclosure();const [scanning, setScanning] = useState(false);const [importing, setImporting] = useState(false);+ const [codexCap, setCodexCap] = useState<number | null>(null);+const keyOf = (candidate: ImportCandidate) =>`${candidate.source}:${candidate.externalId}`;@@ -423,8 +425,10 @@ export function SessionImportPanel() {try {const res = await api.scanImportSessions();setCandidates(res.sessions);+ setCodexCap(typeof res.truncated?.codex === "number" ? res.truncated.codex : null);setSelected(new Set());disclosure.reset();+} catch (e) {showToast(e instanceof Error ? e.message : String(e), { variant: "error" });} finally {@@ -527,12 +531,16 @@ export function SessionImportPanel() {/>}/>+ {codexCap != null ? (+ <p className="import-hint">{t("settings.importCodexCapped", { limit: codexCap })}</p>+ ) : null}<ImportResultsmessage={candidates.length === 0 ? t("settings.importNone") : undefined}><div className="import-groups">+{groups.map((group, groupIndex) => {const groupKeys = group.items.map(keyOf);const groupSelected = groupKeys.filter((k) => selected.has(k)).length;diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex f095e07db..e89dda843 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -555,7 +555,11 @@ export const api = {config,).then((result) => ({ ...result, session: normalizeSession(result.session) })),scanImportSessions: () =>- invoke<{ sessions: ImportCandidate[] }>(IPC.invoke.sessionImportScan),+ invoke<{+ sessions: ImportCandidate[];+ truncated?: Partial<Record<ImportSource, number>>;+ }>(IPC.invoke.sessionImportScan),+runImportSessions: (items: ImportCandidate[]) =>invoke<ImportRunResult>(IPC.invoke.sessionImportRun, items),scanImportModelConfigs: () =>diff --git a/apps/desktop/test/importer-codex-scan.test.mjs b/apps/desktop/test/importer-codex-scan.test.mjsindex 12bcfa57d..bed0f8d52 100644--- a/apps/desktop/test/importer-codex-scan.test.mjs+++ b/apps/desktop/test/importer-codex-scan.test.mjs@@ -9,9 +9,13 @@ import { fileURLToPath, pathToFileURL } from "node:url";const here = dirname(fileURLToPath(import.meta.url));register(pathToFileURL(joinPath(here, "helpers/ts-import-hooks.mjs")));-const { CODEX_SCAN_FULL_PARSE_MAX_BYTES, CODEX_SCAN_MAX_FILES, scanCodexSessions } = await import(- "../electron/main/importers/codex.ts"-);+const {+ CODEX_SCAN_FULL_PARSE_MAX_BYTES,+ CODEX_SCAN_MAX_FILES,+ scanCodexSessions,+ scanCodexSessionsResult,+} = await import("../electron/main/importers/codex.ts");+const iso = (value) => new Date(value).toISOString();@@ -421,6 +425,44 @@ test("scans newest sessions first and bounds total files to limit", async () =>assert.equal(summaries.length, 1);assert.equal(summaries[0].externalId, "new-1");assert.equal(summaries[0].title, "今天的最新消息");+ const detailed = await scanCodexSessionsResult(dir, 1);+ assert.equal(detailed.truncated, true);+ assert.equal(detailed.sessions[0].externalId, "new-1");+ const uncapped = await scanCodexSessionsResult(dir);+ assert.equal(uncapped.truncated, false);+ assert.equal(uncapped.sessions.length, 2);},);});++test("the default 250-file cap keeps the newest path-dated sessions", async () => {+ const cases = [];+ for (let i = 0; i < CODEX_SCAN_MAX_FILES; i += 1) {+ const id = `new-${String(i).padStart(3, "0")}`;+ cases.push([+ `2026/09/18/${id}.jsonl`,+ [+ metaLine(id, "/repo", "2026-09-18T00:00:00Z"),+ responseItem("user", id, "2026-09-18T00:00:01Z"),+ ].join("\n"),+ ]);+ }+ cases.push([+ "2026/01/01/old.jsonl",+ [+ metaLine("old-1", "/repo", "2026-01-01T00:00:00Z"),+ responseItem("user", "很早以前的消息", "2026-01-01T00:00:01Z"),+ ].join("\n"),+ ]);+ await withArchive(cases, async (dir) => {+ const { sessions, truncated } = await scanCodexSessionsResult(dir);+ assert.equal(truncated, true);+ assert.equal(sessions.length, CODEX_SCAN_MAX_FILES);+ assert.ok(sessions.every((session) => session.externalId.startsWith("new-")));+ assert.equal(+ sessions.some((session) => session.externalId === "old-1"),+ false,+ );+ });+});+diff --git a/apps/desktop/test/settings-import-page.test.mjs b/apps/desktop/test/settings-import-page.test.mjsindex d5a98b2cd..cc81e03e4 100644--- a/apps/desktop/test/settings-import-page.test.mjs+++ b/apps/desktop/test/settings-import-page.test.mjs@@ -56,8 +56,10 @@ test("every kind keeps its own scan and its state across a tab switch", () => {}// No kind may start another kind's scan.assert.match(page, /api\.scanImportSessions\(\)/);+ assert.match(page, /settings\.importCodexCapped/);assert.match(page, /api\.scanExternalMcp\(\)/);+// Panels stay mounted and only `hidden` takes the inactive one out of view.assert.match(page, /hidden={kind !== entry\.id}/);assert.match(cssRule(".import-view[hidden]"), /display:\s*none/);diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex 44e36d717..d8e5a4940 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1014,7 +1014,7 @@ Minimal interface:directory, creates it if missing, and opens it in the system file manager.The renderer supplies only the session id; Main rejects a path outside thescratch root.-- `session/importScan`+- `session/importScan -> { sessions, truncated? }`- `session/importRun(candidates) -> { imported, skipped, failed }`- `modelConfig/importScan -> { providers }`- `modelConfig/importRun(candidates) -> { imported, skipped, failed }`@@ -1024,7 +1024,10 @@ Import candidates carry `projectPath: string | null` andimporter's sampled-scan threshold; larger files are sampled (head + tail) soscanning a multi-gigabyte archive stays interactive, and their `messageCount`is null — the import list renders an em dash for it, while imported sessions-always compute their real message count at convert time. Scan titles come+always compute their real message count at convert time. Codex discovery also+caps traversal at 250 session files, walking `YYYY/MM/DD` paths newest-first+(path date, not `updatedAt`). Hitting that cap sets `truncated.codex` to 250+so the renderer can say the list is incomplete. Scan titles comefrom the first real user message: known synthetic injections (repoinstructions, the IDE-context family such as `# Context from my IDE setup:`or `# Browser comments:`) are skipped, while pasted markdown starting with@@ -1032,6 +1035,7 @@ or `# Browser comments:`) are skipped, while pasted markdown starting withsource file's mtime, never to the import moment. A successful importrefreshes both sessions and the durable Projects index.+`modelConfig/importScan` reads Claude Code, Codex, OpenCode, Pi, and CCSwitch config files from the user home directory and returns public provider drafts(`source`, `externalId`, `name`, `baseUrl`, `apiStyle`, `modelIds`,diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.mdindex a9280fb96..37045e280 100644--- a/docs/spec/04-ux/06-settings-ia.md+++ b/docs/spec/04-ux/06-settings-ia.md@@ -547,7 +547,11 @@ system while preserving their different data ownership:project-path grouping behavior follows[08-component-spec §18](08-component-spec.md#18-import-destination).The Group-by control is the same in-app menu select as the Appearance and- Permissions pickers, not a platform-drawn `<select>`.+ Permissions pickers, not a platform-drawn `<select>`. A Codex archive larger+ than `CODEX_SCAN_MAX_FILES` (250) is truncated to the newest session files by+ `YYYY/MM/DD` path date; the workbench shows a localized cap note, and omitted+ Codex files are not in that candidate list.+- Model configuration: review provider drafts through`ModelConfigImportPanel`([08-component-spec §18.5](08-component-spec.md#185-modelconfigimportpanel)).diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 2d8700ded..eb654b4c0 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -3290,6 +3290,12 @@ CLAUDE CODE ~/code/pi 4- A successful scan replaces the prior candidate set, clears selection, andshows every group expanded: the found candidates are the answer to the scan,so they are not hidden behind a second click.+- Codex session discovery walks `~/.codex/sessions/YYYY/MM/DD` newest-path-first+ and stops after 250 `.jsonl` files. That order is folder-date lexicographic,+ not `updatedAt`. When the cap hits, `session/importScan` returns+ `truncated.codex = 250` and the sessions toolbar shows the localized cap note;+ older Codex files are absent from the candidate list.+- Every kind scans on its own: a session scan never starts a model-config,skills, or MCP scan, and switching tabs preserves the result and theselection of the kind left behind (inactive panels stay mounted and hidden).diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 718d9f371..930c2b4da 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1989,7 +1989,8 @@ identify the platform validation still needed.- **Preconditions**: Supported local agent stores contain importable sessions across at least two project paths and two sources, including one session without a project path; the app can be launched once with an English system locale and once with a Simplified Chinese system locale.- **Steps**: 1) Launch in English and open Settings → Import. 2) Scan for sessions. 3) Inspect the initial source groups. 4) Expand one group and select a session. 5) Change Group by to Project path. 6) Switch back to Source. 7) Repeat the flow after launching with a Simplified Chinese system locale.-- **Expected**: Source/来源 is the initial grouping; all groups are collapsed after the scan and after either grouping change; project-path mode shows exact project paths and a final No project/未关联项目 group; expanding one group leaves the others collapsed; the selected session remains selected across grouping changes; counts, dates, selection labels, accessible names, and the import result use the active locale without raw keys or unresolved double-brace placeholders. A Codex archive above the scan threshold may show an em dash for its unknown message count during review, but it remains selectable and the later import converts the complete transcript.+- **Expected**: Source/来源 is the initial grouping; all groups are collapsed after the scan and after either grouping change; project-path mode shows exact project paths and a final No project/未关联项目 group; expanding one group leaves the others collapsed; the selected session remains selected across grouping changes; counts, dates, selection labels, accessible names, and the import result use the active locale without raw keys or unresolved double-brace placeholders. A Codex archive above the scan threshold may show an em dash for its unknown message count during review, but it remains selectable and the later import converts the complete transcript. A Codex archive with more than 250 session files shows only the newest 250 by folder date plus a localized cap note; older Codex sessions are absent from that scan.+- **Specs linked**: `04-ux/01-ui-ia.md`, `04-ux/02-i18n-english-first.md`, `04-ux/08-component-spec.md`- **Acceptance**: F (session import review)- **Milestone**: M2diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 9d5fe4515..05d5c900c 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -880,7 +880,9 @@ sklm: {"importFound": "Sitzungen gefunden: {{count}}","importFound_one": "1 Sitzung gefunden","importFound_other": "{{count}} Sitzungen gefunden",+ "importCodexCapped": "Codex ist auf die {{limit}} neuesten Sitzungsdateien (nach Ordnerdatum) begrenzt.","importNone": "Auf diesem Computer wurden keine importierbaren Sitzungen gefunden.",+"importSelectAll": "Alle auswählen","importSelected": "Ausgewählte importieren ({{count}})","importing": "Importieren…",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 8c1d2b2ee..d5929956e 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -892,7 +892,9 @@ sklm: {importFound: "Sessions found: {{count}}",importFound_one: "1 session found",importFound_other: "{{count}} sessions found",+ importCodexCapped: "Codex is limited to the {{limit}} newest session files (by folder date).",importNone: "No importable sessions found on this machine.",+importSelectAll: "Select all",importSelected: "Import selected ({{count}})",importing: "Importing…",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 95b1e019e..6e2c946ab 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -880,7 +880,9 @@ sklm: {"importFound": "Sesiones encontradas: {{count}}","importFound_one": "1 sesión encontrada","importFound_other": "{{count}} sesiones encontradas",+ "importCodexCapped": "Codex se limita a los {{limit}} archivos de sesión más recientes (por fecha de carpeta).","importNone": "No se encontraron sesiones importables en esta máquina.",+"importSelectAll": "Seleccionar todo","importSelected": "Importar seleccionado ({{count}})","importing": "Importando…",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 2c4f4fe88..3a518e772 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -880,7 +880,9 @@ sklm: {"importFound": "Sessions trouvées : {{count}}","importFound_one": "1 session trouvée","importFound_other": "{{count}} sessions trouvées",+ "importCodexCapped": "Codex est limité aux {{limit}} fichiers de session les plus récents (par date de dossier).","importNone": "Aucune session importable trouvée sur cette machine.",+"importSelectAll": "Sélectionner tous les","importSelected": "Importer la sélection ({{count}})","importing": "Importer…",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex ae11e0d38..9a600ca44 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -892,7 +892,9 @@ sklm: {importFound: "찾은 세션: {{count}}",importFound_one: "세션 1개 찾음",importFound_other: "세션 {{count}}개 찾음",+ importCodexCapped: "Codex는 폴더 날짜 기준 최신 세션 파일 {{limit}}개만 표시합니다.",importNone: "이 컴퓨터에서 가져올 수 있는 세션을 찾지 못했습니다.",+importSelectAll: "모두 선택",importSelected: "선택 항목 가져오기 ({{count}})",importing: "가져오는 중…",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 437d15746..8ed501526 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -892,7 +892,9 @@ sklm: {importFound: "Bulunan oturumlar: {{count}}",importFound_one: "1 oturum bulundu",importFound_other: "{{count}} oturum bulundu",+ importCodexCapped: "Codex, klasör tarihine göre en yeni {{limit}} oturum dosyasıyla sınırlıdır.",importNone: "Bu makinede içe aktarılabilir oturum bulunamadı.",+importSelectAll: "Tümünü seç",importSelected: "Seçilenleri içe aktar ({{count}})",importing: "İçe aktarılıyor…",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 07f87fdcd..864fc1174 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -881,7 +881,9 @@ sklm: {importFound: "发现 {{count}} 个会话",importFound_one: "发现 1 个会话",importFound_other: "发现 {{count}} 个会话",+ importCodexCapped: "Codex 仅列出按目录日期最新的 {{limit}} 个会话文件。",importNone: "未在本机发现可导入的会话。",+importSelectAll: "全选",importSelected: "导入所选({{count}})",importing: "正在导入…",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex b94bfea55..617a4ebd1 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -881,7 +881,9 @@ sklm: {importFound: "發現 {{count}} 個會話",importFound_one: "發現 1 個會話",importFound_other: "發現 {{count}} 個會話",+ importCodexCapped: "Codex 僅列出依目錄日期最新的 {{limit}} 個工作階段檔案。",importNone: "未在本機發現可匯入的會話。",+importSelectAll: "全選",importSelected: "匯入所選({{count}})",importing: "正在匯入…",