From 27b9a640077c6cab656e489b1380732222290858 Mon Sep 17 00:00:00 2001 From: neo Date: Wed, 11 Nov 2026 19:39:53 +0800 Subject: [PATCH 01/18] =?UTF-8?q?feat:=201.9.0=20=E2=80=94=20zstd=20rollou?= =?UTF-8?q?ts,=20Codex=20titles/projects,=20goal=20mode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Import fidelity - read `rollout-*.jsonl.zst` with the runtime's own node:zlib zstd decoder (no new dependency, no conversion of Codex data); multi-frame rollouts are decoded frame by frame instead of stopping at frame one - stream rollouts instead of `readFileSync`, so the 256 MiB guard no longer hides real conversations (default cap now 2 GiB); two sessions here (388 MiB and 1.2 GB) were previously invisible - drop the Codex desktop envelopes that leaked into transcripts as user messages: `` (whole SKILL.md), ``, ``, ``, ``, ``, ``; `` and `` stay - carry goal mode across: read `event_msg/thread_goal_updated` and replay it as the `goal/change` events DSH derives goals from (create + transition); on re-import append only a changed phase Catalog fidelity - new `lib/codex-index.mjs`: titles and projects come from `~/.codex/state_5.sqlite` (`threads.name`, `projects.name`, `project_roots.path`), with `session_index.jsonl` and the rollout as fallbacks - group the picker by Codex project (one project owns several repo roots) and hide guardian reviews / spawned sub-agents by default, matching the sidebar - workspace titles are the Codex project name, never a path; auto-generated `base (path)` titles are migrated at startup and on attach - export writes `thread_goal_updated` so a DSH goal reappears in Codex Compatibility - resolve `@deepseek-ai/dsh-session-format-*` inside the Desktop app on Windows (`process.resourcesPath` → `app.asar/dsh/node_modules`), which the v0→v4 migration needs on that platform - accept host 0.2.2-rc.1; listen to `agent/created` (the old `agent/session-start` name does not exist, so autoImport never ran) - importing no longer reloads the page; the result panel offers a manual refresh instead - test harness: Windows-safe ESM imports (`pathToFileURL`), zstd/native decoding in tests, new suites for the Codex index and workspace titles Verification: 12 suites / 77 tests green; `node --check` clean on lib+bin; `npm pack --dry-run` still ships cordis.patch.yml and lib/client.js. --- .gitignore | 1 + CHANGELOG.md | 118 ++++++++++++++ bin/dsh-codex-sync.js | 38 ++++- lib/attach-workspaces.mjs | 77 +++++---- lib/client.js | 31 ++-- lib/codex-index.mjs | 266 +++++++++++++++++++++++++++++++ lib/codex-reader.mjs | 206 ++++++++++++++++++------ lib/export-codex.js | 81 ++++++++-- lib/import-service.js | 204 ++++++++++++++++++++---- lib/index.js | 29 +++- lib/session-migrate.mjs | 30 +++- lib/zstd-frame.mjs | 41 +++++ package.json | 4 +- scripts/extract-asar-subtree.mjs | 52 ++++++ scripts/run-tests.mjs | 2 + test/attach-workspaces.test.mjs | 131 +++++++++++++++ test/codex-index.test.mjs | 114 +++++++++++++ test/codex-reader.test.mjs | 171 +++++++++++++++++--- test/export-codex.test.mjs | 45 +++++- test/host.smoke.mjs | 11 +- test/import-service.test.mjs | 47 ++++++ test/item-sync.test.mjs | 13 +- test/zstd-frame.test.mjs | 12 +- 23 files changed, 1524 insertions(+), 200 deletions(-) create mode 100644 lib/codex-index.mjs create mode 100644 scripts/extract-asar-subtree.mjs create mode 100644 test/attach-workspaces.test.mjs create mode 100644 test/codex-index.test.mjs diff --git a/.gitignore b/.gitignore index a1127ae..6625018 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules/ *.tgz .DS_Store +.npm-cache/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5837f7d..e8be3ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,123 @@ # Changelog +## 1.9.0 — 2026-11-11 + +- **Goal mode now survives the trip in both directions.** + - Codex → DSH: the reader picks up Codex's `event_msg/thread_goal_updated` + snapshots (the last one wins) and the importer replays them as the + `goal/change` events DSH's `ctx.goals` reads ("backed exclusively by the + owning session log"), so an unfinished Codex goal arrives **active** and a + paused one arrives paused. On re-import only the transition is appended, and + only when the phase actually changed. + - DSH → Codex: the exporter reads the session's last `goal/change` and writes a + `thread_goal_updated` snapshot into the rollout, so Codex shows the goal + again. `active`/`paused` map directly; a `blocked` goal exports as `paused` + (Codex's known statuses are only active/paused); a **completed** goal is not + re-exported as a live one. +- Goal `objective`, `createdAt`/`updatedAt` and the goal id + (`goal-codex-`, stable across re-imports) are preserved; Codex's + `tokensUsed`/`timeUsedSeconds` are not carried into DSH's `roundsStarted` + (different meaning). +- Tests: reader goal snapshot, import (create + pause), re-import transition, + export snapshot + blocked/complete mapping. 77 tests total. + +## 1.8.5 — 2026-11-11 + +- Filter the other Codex desktop envelopes that were imported as user messages: + ``, ``, + `` (opened pages, streamed block edits), + ``, ``, + ``, ``, and the + `` placeholder. The opener now also + matches tags that carry attributes (`<… source="goal">`). +- Kept on purpose: `` (real assistant content) and + `` (carries the user's own answer). +- Over the 1134 rollouts here, the envelopes that leaked into transcripts went + from ~8100 blocks to 0 (only those two kept families remain). + +## 1.8.4 — 2026-11-11 + +- **Activated skills no longer land in the imported transcript.** Codex hands a + skill to the model as a user message wrapped in `…` (the whole + SKILL.md: frontmatter, path and body), and the reader only dropped a fixed list + of openers, so the skill text was imported as if the user had typed it. + `` / `` are now filtered like the other injections. +- Verified over all 1132 rollouts here: 0 remaining `` blocks (one + imported chat had 20 of them). + +## 1.8.3 — 2026-11-11 + +- Listen for `agent/created` instead of `agent/session-start`: this DSH build + has no `agent/session-start` event, so both startup hooks were silent no-ops. + The catalog event is `agent/created({ agent, source })` with + `SessionStartSource = 'startup' | 'resume' | 'clear' | 'compact'`. +- Affected: the autoImport startup hook (it never imported) and the new + workspace-title migration hook; the latter now runs once per process. + +## 1.8.2 — 2026-11-11 + +- **Workspaces are named after the Codex project, not the path.** Attaching an + imported session used to title its workspace `basename (~/…/path)`, so one + Codex project (which owns several repo roots) showed up under each repo's + folder name, with a path glued on. Titles are now `projects.name` from + `~/.codex/state_5.sqlite` (`zbwx-frontend-v2 (~/…)` → `zbwx-v2`), falling back + to the folder name alone — never a path. +- Existing auto-generated titles are migrated at startup and on every attach + (`/attach-workspaces` included). Titles you renamed yourself are left alone. +- New `test/attach-workspaces.test.mjs` covers project-name resolution, the + path-free fallback, the legacy-title migration and custom-title preservation. + +## 1.8.1 — 2026-11-11 + +- **Importing no longer reloads the whole page.** The client used to call + `window.location.reload()` 2.5 s after a successful import (on both the HTTP + and command paths), which interrupted whatever you were reading. It now + re-fetches the plugin's own catalog so the rows flip to "imported", and offers + 「刷新列表」/「Refresh list」 in the result panel for the sidebar, which the Host + owns and does not let a plugin refresh in place. +- Removed the now-unused reload timer and its cleanup effect. + +## 1.8.0 — 2026-11-11 + +- **Titles and project names now come from Codex's own state** + (`~/.codex/state_5.sqlite`): `threads.name` is the title the sidebar shows + (`threads.title` is often a pasted prompt), and `projects.name` + + `project_roots.path` give the project a chat belongs to. Previously titles + came from `session_index.jsonl` (which misses ~25% of threads and can be + stale) and projects were guessed from the cwd folder name, which split one + Codex project into several entries (e.g. `zbwx-v2` appeared per repo). +- **Internal threads are no longer listed as chats**: Codex marks guardian + reviews (`{"subagent":{"other":"guardian"}}`, ~985 rows here) and spawned + sub-agents in `threads.source`; both are now hidden unless sub-agents are + requested, matching the Codex sidebar. Their nesting uses the recorded + `parent_thread_id`. +- **The 256 MiB session cap is gone by default (now 2 GiB)**: the reader streams, + so the cap only hid real conversations. Two sessions here (388 MiB and 1.2 GB, + 6090 and 8882 messages) previously never appeared in the list. +- `doctor` reports the catalog source and the zstd/compressed session split. +- New `test/codex-index.test.mjs` covers path normalization, title precedence, + project resolution (by id and longest root) and origin classification. + +## 1.7.1 — 2026-11-11 + +- **Read zstd-compressed Codex rollouts** (`rollout-*.jsonl.zst`, what current Codex + Desktop writes). Inflating them uses the runtime's own `node:zlib` zstd decoder, so + no extra dependency and no conversion of Codex's data is needed. Multi-frame + rollouts (a rollout extended by appending a frame) are decoded frame by frame + instead of stopping at the first frame. +- **Keep the Codex thread name on import**: titles come from + `~/.codex/session_index.jsonl` (`thread_name`) instead of falling back to the + first prompt. +- **Stream rollouts instead of `readFileSync`**, so a large session can no longer hit + Node's string-length ceiling. +- **Find the session-format migration packages inside the Desktop app on Windows** + (`process.resourcesPath` → `app.asar/dsh/node_modules`), which is required to + import into the current (v4) format on that platform. +- Accept host `0.2.2-rc.1` in `peerDependencies`. +- Tests: reader runs on the installed DSH packages (17 import-service tests green + against v0→v4), plus coverage for compressed and multi-frame rollouts and for + Windows-correct ESM imports in the test harness. + ## 1.6.2 — 2026-10-05 - Import sessions in the installed DSH current format and support handle-based persistence, incremental assistant replies, new turns, and idempotent re-imports (PR #3). diff --git a/bin/dsh-codex-sync.js b/bin/dsh-codex-sync.js index b04c761..3885f32 100755 --- a/bin/dsh-codex-sync.js +++ b/bin/dsh-codex-sync.js @@ -124,16 +124,28 @@ export function ensureReverseServer(dir, noBuild) { log(`✓ reverse MCP server already built: ${cliPath}`) return cliPath } - log(`→ cloning ${REVERSE_REPO} into ${dir}`) - execFileSync('git', ['clone', '--depth', '1', REVERSE_REPO, dir], { stdio: 'inherit' }) + if (!existsSync(dir)) { + log(`→ cloning ${REVERSE_REPO} into ${dir}`) + execFileSync('git', ['clone', '--depth', '1', REVERSE_REPO, dir], { stdio: 'inherit' }) + } else { + log(`→ directory exists, skipping clone: ${dir}`) + } if (noBuild) { log('! --no-build: server cloned but not built; run `pnpm install && pnpm build` inside the dir') return cliPath } log('→ pnpm install') - execFileSync('pnpm', ['install'], { cwd: dir, stdio: 'inherit' }) - log('→ pnpm build') - execFileSync('pnpm', ['build'], { cwd: dir, stdio: 'inherit' }) + const pnpmPath = 'C:\\Users\\neo\\.dsh\\dsh-runtimes\\dsh-primary-runtime\\dependencies\\pnpm\\bin\\pnpm.mjs' + const nodeBin = process.execPath + if (existsSync(pnpmPath)) { + execFileSync(nodeBin, [pnpmPath, 'install'], { cwd: dir, stdio: 'inherit' }) + log('→ pnpm build') + execFileSync(nodeBin, [pnpmPath, 'build'], { cwd: dir, stdio: 'inherit' }) + } else { + execFileSync('pnpm', ['install'], { cwd: dir, stdio: 'inherit' }) + log('→ pnpm build') + execFileSync('pnpm', ['build'], { cwd: dir, stdio: 'inherit' }) + } if (!existsSync(cliPath)) { throw new Error(`build finished but ${cliPath} is missing`) } @@ -219,22 +231,25 @@ async function cmdDoctor(args) { // codex sessions + oversized risk try { const { listCodexSessions, parseCodexSession } = await import('../lib/codex-reader.mjs') + const { DEFAULT_MAX_SESSION_BYTES } = await import('../lib/import-service.js') const files = listCodexSessions(join(CODEX_HOME, 'sessions')) let big = 0 let ok = 0 let subagents = 0 + let compressed = 0 const { statSync } = await import('node:fs') for (const f of files) { + if (f.endsWith('.zst')) compressed += 1 let size = 0 try { size = statSync(f).size } catch { continue } - if (size > 256 * 1024 * 1024) big += 1 + if (size > DEFAULT_MAX_SESSION_BYTES) big += 1 else { try { - const header = parseCodexSession(f).header + const header = (await parseCodexSession(f)).header if (header.id) { ok += 1 if (header.parentThreadId) subagents += 1 @@ -244,7 +259,14 @@ async function cmdDoctor(args) { } } } - lines.push(`codex sessions: ${files.length} files, ${ok} importable, ${subagents} sub-agent threads (filtered from import), ${big} oversized (>256MiB, skipped)`) + lines.push(`codex sessions: ${files.length} files (${compressed} zstd-compressed), ${ok} importable, ${subagents} internal threads (guardian/sub-agent, filtered from import), ${big} oversized (>${Math.round(DEFAULT_MAX_SESSION_BYTES / 1024 / 1024)}MiB, skipped)`) + try { + const { loadCodexIndex } = await import('../lib/codex-index.mjs') + const index = loadCodexIndex(CODEX_HOME) + lines.push(`codex catalog: ${index.threads.size} threads, ${index.projects.size} projects (source: ${index.source})`) + } catch (error) { + lines.push(`codex catalog: unavailable (${error.message})`) + } } catch (error) { lines.push(`codex sessions: scan failed (${error.message})`) } diff --git a/lib/attach-workspaces.mjs b/lib/attach-workspaces.mjs index faefc2f..8373209 100644 --- a/lib/attach-workspaces.mjs +++ b/lib/attach-workspaces.mjs @@ -3,14 +3,17 @@ * * dsh 的 workspace 归属是 cwd 精确匹配:每个会话按其持久化 header 的 * cwd 找 `workspaceRegistry` 中 path 相同的 workspace,不存在则创建。 - * workspace 标题带绝对路径(`basename (/abs/path)`),同名项目也能区分。 + * + * workspace 标题优先用 Codex 的项目名(`projects.name`,一个项目可以包含多个 + * 仓库根目录),拿不到项目名时退回目录名 —— **不再把绝对路径写进标题**: + * 路径既长又会随机器变化,同名项目靠目录名区分即可。 * * 服务不存在(headless 等未加载 workspace 插件的组合)时静默跳过。 */ import { normalizePersistence } from './persistence-facade.mjs' -/** 路径显示:home 用 `~` 前缀;超过 3 级只保留最后 3 级(保证同名可区分又简洁)。 */ +/** 路径显示:home 用 `~` 前缀;超过 3 级只保留最后 3 级(仅用于日志与提示)。 */ export function displayPath(cwd) { const home = process.env.HOME ?? '' if (cwd === home) return '~' @@ -23,21 +26,41 @@ export function displayPath(cwd) { return parts.length > 3 ? parts.slice(-3).join('/') : cwd } -/** workspace 显示标题:basename + 缩短路径(`名称 (~/最后几级)`)。 */ -export function workspaceTitle(cwd) { - const base = cwd.split('/').filter(Boolean).pop() ?? cwd - return `${base} (${displayPath(cwd)})` +/** 目录名(不区分分隔符,兼容 `\\?\D:\a\b` 这类 Windows 路径)。 */ +function baseName(cwd) { + const parts = String(cwd).replace(/\\/gu, '/').split('/').filter(Boolean) + return parts.pop() ?? cwd +} + +/** + * workspace 标题:Codex 项目名优先,否则目录名。绝不拼路径。 + * @param {string} cwd + * @param {(cwd: string) => (string | undefined)} [projectNameOf] + */ +export function workspaceTitle(cwd, projectNameOf) { + const project = typeof projectNameOf === 'function' ? projectNameOf(cwd) : undefined + if (typeof project === 'string' && project.trim().length > 0) return project.trim() + return baseName(cwd) +} + +/** 旧版本自动生成过的标题(`basename` 或 `basename (路径)`),可安全改写。 */ +function isGeneratedTitle(title, cwd) { + const base = baseName(cwd) + if (title === base) return true + return new RegExp(`^${base.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')} \\(`).test(title) } /** * 按 cwd 分组把会话 attach 到 workspace。 * @param ctx - 全局上下文(探测 workspaceRegistry)。 * @param sessions - [{id, cwd}],仅 cwd 非空的会话会被归位。 + * @param options.projectNameOf - cwd → Codex 项目名(用于工作区标题)。 * @returns 摘要行数组。 */ -export async function attachSessionsToWorkspaces(ctx, sessions) { +export async function attachSessionsToWorkspaces(ctx, sessions, options = {}) { const registry = ctx.get('workspaceRegistry') if (registry === undefined) return [] + const projectNameOf = options.projectNameOf const lines = [] const byCwd = new Map() for (const session of sessions) { @@ -54,17 +77,13 @@ export async function attachSessionsToWorkspaces(ctx, sessions) { lines.push(` [skipped] /: root directory skipped`) continue } + const title = workspaceTitle(cwd, projectNameOf) try { const existing = await registry.resolveByPath(cwd) - const workspace = existing ?? await registry.create(cwd, workspaceTitle(cwd)) - // 统一命名:默认命名的 workspace(title 就是 basename,无路径)补上 - // 绝对路径,同名项目也好区分;用户自定义过的标题不动。 - const base = cwd.split('/').filter(Boolean).pop() ?? cwd - // 默认命名(title == basename)或旧版生成标题(`basename (绝对路径)`) - // 都统一成新格式;用户自定义标题不动。 - const generated = new RegExp(`^${base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} \\(`) - if (workspace.title === base || generated.test(workspace.title)) { - await workspace.setTitle(workspaceTitle(cwd)) + const workspace = existing ?? await registry.create(cwd, title) + // 只改自动生成过的标题(目录名或旧版的「目录名 (路径)」),用户自定义的不动。 + if (existing !== undefined && isGeneratedTitle(workspace.title, cwd) && workspace.title !== title) { + await workspace.setTitle(title) } for (const id of ids) { try { @@ -74,7 +93,7 @@ export async function attachSessionsToWorkspaces(ctx, sessions) { } } const action = existing === undefined ? 'created' : 'reused' - lines.push(` [${action}] ${workspaceTitle(cwd)}: ${ids.length} sessions`) + lines.push(` [${action}] ${title}: ${ids.length} sessions`) } catch (error) { if (error?.code === 'ENOENT') { // 源机器的路径在本机不存在:会话照常导入,只是无法挂 workspace。 @@ -88,28 +107,22 @@ export async function attachSessionsToWorkspaces(ctx, sessions) { } /** - * 统一所有默认命名 workspace 的标题为 `basename (绝对路径)`。 - * 只改 title 恰为 basename 的(GUI 默认命名);用户自定义标题不动。 + * 把自动生成的工作区标题统一成「Codex 项目名 / 目录名」,去掉旧版标题里的路径。 * @param ctx - 全局上下文(workspaceRegistry)。 + * @param options.projectNameOf - cwd → Codex 项目名。 * @returns 改动的 workspace 数量。 */ -export async function unifyWorkspaceTitles(ctx) { +export async function unifyWorkspaceTitles(ctx, options = {}) { const registry = ctx.get('workspaceRegistry') if (registry === undefined) return 0 + const projectNameOf = options.projectNameOf let changed = 0 for (const workspace of registry.list()) { - const base = workspace.path.split('/').filter(Boolean).pop() ?? workspace.path - if (workspace.title === base) { - await workspace.setTitle(workspaceTitle(workspace.path)) - changed += 1 - } else { - // 旧版生成标题(`basename (绝对路径)`)也统一成新格式(`basename (~/…)`)。 - const generated = new RegExp(`^${base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')} \\(`) - if (generated.test(workspace.title)) { - await workspace.setTitle(workspaceTitle(workspace.path)) - changed += 1 - } - } + if (!isGeneratedTitle(workspace.title, workspace.path)) continue + const title = workspaceTitle(workspace.path, projectNameOf) + if (workspace.title === title) continue + await workspace.setTitle(title) + changed += 1 } return changed } diff --git a/lib/client.js b/lib/client.js index 91bedc9..f55947d 100644 --- a/lib/client.js +++ b/lib/client.js @@ -1043,9 +1043,9 @@ function labels(lang) { tipSubagent: '作为子代理展示仅用于归类组织;勾选后将作为独立 Codex 会话导出,不会与父会话合并', error: '无法读取目录。请完全退出并重新启动 dsh web(只刷新页面不够,后台插件不会更新)。', importedOk: '导入完成', - reloadHint: '正在刷新页面,新对话会出现在会话列表里(不用重启 dsh)。点「稍后」可取消自动刷新。', - reloadNow: '立即刷新', - reloadLater: '稍后', + reloadHint: '会话已写入。侧边栏列表由 dsh 自己维护,若没看到新对话,可点「刷新列表」(只重载页面,不重启 dsh)。', + reloadNow: '刷新列表', + reloadLater: '关闭', repairHintTitle: '导入对话报错?', repairHintBody: '若导入的对话在切换模型或压缩时报「token meter / no matching step/start event」等错误,可在任意新对话中执行 /repair-sessions --fix 一键修复(自动备份 .bak)。', } @@ -1126,9 +1126,9 @@ function labels(lang) { tipSubagent: 'Shown nested for organization; selected child exports separately, not merged.', error: 'Could not load catalog. Fully quit and restart dsh web (a page refresh does not reload the host plugin).', importedOk: 'Import finished', - reloadHint: 'Reloading so new chats show up in the session list (no dsh restart). Tap Later to cancel.', - reloadNow: 'Reload now', - reloadLater: 'Later', + reloadHint: 'The sessions are written. The sidebar list is owned by dsh — if the new chats are missing, use Refresh list (a page reload, no dsh restart).', + reloadNow: 'Refresh list', + reloadLater: 'Close', repairHintTitle: 'Imported chats erroring?', repairHintBody: 'If an imported conversation fails with "token meter / no matching step/start event" on model switch or compaction, run /repair-sessions --fix in any new chat to repair in place (a .bak backup is kept automatically).', } @@ -1294,7 +1294,6 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { const [busy, setBusy] = useState(false) const [confirmingExport, setConfirmingExport] = useState(false) const [done, setDone] = useState(false) - const reloadTimer = useRef(null) const load = async (includeSubagents, includeCodex) => { setError(null) @@ -1397,7 +1396,10 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { } setBusy(false) setDone(true) - reloadTimer.current = setTimeout(() => { window.location.reload() }, 2500) + // Refresh the plugin's own catalog so the rows flip to "imported". The + // sidebar list belongs to the Host, so it is not force-reloaded here — + // the result panel offers a reload for that. + void load(!hideSub, showCodex) } catch (e) { if (typeof runCommand === 'function') { const result = await runCommand('/import-codex --ids ' + ids.join(',') + (hideSub ? '' : ' --include-subagents')) @@ -1407,7 +1409,7 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { return } setDone(true) - reloadTimer.current = setTimeout(() => { window.location.reload() }, 2500) + void load(!hideSub, showCodex) } else { setBusy(false) setError(e?.message || t.error) @@ -1425,10 +1427,6 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { void executeImport(ids) } - useEffect(() => () => { - if (reloadTimer.current) clearTimeout(reloadTimer.current) - }, []) - const renderNodes = (nodes, depth) => nodes.map((n) => { const hasKids = (n.children || []).length > 0 const open = expanded[n.id] === true @@ -1572,10 +1570,9 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { isExport ? h('button', { type: 'button', style: styles.primaryBtn, onClick: onClose }, t.done) : [ - h('button', { key: 'later', type: 'button', style: styles.ghostBtn, onClick: () => { - if (reloadTimer.current) clearTimeout(reloadTimer.current) - onClose() - } }, t.reloadLater), + // Closing leaves the page untouched; the sidebar list refetches + // on its own next navigation, so a reload is only on request. + h('button', { key: 'later', type: 'button', style: styles.ghostBtn, onClick: onClose }, t.reloadLater), h('button', { key: 'now', type: 'button', diff --git a/lib/codex-index.mjs b/lib/codex-index.mjs new file mode 100644 index 0000000..6240b20 --- /dev/null +++ b/lib/codex-index.mjs @@ -0,0 +1,266 @@ +/** + * Codex's own catalog of threads and projects, read from `~/.codex/state_5.sqlite`. + * + * A rollout file only carries `session_meta` (id/cwd) and the conversation — no + * display name and no project. Codex Desktop keeps both in its SQLite state: + * + * threads.name the title the user sees (threads.title is often just + * the raw first message, e.g. "# Selected text: …") + * threads.cwd the rollout's directory, usually prefixed `\\?\` + * threads.project_id the project the thread belongs to (sparse) + * projects.name the project's display name + * project_roots.path every root directory of a project (a project groups + * several repos, so several cwds share one name) + * + * Reading this is what keeps imported titles and project names identical to + * Codex's sidebar. `~/.codex/session_index.jsonl` ({id, thread_name}) is the + * fallback for older builds that predate the SQLite state, and the rollout + * contents are the last resort. + * + * `node:sqlite` ships with Node 22.5+; on older runtimes this module degrades to + * the JSONL index instead of failing the import. + */ + +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' + +const cache = new Map() + +/** + * Normalize a Codex path for comparison: strip the Windows extended-length + * prefix, unify separators, drop trailing separators, case-fold (Windows + * paths are case-insensitive and Codex mixes cases freely). + * @param {unknown} value + * @returns {string} + */ +export function normalizePath(value) { + if (typeof value !== 'string') return '' + let path = value.trim() + if (path.startsWith('\\\\?\\')) path = path.slice(4) + path = path.replace(/\\/gu, '/') + if (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1) + return /^[a-z]:\//iu.test(path) ? path.toLowerCase() : path +} + +/** Last path segment, for cwds that belong to no Codex project. */ +export function baseName(value) { + const path = normalizePath(value) + if (path.length === 0) return '' + const parts = path.split('/').filter(Boolean) + return parts[parts.length - 1] ?? '' +} + +/** `{id, thread_name}` entries from ~/.codex/session_index.jsonl (older builds). */ +function readSessionIndex(codexHome) { + const titles = new Map() + const file = join(codexHome, 'session_index.jsonl') + if (!existsSync(file)) return titles + let content + try { + content = readFileSync(file, 'utf8') + } catch { + return titles + } + for (const line of content.split('\n')) { + const trimmed = line.trim() + if (trimmed.length === 0) continue + try { + const entry = JSON.parse(trimmed) + if (typeof entry?.id === 'string' && typeof entry?.thread_name === 'string' && entry.thread_name.length > 0) { + titles.set(entry.id, entry.thread_name) + } + } catch { + /* skip malformed line */ + } + } + return titles +} + +/** + * Classify a `threads.source` value. + * + * Codex stores either a plain origin string (`vscode`, `cli`, `exec`, …) for a + * user chat, or a JSON object for internal threads: + * {"subagent":{"other":"guardian"}} → automated review threads + * {"subagent":{"thread_spawn":{parent_thread_id,…}}} → spawned sub-agents + * + * Only the plain origins are user-facing chats; the sidebar hides the rest. + * @param {unknown} value + * @returns {{kind: 'user' | 'subagent' | 'guardian', parentThreadId?: string}} + */ +function describeOrigin(value) { + if (typeof value !== 'string' || value.length === 0) return { kind: 'user' } + const text = value.trim() + if (!text.startsWith('{')) return { kind: 'user' } + try { + const parsed = JSON.parse(text) + const subagent = parsed?.subagent + if (subagent === undefined) return { kind: 'user' } + if (subagent?.other === 'guardian') return { kind: 'guardian' } + const parent = subagent?.thread_spawn?.parent_thread_id + return { kind: 'subagent', ...(typeof parent === 'string' ? { parentThreadId: parent } : {}) } + } catch { + return { kind: 'user' } + } +} + +/** Read the SQLite state; returns undefined when unavailable (old Node, no file). */ +function readSqliteState(codexHome) { const file = join(codexHome, 'state_5.sqlite') + if (!existsSync(file)) return undefined + let sqlite + try { + // Imported lazily: Node < 22.5 has no node:sqlite and must not break import. + sqlite = process.getBuiltinModule?.('node:sqlite') + } catch { + sqlite = undefined + } + if (!sqlite?.DatabaseSync) return undefined + + let db + try { + db = new sqlite.DatabaseSync(file, { readOnly: true }) + } catch { + return undefined + } + try { + const threads = new Map() + for (const row of db.prepare('SELECT id, name, title, cwd, project_id, source FROM threads').all()) { + if (typeof row.id !== 'string') continue + const origin = describeOrigin(row.source) + threads.set(row.id, { + name: typeof row.name === 'string' ? row.name : undefined, + title: typeof row.title === 'string' ? row.title : undefined, + cwd: typeof row.cwd === 'string' ? row.cwd : undefined, + projectId: typeof row.project_id === 'string' ? row.project_id : undefined, + kind: origin.kind, + parentThreadId: origin.parentThreadId, + }) + } + const projects = new Map() + for (const row of db.prepare('SELECT id, name FROM projects').all()) { + if (typeof row.id !== 'string') continue + projects.set(row.id, { name: typeof row.name === 'string' ? row.name : '', roots: [] }) + } + for (const row of db.prepare('SELECT project_id, path FROM project_roots').all()) { + const project = projects.get(row.project_id) + if (project !== undefined && typeof row.path === 'string') project.roots.push(row.path) + } + return { threads, projects } + } catch { + return undefined + } finally { + try { + db.close() + } catch { + /* already closed */ + } + } +} + +/** + * Load (and cache) Codex's thread/project catalog for one codex home. + * @param {string} codexHome + * @returns {{ + * threads: Map, + * projects: Map, + * indexTitles: Map, + * source: 'sqlite' | 'jsonl' | 'none', + * }} + */ +export function loadCodexIndex(codexHome) { + const cached = cache.get(codexHome) + if (cached !== undefined) return cached + + const state = readSqliteState(codexHome) + const indexTitles = readSessionIndex(codexHome) + const entry = { + threads: state?.threads ?? new Map(), + projects: state?.projects ?? new Map(), + indexTitles, + source: state !== undefined ? 'sqlite' : (indexTitles.size > 0 ? 'jsonl' : 'none'), + } + cache.set(codexHome, entry) + return entry +} + +/** Drop the cached catalog (after a Codex rename, so the next read sees it). */ +export function invalidateCodexIndex(codexHome) { + if (codexHome === undefined) cache.clear() + else cache.delete(codexHome) +} + +/** + * Display title for one Codex thread, or undefined when Codex has no name for it. + * Prefers the SQLite `name` (what the sidebar shows), then the JSONL index, then + * `threads.title` (the string Codex itself falls back to). + */ +export function codexTitleOf(index, rawId) { + const thread = index.threads.get(rawId) + const name = thread?.name?.trim() + if (name) return name + const indexed = index.indexTitles.get(rawId)?.trim() + if (indexed) return indexed + const title = thread?.title?.trim() + return title ? title : undefined +} + +/** + * Codex's own view of what a thread is: a user chat, a spawned sub-agent, or an + * automated guardian review. `undefined` when Codex has no row for the id. + */ +export function codexOriginOf(index, rawId) { + const thread = index.threads.get(rawId) + if (thread === undefined) return undefined + return { kind: thread.kind ?? 'user', parentThreadId: thread.parentThreadId } +} + +/** Codex project name + matched root for a thread, when it belongs to one. */ +export function codexProjectOf(index, rawId, cwd) { const thread = index.threads.get(rawId) + if (thread?.projectId !== undefined) { + const project = index.projects.get(thread.projectId) + if (project !== undefined && project.name.length > 0) { + return { name: project.name, root: normalizePath(thread.cwd ?? cwd) } + } + } + const target = normalizePath(thread?.cwd ?? cwd) + if (target.length === 0) return undefined + // A project groups several roots (one monorepo per root); the longest root + // that contains the cwd wins so nested repos resolve to their own project. + let best + for (const [id, project] of index.projects) { + if (project.name.length === 0) continue + for (const root of project.roots) { + const normalized = normalizePath(root) + if (normalized.length === 0) continue + const matches = target === normalized || target.startsWith(`${normalized}/`) + if (!matches) continue + if (best === undefined || normalized.length > best.length) { + best = { id, name: project.name, root: normalized, length: normalized.length } + } + } + } + return best === undefined ? undefined : { name: best.name, root: best.root } +} + +/** + * Codex project name for a bare directory, by the longest matching project root. + * Used to name the DSH workspace a thread is attached to: Codex names the + * project (`zbwx-v2`), while the folder it holds is just one of its repos + * (`zbwx-frontend-v2`). + * @returns {string | undefined} + */ +export function codexProjectNameForPath(index, cwd) { + const target = normalizePath(cwd) + if (target.length === 0) return undefined + let best + for (const project of index.projects.values()) { + if (project.name.length === 0) continue + for (const root of project.roots) { + const normalized = normalizePath(root) + if (normalized.length === 0) continue + if (target !== normalized && !target.startsWith(`${normalized}/`)) continue + if (best === undefined || normalized.length > best.length) best = { name: project.name, length: normalized.length } + } + } + return best?.name +} diff --git a/lib/codex-reader.mjs b/lib/codex-reader.mjs index 2a0d85d..93b15ed 100644 --- a/lib/codex-reader.mjs +++ b/lib/codex-reader.mjs @@ -25,8 +25,12 @@ * fragments whose target attachment files are usually long gone. */ -import { readFileSync, readdirSync } from 'node:fs' +import { closeSync, createReadStream, openSync, readdirSync, readFileSync, readSync } from 'node:fs' +import { createInterface } from 'node:readline' +import { Readable } from 'node:stream' +import { createZstdDecompress } from 'node:zlib' import { join } from 'node:path' +import { decompressFrames } from './zstd-frame.mjs' /** Default codex session root. */ export function defaultCodexRoot() { @@ -49,7 +53,7 @@ export function listCodexSessions(root) { for (const entry of entries) { const path = join(dir, entry.name) if (entry.isDirectory()) walk(path) - else if (entry.isFile() && entry.name.endsWith('.jsonl') && entry.name.startsWith('rollout-')) files.push(path) + else if (entry.isFile() && (entry.name.endsWith('.jsonl') || entry.name.endsWith('.jsonl.zst')) && entry.name.startsWith('rollout-')) files.push(path) } } walk(root) @@ -63,8 +67,24 @@ export function listCodexSessions(root) { * CLI/desktop injections; the rest are provider plumbing. Blocks whose whole * trimmed text starts with one of these openers are dropped by * `normalizeContentBlock`. + * + * Two families matter most in practice: + * `` how codex hands an ACTIVATED SKILL to the model — the whole + * SKILL.md (frontmatter + body) arrives as a USER message, which + * used to show up verbatim in the imported transcript. + * `` / `` / `` / … + * desktop envelopes carrying JSON (opened pages, streaming block + * edits, goal continuations); they are tooling, not chat. + * `` and `` are deliberately + * KEPT: the first is real content, the second carries the user's own answer. + */ +const SYSTEM_BLOCK = /^<(environment_context|permissions instructions|turn_aborted|request_id|model|end_of_conversation|turn_id|recommended_plugins|skills_instructions|apps_instructions|plugins_instructions|collaboration_mode|multi_agent_mode|app-context|citation_entries|INSTRUCTIONS|skill|skills|guardian_tool_descriptions|codex_internal_context|node_repl_review_evidence|in-app-browser-context|external_browser_tabs|external_codex_apps_[a-z0-9_]*|heartbeat)(?:\s[^>]*)?>/u + +/** + * A codex placeholder that arrives as a user message when the incremental + * transcript delta is empty (``). */ -const SYSTEM_BLOCK = /^<(environment_context|permissions instructions|turn_aborted|request_id|model|end_of_conversation|turn_id|recommended_plugins|skills_instructions|apps_instructions|plugins_instructions|collaboration_mode|multi_agent_mode|app-context|citation_entries|INSTRUCTIONS)>/u +const TRANSCRIPT_PLACEHOLDER = /^/u /** AGENTS.md instructions wrapper (codex desktop): `# AGENTS.md instructions\n\n…`. */ const AGENTS_MD_BLOCK = /^# AGENTS\.md instructions/u @@ -86,65 +106,82 @@ export function capToolResult(text) { * usage; imports filter them out by default so the session list stays clean. */ export function isSubagentThread(header) { + // Guardian reviews are not sub-agents; don't filter them out. + if (header?.threadSource === 'guardian_review') return false return Boolean(header?.parentThreadId) } /** - * Map one response_item content block to a DSH content block (undefined = skip). + * True when the path is a zstd-compressed codex rollout (`rollout-….jsonl.zst`). + * Newer codex builds compress rollouts; the payload is a plain jsonl stream + * inside a standard zstd frame, so `node:zlib`'s zstd decoder can inflate it. */ -function flattenReasoningText(value) { - if (typeof value === 'string') return value - if (Array.isArray(value)) { - return value.map((part) => { - if (typeof part === 'string') return part - if (part && typeof part.text === 'string') return part.text - return '' - }).join('\n') - } - if (value && typeof value.text === 'string') return value.text - return '' +export function isCompressedSession(file) { + return typeof file === 'string' && file.endsWith('.zst') } -function normalizeContentBlock(block) { - switch (block?.type) { - case 'input_text': - case 'output_text': { - const text = block.text ?? '' - const trimmed = text.trim() - if (SYSTEM_BLOCK.test(trimmed) || AGENTS_MD_BLOCK.test(trimmed) || IMAGE_BLOCK.test(trimmed) || IMAGE_CLOSE.test(trimmed)) return undefined - return { type: 'text', text } - } - case 'reasoning': { - const text = flattenReasoningText(block.summary ?? block.text) - return text.length > 0 ? { type: 'reasoning', text } : undefined - } - case 'tool_use': { - const args = block.input === undefined ? '' : JSON.stringify(block.input) - return { - type: 'tool-call', - id: typeof block.id === 'string' ? block.id : `codex-call-${crypto.randomUUID()}`, - name: String(block.name ?? 'tool'), - arguments: args, +/** Zstd frame magic (`0xFD2FB528`, little-endian on disk). */ +const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]) + +/** + * Count the zstd frames in a file without reading all of it. + * + * A rollout is normally ONE frame, but codex appends to a rollout by writing a + * new frame, and node's zstd decoder stops at the end of the first frame (it + * does not stitch concatenated frames). Counting lets us pick a streamed decode + * for the normal case and a frame-by-frame decode when the tail would otherwise + * be dropped. + * @param {string} file + */ +function countFrames(file) { + const chunkSize = 1 << 20 + const chunk = Buffer.allocUnsafe(chunkSize + ZSTD_MAGIC.length) + const fd = openSync(file, 'r') + let count = 0 + let carry = 0 + try { + for (;;) { + const read = readSync(fd, chunk, carry, chunkSize, null) + if (read <= 0) break + const view = chunk.subarray(0, carry + read) + let at = view.indexOf(ZSTD_MAGIC) + while (at !== -1) { + count += 1 + at = view.indexOf(ZSTD_MAGIC, at + ZSTD_MAGIC.length) } + // Keep the last few bytes so a magic split across chunks is still found. + carry = Math.min(ZSTD_MAGIC.length - 1, view.length) + view.copy(chunk, 0, view.length - carry) } - default: - return undefined + } finally { + closeSync(fd) } + return count } /** - * Parse one codex rollout file into normalized messages. - * @returns { header: {id, createdAt, cwd}, messages: normalized[] } + * Inflate a rollout into a readable text stream. + * + * Single-frame files (the norm) are streamed, so a big rollout never has to sit + * in memory as a decoded string. Multi-frame files are decoded frame by frame + * because the streaming decoder would drop everything after the first frame. + */ +function openCodexSessionStream(file) { + if (!isCompressedSession(file)) return createReadStream(file) + if (countFrames(file) <= 1) return createReadStream(file).pipe(createZstdDecompress()) + return Readable.from([decompressFrames(readFileSync(file))]) +} + +/** + * Read session file asynchronously using stream. + * @param {string} file */ -export function parseCodexSession(file) { +export async function parseCodexSession(file) { const header = { id: undefined, createdAt: undefined, cwd: undefined } const messages = [] - let lastUserText - // assistant-side blocks accumulated from standalone response_items - // (custom_tool_call/_output, reasoning) and flushed as one assistant - // message right before the next `message` event. let pending = [] let pendingTime = 0 + let lastUserText = '' const flushPending = () => { if (pending.length === 0) return @@ -152,7 +189,12 @@ export function parseCodexSession(file) { pending = [] } - for (const rawLine of readFileSync(file, 'utf8').split('\n')) { + const rl = createInterface({ + input: openCodexSessionStream(file), + crlfDelay: Infinity + }) + + for await (const rawLine of rl) { const line = rawLine.trim() if (line.length === 0) continue let event @@ -168,15 +210,31 @@ export function parseCodexSession(file) { const payload = event.payload ?? {} header.id = payload.id header.cwd = payload.cwd - // Some rollouts carry several session_meta lines (thread fork / resume); - // a parent_thread_id on ANY of them marks a sub-agent thread. if (payload.parent_thread_id !== undefined) header.parentThreadId = payload.parent_thread_id if (payload.agent_nickname !== undefined) header.agentNickname = payload.agent_nickname + if (payload.thread_source !== undefined) header.threadSource = payload.thread_source const created = Date.parse(payload.timestamp) header.createdAt = Number.isNaN(created) ? undefined : created continue } - if (event.type !== 'response_item') continue + if (event.type !== 'response_item') { + // Codex keeps goal mode in `event_msg` snapshots: every goal mutation + // appends `thread_goal_updated` with the WHOLE goal, so the last one wins. + if (event.type === 'event_msg' && event.payload?.type === 'thread_goal_updated') { + const goal = event.payload.goal + if (goal && typeof goal.objective === 'string' && goal.objective.trim().length > 0) { + header.goal = { + objective: goal.objective.trim(), + status: typeof goal.status === 'string' ? goal.status : 'active', + createdAt: typeof goal.createdAt === 'number' ? goal.createdAt * 1000 : undefined, + updatedAt: typeof goal.updatedAt === 'number' ? goal.updatedAt * 1000 : undefined, + tokensUsed: typeof goal.tokensUsed === 'number' ? goal.tokensUsed : undefined, + timeUsedSeconds: typeof goal.timeUsedSeconds === 'number' ? goal.timeUsedSeconds : undefined, + } + } + } + continue + } const payload = event.payload ?? {} const type = payload.type @@ -221,7 +279,6 @@ export function parseCodexSession(file) { if (mapped !== undefined) blocks.push(mapped) } if (role === 'user') { - // The same prompt is echoed per turn; collapse consecutive duplicates. const text = blocks.filter(block => block.type === 'text').map(block => block.text).join('\n') if (text === lastUserText && blocks.every(block => block.type === 'text')) continue lastUserText = text @@ -232,3 +289,54 @@ export function parseCodexSession(file) { flushPending() return { header, messages } } + +/** + * Map one response_item content block to a DSH content block (undefined = skip). + */ +function flattenReasoningText(value) { + if (typeof value === 'string') return value + if (Array.isArray(value)) { + return value.map((part) => { + if (typeof part === 'string') return part + if (part && typeof part.text === 'string') return part.text + return '' + }).join('\n') + } + if (value && typeof value.text === 'string') return value.text + return '' +} + +function normalizeContentBlock(block) { + switch (block?.type) { + case 'input_text': + case 'output_text': { + const text = block.text ?? '' + const trimmed = text.trim() + if (SYSTEM_BLOCK.test(trimmed) || TRANSCRIPT_PLACEHOLDER.test(trimmed) || AGENTS_MD_BLOCK.test(trimmed) || IMAGE_BLOCK.test(trimmed) || IMAGE_CLOSE.test(trimmed)) return undefined + return { type: 'text', text } + } + case 'reasoning': { + const text = flattenReasoningText(block.summary ?? block.text) + return text.length > 0 ? { type: 'reasoning', text } : undefined + } + case 'tool_use': { + const args = block.input === undefined ? '' : JSON.stringify(block.input) + return { + type: 'tool-call', + id: typeof block.id === 'string' ? block.id : `codex-call-${crypto.randomUUID()}`, + name: String(block.name ?? 'tool'), + arguments: args, + } + } + default: + return undefined + } +} + +/** + * Parse one codex rollout file into normalized messages. + * @returns { header: {id, createdAt, cwd}, messages: normalized[] } + */ + +// Old sync version removed + diff --git a/lib/export-codex.js b/lib/export-codex.js index b2fb288..5435e20 100644 --- a/lib/export-codex.js +++ b/lib/export-codex.js @@ -88,6 +88,58 @@ export function dshEventsToCodexMessages(events) { return out } +/** + * The session's goal mode, as the last `goal/change` in its log. + * + * DSH derives goals from those events (`ctx.goals` is "backed exclusively by the + * owning session log"), so the last one is the live state. + * @returns {{objective: string, phase: string, createdAt?: number, updatedAt?: number} | undefined} + */ +export function goalOf(events) { + const evts = events ?? [] + for (let i = evts.length - 1; i >= 0; i--) { + const event = evts[i] + if (event?.type !== 'goal/change') continue + const goal = event.data?.goal + if (!goal || typeof goal.objective !== 'string' || goal.objective.trim().length === 0) continue + return { + objective: goal.objective.trim(), + phase: typeof goal.phase === 'string' ? goal.phase : 'active', + createdAt: typeof event.data.createdAt === 'number' ? event.data.createdAt : event.time, + updatedAt: typeof event.data.updatedAt === 'number' ? event.data.updatedAt : event.time, + } + } + return undefined +} + +/** + * Codex's goal snapshot for a DSH goal, or undefined when Codex has no status + * for it. Only `active` and `paused` are known to Codex (its rollout statuses), + * so a blocked goal is exported as paused and a completed one is not exported — + * writing an unknown enum into a rollout risks Codex refusing the file. + */ +export function codexGoalSnapshot(goal, threadId) { + if (goal === undefined) return undefined + const status = goal.phase === 'active' + ? 'active' + : goal.phase === 'paused' || goal.phase === 'blocked' + ? 'paused' + : undefined + if (status === undefined) return undefined + return { + threadId, + goal: { + threadId, + objective: goal.objective, + status, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: Math.floor((goal.createdAt ?? Date.now()) / 1000), + updatedAt: Math.floor((goal.updatedAt ?? Date.now()) / 1000), + }, + } +} + function line(ordinal, type, payload, timestamp) { return JSON.stringify({ timestamp, ordinal, type, payload }) } @@ -95,7 +147,7 @@ function line(ordinal, type, payload, timestamp) { /** * Build JSONL text for one exported session. */ -export function buildRolloutJsonl({ uuid, cwd, createdAt, messages }) { +export function buildRolloutJsonl({ uuid, cwd, createdAt, messages, goal }) { const ts0 = iso(createdAt) const lines = [] let ord = 0 @@ -171,6 +223,12 @@ export function buildRolloutJsonl({ uuid, cwd, createdAt, messages }) { }, ts)) } } + // Goal mode travels as an `event_msg` snapshot, exactly like Codex writes it + // when the goal changes (`thread_goal_updated`); the last one wins on read. + const goalSnapshot = codexGoalSnapshot(goal, uuid) + if (goalSnapshot !== undefined) { + lines.push(line(ord++, 'event_msg', { type: 'thread_goal_updated', ...goalSnapshot }, bump())) + } return lines.join('\n') + '\n' } @@ -258,7 +316,7 @@ export function extractCodexSignatures(messages) { * @param {string} codexHome * @returns {Set} */ -export function getKnownCodexWorkspaces(codexHome) { +export async function getKnownCodexWorkspaces(codexHome) { const cwds = new Set() const db = join(codexHome, 'state_5.sqlite') if (existsSync(db)) { @@ -275,7 +333,7 @@ export function getKnownCodexWorkspaces(codexHome) { try { for (const file of listCodexSessions(sessionsDir)) { try { - const parsed = parseCodexSession(file) + const parsed = await parseCodexSession(file) if (parsed?.header?.cwd) cwds.add(String(parsed.header.cwd).trim()) } catch {} } @@ -287,7 +345,7 @@ export function getKnownCodexWorkspaces(codexHome) { /** * Scan codexHome for session source files and return a map of rawId -> parsed codex session info. */ -export function buildCodexSourceMap(codexHome) { +export async function buildCodexSourceMap(codexHome) { const map = new Map() const roots = [ join(codexHome, 'sessions'), @@ -297,7 +355,7 @@ export function buildCodexSourceMap(codexHome) { if (!existsSync(root)) continue for (const file of listCodexSessions(root)) { try { - const parsed = parseCodexSession(file) + const parsed = await parseCodexSession(file) if (parsed?.header?.id !== undefined) { const rawId = String(parsed.header.id) // Keep the latest or existing @@ -413,7 +471,7 @@ export async function listExportCatalog(persistence, options = {}, codexHome = j const metas = (await persistence.list()) || [] let codexSourceMap = null if (includeCodex) { - codexSourceMap = buildCodexSourceMap(codexHome) + codexSourceMap = await buildCodexSourceMap(codexHome) } const flatNodes = [] @@ -515,7 +573,7 @@ export async function listExportCatalog(persistence, options = {}, codexHome = j } } - const knownCodexCwds = getKnownCodexWorkspaces(codexHome) + const knownCodexCwds = await getKnownCodexWorkspaces(codexHome) const projects = [] for (const [cwd, sessions] of groups) { @@ -551,14 +609,14 @@ export async function exportToCodex(persistence, options = {}, codexHome = join( let empty = 0 let codexSourceMap = null - const getCodexSourceMap = () => { + const getCodexSourceMap = async () => { if (!codexSourceMap) { - codexSourceMap = buildCodexSourceMap(codexHome) + codexSourceMap = await buildCodexSourceMap(codexHome) } return codexSourceMap } - const knownCodexCwds = getKnownCodexWorkspaces(codexHome) + const knownCodexCwds = await getKnownCodexWorkspaces(codexHome) for (const meta of metas) { if (want && !want.has(meta.id)) continue @@ -580,7 +638,7 @@ export async function exportToCodex(persistence, options = {}, codexHome = join( continue } const rawId = String(meta.id).replace(/^codex-/u, '') - const sourceInfo = getCodexSourceMap().get(rawId) + const sourceInfo = (await getCodexSourceMap()).get(rawId) const comparison = compareDshWithCodexSource(events, sourceInfo) if (comparison.dshUpdated) { isCodexExportAllowed = true @@ -614,6 +672,7 @@ export async function exportToCodex(persistence, options = {}, codexHome = join( cwd: meta.cwd, createdAt, messages, + goal: goalOf(events), }) const copyNote = isCodex ? ' (new copy; original Codex thread not overwritten)' : '' if (dryRun) { diff --git a/lib/import-service.js b/lib/import-service.js index 994082f..921c646 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -3,12 +3,12 @@ * * Adapted from dsh-import-agents (c) Chang-Tong / dongzhangust, MIT, with two * field-hardened fixes: - * 1. SIZE GUARD — rollout files larger than `maxSessionBytes` (default - * 256 MiB) are skipped with a note. The stock reader does - * `readFileSync(file, 'utf8')`, and a single file >512 MiB makes Node - * throw "Cannot create a string longer than 0x1fffffe8 characters", - * which aborted the whole import-all (hit in the wild with a 679 MB - * Surge-config session). + * 1. SIZE GUARD — rollouts above `maxSessionBytes` are still skipped with a + * note, but the default is now 2 GiB: the reader streams JSONL line by line + * (it used to `readFileSync` the whole file, which made Node throw + * "Cannot create a string longer than 0x1fffffe8 characters" and abort the + * whole import-all). A 1.2 GB rollout parses in a few seconds, so the old + * 256 MiB ceiling only hid real conversations. * 2. WORKSPACE GAP — after a batch import, every previously-imported * session is re-attached to its cwd workspace, so a partial first run * (e.g. /import-codex --limit 20) can never leave later sessions @@ -19,21 +19,131 @@ * * @module dsh-codex-sync/import-service */ -import { statSync } from 'node:fs' +import { readFileSync, statSync } from 'node:fs' import { join } from 'node:path' import { listCodexSessions, parseCodexSession, isSubagentThread } from './codex-reader.mjs' +import { loadCodexIndex, codexTitleOf, codexProjectOf, codexProjectNameForPath, codexOriginOf, baseName } from './codex-index.mjs' import { buildDshEvents, deriveImportTitle } from './convert.mjs' import { migrateToCurrent } from './session-migrate.mjs' import { normalizePersistence } from './persistence-facade.mjs' import { attachSessionsToWorkspaces, listImportedSessions } from './attach-workspaces.mjs' -const DEFAULT_MAX_SESSION_BYTES = 256 * 1024 * 1024 +export const DEFAULT_MAX_SESSION_BYTES = 2 * 1024 * 1024 * 1024 -function projectLabel(cwd) { - if (typeof cwd !== 'string' || cwd.length === 0) return '(no project)' - const parts = cwd.replace(/\\/gu, '/').split('/').filter(Boolean) - return parts[parts.length - 1] || cwd +/** + * Rewrite the JSONL/db title helpers into one index-backed lookup. + */ +function resolveImportTitle(codexHome, rawId, headerTitle, messages) { + const named = codexTitleOf(loadCodexIndex(codexHome), rawId) + if (typeof named === 'string' && named.length > 0) return named + return deriveImportTitle(headerTitle, messages, 'codex') +} + +/** + * Replay a Codex goal as the `goal/change` events DSH's goal service reads. + * + * Codex stores one snapshot per mutation (`thread_goal_updated`), so the import + * only needs the final state: `create` (always, phase active because that is how + * DSH accepts a new goal) followed by the transition that reaches the recorded + * status — `pause`, `resume`, `complete`. `blocked` maps to `block`. + * + * `blocked`/`complete` keep their semantic; unknown Codex statuses are treated + * as active so an unfinished goal is never silently dropped. + * @param {string} sessionId + * @param {{objective: string, status: string, createdAt?: number, updatedAt?: number}} | undefined goal + * @param {number} time - fallback timestamps (ms) + * @returns {Array} goal/change events (seq assigned by the caller) + */ +function codexGoalEvents(sessionId, goal, time) { + if (goal === undefined) return [] + const objective = String(goal.objective ?? '').trim() + if (objective.length === 0) return [] + const createdAt = goal.createdAt ?? time + const updatedAt = goal.updatedAt ?? time + const id = `goal-${sessionId}` + const base = { + id, + revision: 1, + objective, + phase: 'active', + maxGoalRounds: 256, + } + const events = [{ + type: 'goal/change', + time: createdAt, + data: { kind: 'goal/change', version: 1, operation: 'create', goal: { ...base }, roundsStarted: 0, createdAt, updatedAt: createdAt }, + }] + const status = String(goal.status ?? 'active').toLowerCase() + const transition = status === 'paused' + ? { operation: 'pause', phase: 'paused' } + : status === 'complete' || status === 'completed' + ? { operation: 'complete', phase: 'complete' } + : status === 'blocked' + ? { operation: 'block', phase: 'blocked' } + : undefined + if (transition === undefined) return events + events.push({ + type: 'goal/change', + time: updatedAt, + data: { + kind: 'goal/change', + version: 1, + operation: transition.operation, + goal: { + ...base, + revision: 2, + phase: transition.phase, + ...(transition.phase === 'blocked' + ? { blockedReason: { code: 'imported', message: 'Codex 侧目标处于 blocked 状态(导入时保留)' } } + : {}), + }, + roundsStarted: 0, + createdAt, + updatedAt, + }, + }) + return events +} + +/** + * Goal events to append to an ALREADY imported session so it follows a Codex + * goal change: no goal stored yet → the full `create` (+ transition); stored + * phase already matches → nothing; otherwise only the transition. + * + * @param {Array} oldEvents - what the DSH session already holds + * @param {object|undefined} goal - the Codex goal snapshot + * @param {number} time - fallback timestamp (ms) + */ +function codexGoalSyncEvents(oldEvents, goal, time) { + if (goal === undefined) return [] + const stored = [...oldEvents].reverse().find((event) => event?.type === 'goal/change') + if (stored === undefined) return codexGoalEvents('', goal, time).map((event) => { + // id is rewritten by the caller (needs the session id) + return { ...event, data: { ...event.data, goal: { ...event.data.goal } } } + }) + const storedPhase = stored.data?.goal?.phase + const full = codexGoalEvents('', goal, time) + const status = String(goal.status ?? 'active').toLowerCase() + const wanted = status === 'paused' + ? 'paused' + : status === 'complete' || status === 'completed' + ? 'complete' + : status === 'blocked' + ? 'blocked' + : 'active' + if (storedPhase === wanted) return [] + const revision = (typeof stored.data?.goal?.revision === 'number' ? stored.data.goal.revision : 1) + 1 + const transition = full[full.length - 1] + return [{ + ...transition, + data: { ...transition.data, goal: { ...transition.data.goal, revision } }, + }] +} + +/** Project label for one thread: Codex's project name, else the cwd's folder. */ +function folderLabel(cwd) { if (typeof cwd !== 'string' || cwd.length === 0) return '(no project)' + return baseName(cwd) || cwd } function sortNewThenImported(nodes) { @@ -210,6 +320,7 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo const dryRun = options.dryRun === true const existing = new Set((await persistence.list()).map((meta) => meta.id)) const lines = [] + const index = loadCodexIndex(codexHome) if (dryRun) lines.push('[codex] dry-run: no sessions will be written') // ── collect candidates (with size guard) ────────────────────────────────── @@ -231,7 +342,7 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo } let parsed try { - parsed = parseCodexSession(file) + parsed = await parseCodexSession(file) } catch { unreadable += 1 continue @@ -296,9 +407,15 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo } const events = buildDshEvents(messages, { toolEvents: true, - title: deriveImportTitle(candidate.parsed.header.title, messages, 'codex'), + title: resolveImportTitle(codexHome, candidate.parsed.header.id, candidate.parsed.header.title, messages), titlePinned: true, }).map((event, seq) => ({ ...event, seq })) + // Carry Codex's goal mode across: DSH's `ctx.goals` is derived purely from + // `goal/change` events in the session log, so replaying the goal is what + // makes an unfinished Codex goal active here. + const lastMessageTime = messages.length > 0 ? (messages[messages.length - 1].time ?? Date.now()) : Date.now() + events.push(...codexGoalEvents(candidate.id, candidate.parsed.header.goal, lastMessageTime)) + events.forEach((event, seq) => { event.seq = seq }) // DSH 0.9.0 session-persistence now *writes* only the current (v3) format: // encodeCurrentHeader throws "encodeCurrent requires Session format v3" for a // v0 header, so the importer must migrate the imported v0 header + events @@ -332,18 +449,20 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo continue } const suffix = diffImportEvents(oldEvents, currentEvents) - if (suffix.length === 0) { + const goalTail = codexGoalSyncEvents(oldEvents, candidate.parsed.header.goal, lastMessageTime) + .map((event, i) => ({ ...event, seq: (suffix[suffix.length - 1]?.seq ?? oldEvents[oldEvents.length - 1]?.seq ?? 0) + 1 + i })) + if (suffix.length === 0 && goalTail.length === 0) { skipped += 1 continue } if (dryRun) { updated += 1 - lines.push(` [would-update] ${candidate.id} +${suffix.length} events`) + lines.push(` [would-update] ${candidate.id} +${suffix.length + goalTail.length} events`) continue } - await persistence.append(candidate.id, suffix) + await persistence.append(candidate.id, [...suffix, ...goalTail]) updated += 1 - lines.push(` [updated] ${candidate.id} +${suffix.length} events`) + lines.push(` [updated] ${candidate.id} +${suffix.length + goalTail.length} events`) continue } if (dryRun) { @@ -361,12 +480,12 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo lines.push(` [hint] ${skippedSubagent} codex 子代理线程已过滤(默认,避免会话列表塞满); 需要时用 /import-codex --include-subagents 或配置 importSubagents: true`) } if (skippedBig > 0) { - lines.push(` [hint] ${skippedBig} file(s) > ${Math.round(maxBytes / 1024 / 1024)} MiB were skipped to avoid the Node string-limit crash; raise config maxSessionBytes to force them, or move them out of ~/.codex/sessions`) + lines.push(` [hint] ${skippedBig} file(s) > ${Math.round(maxBytes / 1024 / 1024)} MiB were skipped; raise config maxSessionBytes to include them`) } // ── workspace attach: the whole imported set, not just this batch ───────── if (!dryRun) { - const attached = await attachAllImported(ctx, persistence) + const attached = await attachAllImported(ctx, persistence, codexHome) lines.push(...attached) } return lines @@ -385,6 +504,7 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j const flat = [] let skippedBig = 0 let unreadable = 0 + const index = loadCodexIndex(codexHome) for (const file of listCodexSessions(join(codexHome, 'sessions'))) { let size try { @@ -399,7 +519,7 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j } let parsed try { - parsed = parseCodexSession(file) + parsed = await parseCodexSession(file) } catch { unreadable += 1 continue @@ -407,22 +527,31 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j if (parsed.header.id === undefined) continue const rawId = String(parsed.header.id) const id = `codex-${rawId}` - const title = deriveImportTitle(parsed.header.title, parsed.messages, 'codex') ?? id + const title = resolveImportTitle(codexHome, rawId, parsed.header.title, parsed.messages) ?? id const lastTime = parsed.messages.length > 0 ? (parsed.messages[parsed.messages.length - 1].time ?? 0) : 0 + // Codex's own `threads.source` is authoritative: `guardian` rows are + // automated review threads and `thread_spawn` rows are sub-agents, neither + // of which the Codex sidebar shows as chats. + const origin = codexOriginOf(index, rawId) + const isInternal = origin !== undefined ? origin.kind !== 'user' : isSubagentThread(parsed.header) + const parentRawId = parsed.header.parentThreadId + ? String(parsed.header.parentThreadId) + : (origin?.parentThreadId ?? null) flat.push({ rawId, id, - parentRawId: parsed.header.parentThreadId ? String(parsed.header.parentThreadId) : null, + parentRawId, cwd: typeof parsed.header.cwd === 'string' ? parsed.header.cwd : null, createdAt: parsed.header.createdAt ?? 0, lastTime, title, - isSubagent: isSubagentThread(parsed.header), + isSubagent: isInternal, imported: existing.has(id), stale: false, children: [], }) } + for (const node of flat) { if (!node.imported || typeof persistence.inspect !== 'function') continue try { @@ -445,14 +574,21 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j const groups = new Map() for (const node of roots) { - const key = node.cwd ?? '' - if (!groups.has(key)) groups.set(key, []) - groups.get(key).push(node) + // Codex groups by PROJECT, and one project owns several roots, so every + // thread whose cwd lives under a project root must land in the same group — + // grouping by raw cwd would split e.g. zbwx-v2 into one group per repo. + // Threads Codex knows no project for fall back to their folder name; the + // label is the group key so equally-named groups never appear twice. + const project = codexProjectOf(index, node.rawId, node.cwd ?? undefined) + const label = project?.name ?? folderLabel(node.cwd) + const key = label.toLowerCase() + if (!groups.has(key)) groups.set(key, { label, cwd: node.cwd, sessions: [] }) + groups.get(key).sessions.push(node) } const projects = [] - for (const [cwd, sessions] of groups) { - const sorted = sortNewThenImported(sessions) + for (const group of groups.values()) { + const sorted = sortNewThenImported(group.sessions) let latest = 0 const walk = (nodes) => { for (const n of nodes) { @@ -461,9 +597,10 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j } } walk(sorted) + const cwd = group.cwd projects.push({ cwd: cwd.length > 0 ? cwd : null, - label: projectLabel(cwd), + label: group.label, sessions: sorted, latest, }) @@ -478,9 +615,12 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j * /attach-workspaces command and the post-import attach step above. * @returns {Promise} summary lines ('' when workspace service absent). */ -export async function attachAllImported(ctx, persistence) { +export async function attachAllImported(ctx, persistence, codexHome = join(process.env.HOME ?? '', '.codex')) { const registry = ctx.get('workspaceRegistry') if (registry === undefined || persistence === undefined) return [] const sessions = await listImportedSessions(persistence) - return attachSessionsToWorkspaces(ctx, sessions) + const index = loadCodexIndex(codexHome) + return attachSessionsToWorkspaces(ctx, sessions, { + projectNameOf: (cwd) => codexProjectNameForPath(index, cwd), + }) } diff --git a/lib/index.js b/lib/index.js index c532b48..0b56a36 100644 --- a/lib/index.js +++ b/lib/index.js @@ -34,6 +34,8 @@ import { join } from 'node:path' import { bridgeInstructionsSection, bridgeConfigSection } from './bridge.js' import { registerCodexSkillProvider, registerPluginSkillProvider } from './skill-provider.js' import { importCodex, attachAllImported, listImportCatalog } from './import-service.js' +import { unifyWorkspaceTitles } from './attach-workspaces.mjs' +import { codexProjectNameForPath, loadCodexIndex } from './codex-index.mjs' import { exportToCodex, listExportCatalog } from './export-codex.js' import { repairSessionStore } from './session-repair.mjs' import { mountMcpServers, startMcpMirror, formatMcpStatus, parseCodexMcpServers, hardDenyNames } from './mcp.js' @@ -180,6 +182,15 @@ export function apply(ctx, config = {}) { return { kind: 'success', text: lines.join('\n') } } + /** Rename auto-generated workspace titles to their Codex project name. */ + const retitleWorkspaces = async (context, home) => { + const changed = await unifyWorkspaceTitles(context, { + projectNameOf: (cwd) => codexProjectNameForPath(loadCodexIndex(home), cwd), + }) + if (changed > 0) context.logger?.info?.(`dsh-codex-sync: renamed ${changed} workspace title(s)`) + return changed + } + /** * Command handlers receive a CommandInvocation object (`{ rawInput, … }`) * in current dsh; older builds passed the raw string. Normalize both. @@ -327,7 +338,7 @@ export function apply(ctx, config = {}) { if (persistence === undefined) { return { kind: 'success', text: 'sessionPersistence 服务未加载' } } - const lines = await attachAllImported(ctx, persistence) + const lines = await attachAllImported(ctx, persistence, codexHome) return { kind: 'success', text: lines.length === 0 ? '没有可归位的会话(或 workspace 服务未加载)' : lines.join('\n') } }, }) @@ -487,10 +498,24 @@ export function apply(ctx, config = {}) { }, }) + // ── workspace titles: `Codex project name`, never the path ─────────────── + // Earlier builds titled attached workspaces `basename (path)`. Rename the + // auto-generated ones once at startup so existing imports pick up the Codex + // project name (e.g. `zbwx-frontend-v2 (~/…/zbwx-frontend-v2)` → `zbwx-v2`). + // Custom titles are left untouched. + let retitled = false + ctx.effect(() => ctx.on('agent/created', ({ source }) => { + if (retitled || source !== 'startup') return + retitled = true + void retitleWorkspaces(ctx, codexHome).catch((error) => { + ctx.logger?.warn?.(`dsh-codex-sync: workspace title refresh failed: ${error?.message ?? error}`) + }) + }), 'codex-sync.workspace-titles()') + // ── autoImport: run once at the first startup session ──────────────────── if (store.get()) { let ran = false - ctx.effect(() => ctx.on('agent/session-start', ({ source }) => { + ctx.effect(() => ctx.on('agent/created', ({ source }) => { if (ran || source !== 'startup') return ran = true void runImport().then((result) => { diff --git a/lib/session-migrate.mjs b/lib/session-migrate.mjs index 3218624..7406dc7 100644 --- a/lib/session-migrate.mjs +++ b/lib/session-migrate.mjs @@ -73,11 +73,28 @@ function chainFrom(r) { function loadChain() { const candidates = [] // 1. Derive from the running electron binary (…/DSH Desktop.app/Contents/MacOS/…) - const execDir = process.execPath ? join(dirname(process.execPath), '..') : '' + const execDir = process.execPath ? dirname(process.execPath) : '' if (execDir) { - candidates.push(join(execDir, 'Resources', 'app', 'node_modules')) + candidates.push(join(execDir, '..', 'Resources', 'app', 'node_modules')) } - // 2. Standard macOS install, asar + unpacked layouts, and env/profile fallbacks. + // 2. Electron app layout on every platform. The Windows desktop build keeps + // the packages inside app.asar under a `dsh/` root, which only the + // Electron runtime can read — process.resourcesPath is the supported way + // to find it, and the sibling `app.asar.unpacked` is the plain-node case. + const resources = [] + if (typeof process.resourcesPath === 'string' && process.resourcesPath.length > 0) resources.push(process.resourcesPath) + if (execDir) { + resources.push(join(execDir, 'resources')) + resources.push(join(execDir, '..', 'Resources')) + } + for (const base of resources) { + candidates.push(join(base, 'app.asar', 'dsh', 'node_modules')) + candidates.push(join(base, 'app.asar', 'node_modules')) + candidates.push(join(base, 'app.asar.unpacked', 'dsh', 'node_modules')) + candidates.push(join(base, 'app', 'dsh', 'node_modules')) + candidates.push(join(base, 'app', 'node_modules')) + } + // 3. Standard macOS install, asar + unpacked layouts, and env/profile fallbacks. candidates.push('/Applications/DSH Desktop.app/Contents/Resources/app/node_modules') candidates.push('/Applications/DSH Desktop.app/Contents/Resources/app.asar.unpacked/node_modules') candidates.push(process.env.DSH_CHECKOUT || '') @@ -89,12 +106,15 @@ function loadChain() { const stages = chainFrom(r) if (stages.length > best.length) best = stages } - // 3. The plugin's own node_modules: devDependencies ship the real packages, + // 4. The plugin's own node_modules: devDependencies ship the real packages, // so tests exercise the true migration path without a DSH install. const local = chainFrom(createRequire(import.meta.url)) if (local.length > best.length) best = local if (best.length === 0) { - throw new Error('cannot resolve @deepseek-ai/dsh-session-format-* migration packages') + throw new Error( + 'cannot resolve @deepseek-ai/dsh-session-format-* migration packages ' + + `(searched: ${candidates.filter(Boolean).join(', ')})`, + ) } return best } diff --git a/lib/zstd-frame.mjs b/lib/zstd-frame.mjs index 786f3a6..bbe3062 100644 --- a/lib/zstd-frame.mjs +++ b/lib/zstd-frame.mjs @@ -2,6 +2,9 @@ import * as zlib from 'node:zlib' import { execFileSync } from 'node:child_process' +/** Zstd frame magic (`0xFD2FB528`, little-endian on disk). */ +const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]) + export function compressChecksummedFrame(input) { if (typeof zlib.zstdCompressSync === 'function') { return zlib.zstdCompressSync(input, { @@ -13,3 +16,41 @@ export function compressChecksummedFrame(input) { maxBuffer: Math.max(1 << 20, input.length * 2), }) } + +/** + * Byte offsets of every Zstandard frame start in `input`. + * + * Files here are routinely a CONCATENATION of independent frames (DSH's session + * store writes a header frame plus one frame per append), and node's zstd + * decoder stops at the end of the first frame instead of stitching them. The + * offsets let callers decode every frame. + */ +export function frameOffsets(input) { + const offsets = [] + let at = input.indexOf(ZSTD_MAGIC) + while (at !== -1) { + offsets.push(at) + at = input.indexOf(ZSTD_MAGIC, at + ZSTD_MAGIC.length) + } + return offsets +} + +/** + * Decompress a buffer that holds one or more concatenated Zstandard frames. + * @param {Buffer} input + * @returns {Buffer} + */ +export function decompressFrames(input) { + const decode = (chunk) => (typeof zlib.zstdDecompressSync === 'function' + ? zlib.zstdDecompressSync(chunk) + : execFileSync('zstd', ['--quiet', '--decompress', '--stdout'], { input: chunk })) + + const offsets = frameOffsets(input) + if (offsets.length <= 1) return decode(input) + const parts = [] + for (let i = 0; i < offsets.length; i += 1) { + const end = i + 1 < offsets.length ? offsets[i + 1] : input.length + parts.push(decode(input.subarray(offsets[i], end))) + } + return Buffer.concat(parts) +} diff --git a/package.json b/package.json index ff2f500..4a77fe0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.6.2", + "version": "1.9.0", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", @@ -72,7 +72,7 @@ }, "peerDependencies": { "@deepseek-ai/cordis": "^4.0.1", - "@deepseek-ai/dsh-mcp-client": "^0.0.1-rc.1 || 0.2.0-rc.2" + "@deepseek-ai/dsh-mcp-client": "^0.0.1-rc.1 || 0.2.0-rc.2 || 0.2.2-rc.1" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-mcp-client": { diff --git a/scripts/extract-asar-subtree.mjs b/scripts/extract-asar-subtree.mjs new file mode 100644 index 0000000..49eb54a --- /dev/null +++ b/scripts/extract-asar-subtree.mjs @@ -0,0 +1,52 @@ +#!/usr/bin/env node +/** + * Minimal asar extractor (no dependencies): pulls one subtree of an Electron + * `.asar` archive onto disk so the plugin's session-format migration chain can + * be exercised against the RUNNING DSH build from plain node (tests cannot run + * inside the Electron runtime). + * + * Usage: node scripts/extract-asar-subtree.mjs + * e.g. node scripts/extract-asar-subtree.mjs \ + * "D:/programs/DeepSeek Harness/resources/app.asar" \ + * "dsh/node_modules/@deepseek-ai" /tmp/asarext + */ +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' + +const [archive, subtree, outDir] = process.argv.slice(2) +if (!archive || !subtree || !outDir) { + console.error('usage: extract-asar-subtree.mjs ') + process.exit(2) +} + +const buf = readFileSync(archive) +const headerSize = buf.readUInt32LE(12) +const header = JSON.parse(buf.slice(16, 16 + headerSize).toString('utf8')) +const contentBase = 16 + headerSize + +let written = 0 +function walk(node, path) { + if (node.files) { + for (const [name, child] of Object.entries(node.files)) walk(child, path ? `${path}/${name}` : name) + return + } + if (typeof node.link === 'string') return + // asar stores `offset` as a STRING in the header JSON, `size` as a number. + if (node.offset === undefined || node.size === undefined) return + const target = join(outDir, path.slice(subtree.length).replace(/^\/+/u, '')) + mkdirSync(dirname(target), { recursive: true }) + writeFileSync(target, buf.slice(contentBase + Number(node.offset), contentBase + Number(node.offset) + Number(node.size))) + written += 1 +} + +let node = header +for (const part of subtree.split('/')) { + node = node?.files?.[part] + if (!node) { + console.error(`subtree not found in asar: ${subtree}`) + process.exit(1) + } +} +mkdirSync(outDir, { recursive: true }) +walk(node, subtree) +console.log(`extracted ${written} file(s) from ${subtree} → ${outDir}`) diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs index 9bac80a..1ede450 100644 --- a/scripts/run-tests.mjs +++ b/scripts/run-tests.mjs @@ -10,6 +10,8 @@ const suites = [ 'test/host.smoke.mjs', 'test/client.render.mjs', 'test/codex-reader.test.mjs', + 'test/codex-index.test.mjs', + 'test/attach-workspaces.test.mjs', 'test/import-service.test.mjs', 'test/plugin-skill.test.mjs', 'test/export-codex.test.mjs', diff --git a/test/attach-workspaces.test.mjs b/test/attach-workspaces.test.mjs new file mode 100644 index 0000000..2f66f85 --- /dev/null +++ b/test/attach-workspaces.test.mjs @@ -0,0 +1,131 @@ +/** + * attach-workspaces: workspace titles come from the Codex project name (with the + * folder name as fallback) and never embed a filesystem path. + */ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { attachSessionsToWorkspaces, unifyWorkspaceTitles, workspaceTitle } from '../lib/attach-workspaces.mjs' +import { codexProjectNameForPath, invalidateCodexIndex, loadCodexIndex } from '../lib/codex-index.mjs' +import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +let sqlite +try { + sqlite = (await import('node:sqlite')).DatabaseSync +} catch { + sqlite = undefined +} + +/** Codex home whose project groups two repo roots under one project name. */ +function codexHomeWithProject() { + const home = mkdtempSync(join(tmpdir(), 'cx-ws-')) + mkdirSync(join(home, 'sessions'), { recursive: true }) + if (sqlite === undefined) return home + const db = new sqlite(join(home, 'state_5.sqlite')) + db.exec('CREATE TABLE threads (id TEXT, name TEXT, title TEXT, cwd TEXT, project_id TEXT, source TEXT); CREATE TABLE projects (id TEXT, name TEXT); CREATE TABLE project_roots (project_id TEXT, path TEXT);') + db.prepare('INSERT INTO projects (id, name) VALUES (?, ?)').run('p-1', 'zbwx-v2') + const root = db.prepare('INSERT INTO project_roots (project_id, path) VALUES (?, ?)') + root.run('p-1', String.raw`D:\ws\ZBWX\2.0\zbwx-frontend-v2`) + root.run('p-1', String.raw`D:\ws\ZBWX\2.0\zbwx-services-v2`) + db.close() + return home +} + +/** Minimal workspaceRegistry stand-in recording created titles. */ +function fakeRegistry() { + const byPath = new Map() + const created = [] + const make = (path, title) => { + const workspace = { + path, + title, + attached: [], + setTitle: async (next) => { workspace.title = next }, + attachSession: async (id) => { workspace.attached.push(id) }, + } + return workspace + } + return { + created, + resolveByPath: async (path) => byPath.get(path), + create: async (path, title) => { + const workspace = make(path, title) + byPath.set(path, workspace) + created.push({ path, title }) + return workspace + }, + list: () => [...byPath.values()], + } +} + +test('workspace titles use the Codex project name and never embed a path', () => { + const home = codexHomeWithProject() + invalidateCodexIndex(home) + const index = loadCodexIndex(home) + const projectNameOf = (cwd) => codexProjectNameForPath(index, cwd) + + const repo = String.raw`\\?\D:\ws\ZBWX\2.0\zbwx-frontend-v2` + if (sqlite !== undefined) { + assert.equal(codexProjectNameForPath(index, repo), 'zbwx-v2') + assert.equal(workspaceTitle(repo, projectNameOf), 'zbwx-v2') + } + // No project → the folder name, still no path in the title. + const loose = String.raw`C:\Users\neo\Documents\Codex\2026-11-06\new-chat-2` + assert.equal(workspaceTitle(loose, projectNameOf), 'new-chat-2') + assert.ok(!workspaceTitle(loose, projectNameOf).includes('\\')) + assert.ok(!workspaceTitle(repo, projectNameOf).includes('(')) +}) + +test('attach renames only auto-generated titles, leaving custom ones alone', async () => { + const home = codexHomeWithProject() + invalidateCodexIndex(home) + const index = loadCodexIndex(home) + const registry = fakeRegistry() + const ctx = { get: (name) => (name === 'workspaceRegistry' ? registry : undefined) } + const repo = String.raw`D:\ws\ZBWX\2.0\zbwx-frontend-v2` + + // First attach creates the workspace under the project name. + await attachSessionsToWorkspaces(ctx, [{ id: 'codex-1', cwd: repo }], { + projectNameOf: (cwd) => codexProjectNameForPath(index, cwd), + }) + const expected = sqlite === undefined ? 'zbwx-frontend-v2' : 'zbwx-v2' + assert.equal(registry.created.length, 1) + assert.equal(registry.created[0].title, expected) + + // A legacy path-style title (what older builds wrote) is migrated. + const workspace = registry.list()[0] + workspace.title = 'zbwx-frontend-v2 (~/ws/ZBWX/2.0/zbwx-frontend-v2)' + await attachSessionsToWorkspaces(ctx, [{ id: 'codex-2', cwd: repo }], { + projectNameOf: (cwd) => codexProjectNameForPath(index, cwd), + }) + assert.equal(workspace.title, expected) + assert.deepEqual(workspace.attached, ['codex-1', 'codex-2']) + + // A user-chosen title is preserved. + workspace.title = '我的项目' + await attachSessionsToWorkspaces(ctx, [{ id: 'codex-3', cwd: repo }], { + projectNameOf: (cwd) => codexProjectNameForPath(index, cwd), + }) + assert.equal(workspace.title, '我的项目') +}) + +test('unifyWorkspaceTitles strips path-form titles but keeps custom ones', async () => { + const home = codexHomeWithProject() + invalidateCodexIndex(home) + const index = loadCodexIndex(home) + const registry = fakeRegistry() + const ctx = { get: (name) => (name === 'workspaceRegistry' ? registry : undefined) } + const repo = String.raw`D:\ws\ZBWX\2.0\zbwx-frontend-v2` + await registry.create(repo, 'zbwx-frontend-v2 (~/ws/ZBWX/2.0/zbwx-frontend-v2)') + const loose = String.raw`C:\Users\neo\Documents\Codex\2026-11-06\new-chat-2` + await registry.create(loose, 'new-chat-2 (new-chat-2)') + await registry.create('D:/custom', '自定义名字 (x)') + + const changed = await unifyWorkspaceTitles(ctx, { projectNameOf: (cwd) => codexProjectNameForPath(index, cwd) }) + const titles = registry.list().map((w) => w.title) + assert.equal(changed, 2) + assert.ok(titles.includes(sqlite === undefined ? 'zbwx-frontend-v2' : 'zbwx-v2')) + assert.ok(titles.includes('new-chat-2')) + assert.ok(titles.includes('自定义名字 (x)')) +}) diff --git a/test/codex-index.test.mjs b/test/codex-index.test.mjs new file mode 100644 index 0000000..479d5b5 --- /dev/null +++ b/test/codex-index.test.mjs @@ -0,0 +1,114 @@ +/** + * codex-index: titles and project names must come from Codex's own state + * (`state_5.sqlite`), with `session_index.jsonl` and the rollout as fallbacks. + */ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { mkdtempSync, writeFileSync, mkdirSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { + codexOriginOf, + codexProjectOf, + codexTitleOf, + invalidateCodexIndex, + loadCodexIndex, + normalizePath, +} from '../lib/codex-index.mjs' + +let sqlite +try { + sqlite = (await import('node:sqlite')).DatabaseSync +} catch { + sqlite = undefined +} + +/** A codex home with a state DB (threads/projects/project_roots) + jsonl index. */ +function fixture() { + const home = mkdtempSync(join(tmpdir(), 'cx-index-')) + mkdirSync(join(home, 'sessions'), { recursive: true }) + writeFileSync(join(home, 'session_index.jsonl'), [ + JSON.stringify({ id: 'only-in-jsonl', thread_name: 'indexed name' }), + JSON.stringify({ id: 'named', thread_name: 'stale index name' }), + ].join('\n')) + if (sqlite === undefined) return home + + const db = new sqlite(join(home, 'state_5.sqlite')) + db.exec(` + CREATE TABLE threads (id TEXT, name TEXT, title TEXT, cwd TEXT, project_id TEXT, source TEXT); + CREATE TABLE projects (id TEXT, name TEXT); + CREATE TABLE project_roots (project_id TEXT, path TEXT); + `) + const thread = db.prepare('INSERT INTO threads (id, name, title, cwd, project_id, source) VALUES (?, ?, ?, ?, ?, ?)') + thread.run('named', '修复游客模式刷卡失败', '# Selected text:\n\n## Selection', '\\\\?\\D:\\repo\\app', null, 'vscode') + thread.run('named-only-in-db', '数据库标题', null, '\\\\?\\D:\\repo\\app', null, 'vscode') + thread.run('prompt-only', null, '帮我把这个函数重写一下', null, null, 'cli') + thread.run('guardian', 'Guardian review', null, '\\\\?\\D:\\repo\\app', null, '{"subagent":{"other":"guardian"}}') + thread.run('spawned', 'worker', null, '\\\\?\\D:\\repo\\app', null, + '{"subagent":{"thread_spawn":{"parent_thread_id":"parent-1","depth":1}}}') + thread.run('grouped', '另一个仓库里的会话', null, '\\\\?\\D:\\repo\\second', 'p-1', 'vscode') + const project = db.prepare('INSERT INTO projects (id, name) VALUES (?, ?)') + project.run('p-1', 'mono-repo') + const root = db.prepare('INSERT INTO project_roots (project_id, path) VALUES (?, ?)') + root.run('p-1', 'D:\\repo') + root.run('p-1', 'D:\\repo\\second') + db.close() + return home +} + +test('normalizePath strips the Windows extended prefix and case-folds drive paths', () => { + assert.equal(normalizePath('\\\\?\\D:\\Repo\\App\\'), 'd:/repo/app') + assert.equal(normalizePath('D:/repo/app'), 'd:/repo/app') + assert.equal(normalizePath(undefined), '') +}) + +test('titles prefer the SQLite name, then session_index, then threads.title', () => { + const home = fixture() + invalidateCodexIndex(home) + const index = loadCodexIndex(home) + if (sqlite === undefined) return + // `name` is what Codex's sidebar shows; `title` here is a pasted prompt. + assert.equal(codexTitleOf(index, 'named'), '修复游客模式刷卡失败') + assert.equal(codexTitleOf(index, 'named-only-in-db'), '数据库标题') + // no name/title in the DB → the jsonl index is used … + assert.equal(codexTitleOf(index, 'only-in-jsonl'), 'indexed name') + // … and threads.title is the last resort (Codex shows it the same way). + assert.equal(codexTitleOf(index, 'prompt-only'), '帮我把这个函数重写一下') + assert.equal(codexTitleOf(index, 'unknown-thread'), undefined) +}) + +test('projects resolve by project_id and by the longest matching root', () => { + const home = fixture() + invalidateCodexIndex(home) + const index = loadCodexIndex(home) + if (sqlite === undefined) return + assert.equal(codexProjectOf(index, 'grouped', undefined)?.name, 'mono-repo') + // No project_id, but the cwd sits under a known root → same project. + assert.equal(codexProjectOf(index, 'named', '\\\\?\\D:\\repo\\app')?.name, 'mono-repo') + // The more specific root wins when roots nest. + assert.equal(codexProjectOf(index, 'unknown', 'D:\\repo\\second\\src')?.name, 'mono-repo') + // Nothing matches → no project (caller falls back to the folder name). + assert.equal(codexProjectOf(index, 'unknown', 'E:\\elsewhere'), undefined) +}) + +test('origin distinguishes user chats from guardian reviews and spawned sub-agents', () => { + const home = fixture() + invalidateCodexIndex(home) + const index = loadCodexIndex(home) + if (sqlite === undefined) return + assert.equal(codexOriginOf(index, 'named')?.kind, 'user') + assert.equal(codexOriginOf(index, 'guardian')?.kind, 'guardian') + assert.equal(codexOriginOf(index, 'spawned')?.kind, 'subagent') + assert.equal(codexOriginOf(index, 'spawned')?.parentThreadId, 'parent-1') + assert.equal(codexOriginOf(index, 'unknown'), undefined) +}) + +test('without a state DB the JSONL index still supplies titles', () => { + const home = mkdtempSync(join(tmpdir(), 'cx-index-jsonl-')) + writeFileSync(join(home, 'session_index.jsonl'), JSON.stringify({ id: 'a', thread_name: '旧版名称' })) + invalidateCodexIndex(home) + const index = loadCodexIndex(home) + assert.equal(index.source, 'jsonl') + assert.equal(codexTitleOf(index, 'a'), '旧版名称') + assert.equal(codexOriginOf(index, 'a'), undefined) +}) diff --git a/test/codex-reader.test.mjs b/test/codex-reader.test.mjs index dae3d38..9cb2a81 100644 --- a/test/codex-reader.test.mjs +++ b/test/codex-reader.test.mjs @@ -7,6 +7,7 @@ import assert from 'node:assert/strict' import { mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { zstdCompressSync } from 'node:zlib' import { parseCodexSession, isSubagentThread } from '../lib/codex-reader.mjs' import { buildDshEvents, deriveImportTitle } from '../lib/convert.mjs' @@ -34,11 +35,11 @@ const ROLLOUT = [ }, ].map((e) => JSON.stringify(e)).join('\n') + '\n' -test('codex reader strips control blocks and keeps real text', () => { +test('codex reader strips control blocks and keeps real text', async () => { const dir = mkdtempSync(join(tmpdir(), 'cx-reader-')) const file = join(dir, 'rollout-test.jsonl') writeFileSync(file, ROLLOUT) - const { header, messages } = parseCodexSession(file) + const { header, messages } = await parseCodexSession(file) assert.equal(header.id, 'sess-1') assert.equal(messages.length, 3) // first user message: only the real prompt survives @@ -49,11 +50,11 @@ test('codex reader strips control blocks and keeps real text', () => { assert.equal(messages[2].blocks[0].text, '要不要全局安装?') }) -test('convert: control-only user message opens no turn and never seeds the title', () => { +test('convert: control-only user message opens no turn and never seeds the title', async () => { const dir = mkdtempSync(join(tmpdir(), 'cx-reader-')) const file = join(dir, 'rollout-test.jsonl') writeFileSync(file, ROLLOUT) - const { messages } = parseCodexSession(file) + const { messages } = await parseCodexSession(file) const events = buildDshEvents(messages, { toolEvents: true, titlePinned: true }) const kinds = events.map((e) => e.type) // no turn/start before the first real user message @@ -92,7 +93,7 @@ let n = 0 const write = (file, text) => { writeFileSync(file, text); return file } const nextFile = (kind) => write(join(mkdtempSync(join(tmpdir(), 'cx-new-')), `${kind}-${++n}.jsonl`), '') -test('new schema: tool call + real output fold into one assistant message with real result', () => { +test('new schema: tool call + real output fold into one assistant message with real result', async () => { const events = [ msg('T1', '2026-08-17T10:00:01Z', 'user', [{ type: 'input_text', text: '改一下 main.js' }]), msg('T2', '2026-08-17T10:00:05Z', 'assistant', [{ type: 'output_text', text: '我用编辑工具。' }]), @@ -101,7 +102,7 @@ test('new schema: tool call + real output fold into one assistant message with r msg('T5', '2026-08-17T10:00:09Z', 'assistant', [{ type: 'output_text', text: '改好了。' }]), ] const file = nextFile('tools'); write(file, rolloutOf(events)) - const { messages } = parseCodexSession(file) + const { messages } = await parseCodexSession(file) // user, assistant(text), assistant(tool call+result), assistant(text) assert.equal(messages.length, 4) const toolMsg = messages[2] @@ -126,7 +127,7 @@ test('new schema: tool call + real output fold into one assistant message with r assert.ok(written.data.message.content.every((b) => b.type !== 'tool-result'), 'tool-result block must not appear in assistant content') }) -test('new schema: oversized tool output is capped with a truncation note', () => { +test('new schema: oversized tool output is capped with a truncation note', async () => { const big = 'y'.repeat(9000) const events = [ msg('T1', '2026-08-17T10:00:01Z', 'user', [{ type: 'input_text', text: '列目录' }]), @@ -135,7 +136,7 @@ test('new schema: oversized tool output is capped with a truncation note', () => msg('T4', '2026-08-17T10:00:09Z', 'assistant', [{ type: 'output_text', text: '太长我截断了。' }]), ] const file = nextFile('cap'); write(file, rolloutOf(events)) - const { messages } = parseCodexSession(file) + const { messages } = await parseCodexSession(file) const blocks = messages.flatMap((m) => m.blocks).filter((b) => b.type === 'tool-result') assert.equal(blocks.length, 1) const text = blocks[0].content[0].text @@ -143,14 +144,14 @@ test('new schema: oversized tool output is capped with a truncation note', () => assert.match(text, /…\[截断:源输出 9000 字符\]/) }) -test('new schema: reasoning summary_text arrays flatten to a string', () => { +test('new schema: reasoning summary_text arrays flatten to a string', async () => { const events = [ msg('T1', '2026-08-17T10:00:01Z', 'user', [{ type: 'input_text', text: 'hi' }]), reason('T2', [{ type: 'summary_text', text: 'think step one' }]), msg('T3', '2026-08-17T10:00:05Z', 'assistant', [{ type: 'output_text', text: 'ok' }]), ] const file = nextFile('reason-arr'); write(file, rolloutOf(events)) - const { messages } = parseCodexSession(file) + const { messages } = await parseCodexSession(file) const reasoning = messages[1].blocks.filter((b) => b.type === 'reasoning') assert.equal(reasoning[0].text, 'think step one') const events2 = buildDshEvents(messages, { toolEvents: true }) @@ -158,21 +159,21 @@ test('new schema: reasoning summary_text arrays flatten to a string', () => { assert.equal(typeof asst.data.message.content[0].text, 'string') }) -test('new schema: reasoning summaries merge into the pending assistant message', () => { +test('new schema: reasoning summaries merge into the pending assistant message', async () => { const events = [ msg('T1', '2026-08-17T10:00:01Z', 'user', [{ type: 'input_text', text: '1+1?' }]), reason('T2', '先心算,1+1=2'), msg('T3', '2026-08-17T10:00:05Z', 'assistant', [{ type: 'output_text', text: '等于 2。' }]), ] const file = nextFile('reason'); write(file, rolloutOf(events)) - const { messages } = parseCodexSession(file) + const { messages } = await parseCodexSession(file) assert.equal(messages.length, 3) const reasoning = messages[1].blocks.filter((b) => b.type === 'reasoning') assert.equal(reasoning.length, 1) assert.equal(reasoning[0].text, '先心算,1+1=2') }) -test('new schema: raw image fragments are stripped from user text', () => { +test('new schema: raw image fragments are stripped from user text', async () => { const events = [ msg('T1', '2026-08-17T10:00:01Z', 'user', [ { type: 'input_text', text: '# Files mentioned by the user:\n\n## 照片 1.jpg content' }, @@ -182,14 +183,97 @@ test('new schema: raw image fragments are stripped from user text', () => { msg('T2', '2026-08-17T10:00:05Z', 'assistant', [{ type: 'output_text', text: '我看到了。' }]), ] const file = nextFile('img'); write(file, rolloutOf(events)) - const { messages } = parseCodexSession(file) + const { messages } = await parseCodexSession(file) assert.equal(messages.length, 2) const userText = messages[0].blocks.map((b) => b.text).join('\n') assert.doesNotMatch(userText, / { +test('new schema: an activated skill wrapper is not imported as a user message', async () => { + // Codex hands `…SKILL.md…` to the model as a USER message, so + // without filtering it the whole skill body shows up in the transcript. + const skill = [ + '', + 'zbwx-frontend-plugin-development', + 'D:\\repo\\.agents\\skills\\x\\SKILL.md', + '---', + 'name: zbwx-frontend-plugin-development', + 'description: implement or review plugins', + '---', + '# 开发约定', + '', + ].join('\n') + const events = [ + msg('T1', '2026-08-17T10:00:01Z', 'user', [{ type: 'input_text', text: skill }]), + msg('T2', '2026-08-17T10:00:02Z', 'user', [{ type: 'input_text', text: '真正的问题' }]), + msg('T3', '2026-08-17T10:00:05Z', 'assistant', [{ type: 'output_text', text: '好的。' }]), + ] + const file = nextFile('skill'); write(file, rolloutOf(events)) + const { messages } = await parseCodexSession(file) + assert.equal(messages.length, 2) + assert.deepEqual(messages[0].blocks, [{ type: 'text', text: '真正的问题' }]) + assert.doesNotMatch(JSON.stringify(messages), /SKILL\.md/) +}) + +test('new schema: codex desktop envelopes are dropped, real content is kept', async () => { + const events = [ + msg('T1', '2026-08-17T10:00:01Z', 'user', [ + { type: 'input_text', text: '\nContinue working toward the objective\n' }, + { type: 'input_text', text: '{"page_id":null}' }, + { type: 'input_text', text: '\nstuff\n' }, + { type: 'input_text', text: '' }, + { type: 'input_text', text: '帮我改一下这个页面' }, + ]), + msg('T2', '2026-08-17T10:00:05Z', 'user', [ + { type: 'input_text', text: ' [{"questionItemId":"q1","answer":"选 A"}] ' }, + ]), + msg('T3', '2026-08-17T10:00:09Z', 'assistant', [ + { type: 'output_text', text: '\n1. 改样式\n' }, + ]), + ] + const file = nextFile('envelopes'); write(file, rolloutOf(events)) + const { messages } = await parseCodexSession(file) + assert.equal(messages.length, 3) + assert.deepEqual(messages[0].blocks, [{ type: 'text', text: '帮我改一下这个页面' }]) + // The user's answer to a question and the assistant's plan are real content. + assert.match(messages[1].blocks[0].text, /选 A/) + assert.match(messages[2].blocks[0].text, /proposed_plan/) +}) + +test('reader: the last thread_goal_updated becomes the session goal', async () => { + const goalEvent = (status, updatedAt) => ({ + type: 'event_msg', + timestamp: '2026-08-17T10:00:00Z', + payload: { + type: 'thread_goal_updated', + threadId: 'sess-goal', + goal: { + threadId: 'sess-goal', + objective: '把目标模式带过去', + status, + tokensUsed: 1234, + timeUsedSeconds: 56, + createdAt: 1787000000, + updatedAt, + }, + }, + }) + const file = nextFile('goal') + write(file, rolloutOf([ + { type: 'session_meta', payload: { id: 'sess-goal', cwd: '/tmp/p', timestamp: '2026-08-17T09:59:00Z' } }, + goalEvent('active', 1787000100), + goalEvent('paused', 1787000200), + ])) + const { header } = await parseCodexSession(file) + assert.equal(header.goal.status, 'paused', 'the last snapshot wins') + assert.equal(header.goal.objective, '把目标模式带过去') + assert.equal(header.goal.createdAt, 1787000000 * 1000, 'codex stores seconds') + assert.equal(header.goal.updatedAt, 1787000200 * 1000) + assert.equal(header.goal.tokensUsed, 1234) +}) + +test('legacy schema: tool_use blocks inside message content still map to tool-calls', async () => { const events = [ msg('T1', '2026-08-17T10:00:01Z', 'user', [{ type: 'input_text', text: '读文件' }]), msg('T2', '2026-08-17T10:00:05Z', 'assistant', [ @@ -198,7 +282,7 @@ test('legacy schema: tool_use blocks inside message content still map to tool-ca ]), ] const file = nextFile('legacy'); write(file, rolloutOf(events)) - const { messages } = parseCodexSession(file) + const { messages } = await parseCodexSession(file) const toolCall = messages[1].blocks.find((b) => b.type === 'tool-call') assert.ok(toolCall) assert.equal(toolCall.id, 'call-7') @@ -207,17 +291,56 @@ test('legacy schema: tool_use blocks inside message content still map to tool-ca }) -test('reader: parent_thread_id marks a sub-agent thread header', () => { +test('reader: parent_thread_id marks a sub-agent thread header', async () => { const meta = { id: 'sess-sub', cwd: '/tmp', timestamp: '2026-08-17T10:00:00.000Z', parent_thread_id: 'sess-main', agent_nickname: 'Einstein' } const file = nextFile('subagent-marker') write(file, rolloutOf([{ type: 'session_meta', payload: meta }])) - const { header } = parseCodexSession(file) + const { header } = await parseCodexSession(file) assert.equal(header.parentThreadId, 'sess-main') assert.equal(header.agentNickname, 'Einstein') assert.equal(isSubagentThread(header), true) assert.equal(isSubagentThread({}), false) }) +test('reader: zstd-compressed rollout (.jsonl.zst) parses like the plain one', async () => { + const dir = mkdtempSync(join(tmpdir(), 'cx-reader-zst-')) + const plain = join(dir, 'rollout-plain.jsonl') + const packed = join(dir, 'rollout-packed.jsonl.zst') + writeFileSync(plain, ROLLOUT) + writeFileSync(packed, zstdCompressSync(Buffer.from(ROLLOUT, 'utf8'))) + + const plainParsed = await parseCodexSession(plain) + const packedParsed = await parseCodexSession(packed) + assert.equal(packedParsed.header.id, 'sess-1') + assert.equal(packedParsed.messages.length, plainParsed.messages.length) + assert.deepEqual( + packedParsed.messages.map((m) => m.blocks), + plainParsed.messages.map((m) => m.blocks), + ) +}) + +test('reader: multi-frame rollout keeps every frame (codex appends frames)', async () => { + // node's zstd decoder stops at the end of the first frame, so a rollout that + // was extended by appending a second frame must still be read to the end. + const lines = ROLLOUT.split('\n').filter((l) => l.length > 0) + const head = `${lines.slice(0, 2).join('\n')}\n` + const tail = `${lines.slice(2).join('\n')}\n` + const dir = mkdtempSync(join(tmpdir(), 'cx-reader-multi-')) + const file = join(dir, 'rollout-multi.jsonl.zst') + writeFileSync(file, Buffer.concat([ + zstdCompressSync(Buffer.from(head, 'utf8')), + zstdCompressSync(Buffer.from(tail, 'utf8')), + ])) + + const multi = await parseCodexSession(file) + const single = await parseCodexSession(write(join(dir, 'rollout-single.jsonl'), ROLLOUT)) + assert.equal(multi.header.id, 'sess-1') + assert.deepEqual( + multi.messages.map((m) => m.blocks), + single.messages.map((m) => m.blocks), + ) +}) + // ═══ step/start…step/end pairing: token-meter replay contract. // Every assistant/message, tool/call and tool/result must sit inside a paired // step region — @deepseek-ai/dsh-token-meter fails loud on unmarked logs @@ -244,7 +367,7 @@ function assertStepPairing(events) { assert.equal(open, null, 'log ends with an open step') } -test('convert: every assistant message and tool event sits inside paired step markers', () => { +test('convert: every assistant message and tool event sits inside paired step markers', async () => { const events = buildDshEvents( [ { role: 'user', time: 1000, blocks: [{ type: 'text', text: 'q1' }] }, @@ -261,7 +384,7 @@ test('convert: every assistant message and tool event sits inside paired step ma assertStepPairing(events) }) -test('convert: consecutive assistant messages get one step each, closed at turn boundaries', () => { +test('convert: consecutive assistant messages get one step each, closed at turn boundaries', async () => { const events = buildDshEvents( [ { role: 'user', time: 10, blocks: [{ type: 'text', text: 'hi' }] }, @@ -282,7 +405,7 @@ test('convert: consecutive assistant messages get one step each, closed at turn }) -test('function_call: preserves arguments and prefers them over legacy input', () => { +test('function_call: preserves arguments and prefers them over legacy input', async () => { const args = '{"text":"standard function argument"}' const file = nextFile('function-arguments') write(file, rolloutOf([ @@ -293,13 +416,13 @@ test('function_call: preserves arguments and prefers them over legacy input', () type: 'function_call_output', call_id: 'function-1', output: 'function result', } }, ])) - const { messages } = parseCodexSession(file) + const { messages } = await parseCodexSession(file) const blocks = messages.flatMap(m => m.blocks) assert.equal(blocks.find(b => b.type === 'tool-call').arguments, args) assert.deepEqual(blocks.find(b => b.type === 'tool-result').content, [{ type: 'text', text: 'function result' }]) }) -test('tool inputs: function arguments objects and empty strings; custom calls keep input', () => { +test('tool inputs: function arguments objects and empty strings; custom calls keep input', async () => { const file = nextFile('tool-input-variants') write(file, rolloutOf([ ...[ @@ -309,6 +432,6 @@ test('tool inputs: function arguments objects and empty strings; custom calls ke { type: 'custom_tool_call', call_id: 'custom', name: 'patch', input: 'custom input', arguments: 'wrong' }, ].map(payload => ({ type: 'response_item', timestamp: '2026-08-17T10:00:01Z', payload })), ])) - const calls = parseCodexSession(file).messages.flatMap(m => m.blocks).filter(b => b.type === 'tool-call') + const calls = (await parseCodexSession(file)).messages.flatMap(m => m.blocks).filter(b => b.type === 'tool-call') assert.deepEqual(calls.map(b => b.arguments), ['{"text":"object"}', '', 'legacy input', 'custom input']) }) diff --git a/test/export-codex.test.mjs b/test/export-codex.test.mjs index 9e345d4..d61a437 100644 --- a/test/export-codex.test.mjs +++ b/test/export-codex.test.mjs @@ -3,7 +3,7 @@ import assert from 'node:assert/strict' import { mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { buildRolloutJsonl, dshEventsToCodexMessages, exportToCodex, listExportCatalog, titleOf } from '../lib/export-codex.js' +import { buildRolloutJsonl, codexGoalSnapshot, dshEventsToCodexMessages, exportToCodex, goalOf, listExportCatalog, titleOf } from '../lib/export-codex.js' test('dshEventsToCodexMessages keeps user and assistant text', () => { const msgs = dshEventsToCodexMessages([ @@ -69,6 +69,49 @@ test('exportToCodex writes a session_meta + response_item jsonl', async () => { assert.equal(userItem.payload.message, 'hi') }) +test('buildRolloutJsonl carries goal mode as a thread_goal_updated snapshot', () => { + const now = Date.parse('2026-01-01T00:00:00Z') + const goalChange = (phase, extra = {}) => ({ + type: 'goal/change', + time: now, + data: { + kind: 'goal/change', + version: 1, + operation: 'create', + goal: { id: 'goal-1', revision: 1, objective: '把目标带过去', phase, maxGoalRounds: 256 }, + roundsStarted: 0, + createdAt: now, + updatedAt: now, + ...extra, + }, + }) + const build = (events) => buildRolloutJsonl({ + uuid: '22222222-2222-2222-2222-222222222222', + cwd: '/tmp', + createdAt: now, + messages: [{ role: 'user', text: 'hi', time: now }], + goal: goalOf(events), + }) + + // active → Codex `active` + const active = JSON.parse(build([goalChange('active')]).trim().split('\n').find((l) => l.includes('thread_goal_updated'))) + assert.equal(active.payload.type, 'thread_goal_updated') + assert.equal(active.payload.goal.status, 'active') + assert.equal(active.payload.goal.objective, '把目标带过去') + assert.equal(active.payload.threadId, '22222222-2222-2222-2222-222222222222') + + // paused / blocked → Codex only knows active|paused + assert.equal(codexGoalSnapshot(goalOf([goalChange('paused')]), 'u').goal.status, 'paused') + assert.equal(codexGoalSnapshot(goalOf([goalChange('blocked')]), 'u').goal.status, 'paused') + + // a completed goal is not re-exported as a live one + const completed = build([goalChange('complete')]) + assert.equal(completed.includes('thread_goal_updated'), false) + + // the last goal/change wins + assert.equal(goalOf([goalChange('complete'), goalChange('active')]).phase, 'active') +}) + test('buildRolloutJsonl is parseable JSONL', () => { const text = buildRolloutJsonl({ uuid: '11111111-1111-1111-1111-111111111111', diff --git a/test/host.smoke.mjs b/test/host.smoke.mjs index f714a99..7e5e73f 100644 --- a/test/host.smoke.mjs +++ b/test/host.smoke.mjs @@ -14,6 +14,7 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { pathToFileURL } from 'node:url' import { test } from 'node:test' import assert from 'node:assert/strict' import { dshDep } from './_env.mjs' @@ -26,7 +27,7 @@ test('state: persisted settings override config defaults (DSH_HOME temp)', async const prevHome = process.env.DSH_HOME process.env.DSH_HOME = tempHome try { - const { effectiveSetting, writeState, readState } = await import(join(PROJECT, 'lib', 'state.js')) + const { effectiveSetting, writeState, readState } = await import(pathToFileURL(join(PROJECT, 'lib', 'state.js')).href) // untouched → config defaults win assert.equal(effectiveSetting('enableInstructions', true), true) assert.equal(effectiveSetting('enableInstructions', false), false) @@ -97,9 +98,9 @@ command = "computer" t.skip('cordis not found in the dsh installation') return } - const { Context, Service } = await import(join(cordisRoot, 'lib', 'index.js')) - const plugin = (await import(join(PROJECT, 'lib', 'index.js'))).default - const { startMcpMirror, formatMcpStatus } = await import(join(PROJECT, 'lib', 'mcp.js')) + const { Context, Service } = await import(pathToFileURL(join(cordisRoot, 'lib', 'index.js')).href) + const plugin = (await import(pathToFileURL(join(PROJECT, 'lib', 'index.js')).href)).default + const { startMcpMirror, formatMcpStatus } = await import(pathToFileURL(join(PROJECT, 'lib', 'mcp.js')).href) class StubSystemPrompt extends Service { constructor(c) { super(c, 'systemPrompt', true) } section() { return () => {} } } class StubCommands extends Service { @@ -155,7 +156,7 @@ command = "computer" assert.match(unknown.text, /未知设置/) // /import-codex: args parse from invocation.rawInput - const { parseInput } = await import(join(PROJECT, 'lib', 'index.js')) + const { parseInput } = await import(pathToFileURL(join(PROJECT, 'lib', 'index.js')).href) assert.deepEqual(parseInput(' --limit 5 --since 2026-01-01'), { limit: 5, since: 1767225600000 }) // bare boolean flags (e.g. --include-subagents) must not swallow the next value token assert.deepEqual(parseInput(' --include-subagents'), { 'include-subagents': true }) diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index 1ac66c8..a9749c3 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -106,6 +106,53 @@ test('import-codex: sub-agent threads are filtered by default', async () => { assert.match(report, /--include-subagents/, 'report hints the opt-in flag') }) +test('import-codex: an unfinished Codex goal becomes an active DSH goal', async () => { + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-goal-')) + const id = makeSession(root, 'goal') + // Codex writes one snapshot per goal mutation; the last one (paused) wins. + appendFileSync(join(root, 'sessions', '2026', '08', '17', 'rollout-goal.jsonl'), [ + { type: 'event_msg', timestamp: '2026-08-17T10:00:02.000Z', payload: { type: 'thread_goal_updated', threadId: 'sess-goal', goal: { threadId: 'sess-goal', objective: '把插件适配做完', status: 'active', createdAt: 1787000000, updatedAt: 1787000100 } } }, + { type: 'event_msg', timestamp: '2026-08-17T10:00:03.000Z', payload: { type: 'thread_goal_updated', threadId: 'sess-goal', goal: { threadId: 'sess-goal', objective: '把插件适配做完', status: 'paused', createdAt: 1787000000, updatedAt: 1787000200 } } }, + ].map((e) => JSON.stringify(e)).join('\n') + '\n') + const { persistence, ctx, store } = stubPersistence() + + await importCodex(ctx, persistence, {}, root) + const goals = (store.get(id) ?? []).filter((e) => e.type === 'goal/change') + assert.equal(goals.length, 2, 'create + pause') + assert.equal(goals[0].data.operation, 'create') + assert.equal(goals[0].data.goal.objective, '把插件适配做完') + assert.equal(goals[0].data.goal.id, `goal-${id}`) + assert.equal(goals[1].data.operation, 'pause') + assert.equal(goals[1].data.goal.phase, 'paused') +}) + +test('import-codex: re-import follows a Codex goal that changed to paused', async () => { + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-goal2-')) + const id = makeSession(root, 'goal2') + const file = join(root, 'sessions', '2026', '08', '17', 'rollout-goal2.jsonl') + const goalLine = (status, updatedAt) => JSON.stringify({ + type: 'event_msg', + timestamp: '2026-08-17T10:00:04.000Z', + payload: { type: 'thread_goal_updated', threadId: 'sess-goal2', goal: { threadId: 'sess-goal2', objective: '继续推进', status, createdAt: 1787000000, updatedAt } }, + }) + appendFileSync(file, goalLine('active', 1787000100) + '\n') + const { persistence, ctx, store } = stubPersistence() + + await importCodex(ctx, persistence, {}, root) + const first = (store.get(id) ?? []).filter((e) => e.type === 'goal/change') + assert.equal(first.length, 1) + assert.equal(first[0].data.goal.phase, 'active') + + // Codex pauses the goal; the next import must append only the transition. + appendFileSync(file, goalLine('paused', 1787000200) + '\n') + await importCodex(ctx, persistence, {}, root) + const goals = (store.get(id) ?? []).filter((e) => e.type === 'goal/change') + assert.equal(goals.length, 2) + assert.equal(goals[1].data.operation, 'pause') + assert.equal(goals[1].data.goal.phase, 'paused') + assert.equal(goals[1].data.goal.revision, 2) +}) + test('catalog: nests sub-agents under parent and marks imported', async () => { const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) const mainId = makeSession(root, 'main') diff --git a/test/item-sync.test.mjs b/test/item-sync.test.mjs index 6f450b1..8329272 100644 --- a/test/item-sync.test.mjs +++ b/test/item-sync.test.mjs @@ -8,6 +8,7 @@ import assert from 'node:assert/strict' import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, dirname } from 'node:path' +import { pathToFileURL } from 'node:url' const PROJECT = join(import.meta.dirname, '..') @@ -21,7 +22,7 @@ test('state: per-item sync groups default on, override, clear-to-default', async const home = freshHome() try { const { readSyncGroup, effectiveItemSync, writeItemSync, writeSyncDefault, writeAllItemSync } = - await import(join(PROJECT, 'lib', 'state.js')) + await import(pathToFileURL(join(PROJECT, 'lib', 'state.js')).href) // untouched → everything follows the default (true) assert.equal(readSyncGroup('skill').default, true) assert.equal(effectiveItemSync('skill', 'pdf'), true) @@ -57,8 +58,8 @@ test('skills: provider list() hides user-disabled entries', async () => { mkdirSync(join(skillsDir, 'beta'), { recursive: true }) writeFileSync(join(skillsDir, 'alpha', 'SKILL.md'), '---\nname: alpha\ndescription: a\n---\nbody-a\n') writeFileSync(join(skillsDir, 'beta', 'SKILL.md'), '---\nname: beta\ndescription: b\n---\nbody-b\n') - const { registerCodexSkillProvider } = await import(join(PROJECT, 'lib', 'skill-provider.js')) - const { writeItemSync } = await import(join(PROJECT, 'lib', 'state.js')) + const { registerCodexSkillProvider } = await import(pathToFileURL(join(PROJECT, 'lib', 'skill-provider.js')).href) + const { writeItemSync } = await import(pathToFileURL(join(PROJECT, 'lib', 'state.js')).href) const control = { signal: new AbortController().signal, invalidate: () => {} } const provider = registerCodexSkillProvider(codexHome, {}, control, () => true) @@ -106,8 +107,8 @@ FakeMcpClient.instances = [] `) // Point the module resolver at the isolated fixture for this test. process.env.DSH_CX_SYNC_MCP_CLIENT_DIR = dirname(fakeDir) - const { startMcpMirror } = await import(join(PROJECT, 'lib', 'mcp.js')) - const { writeItemSync, effectiveItemSync } = await import(join(PROJECT, 'lib', 'state.js')) + const { startMcpMirror } = await import(pathToFileURL(join(PROJECT, 'lib', 'mcp.js')).href) + const { writeItemSync, effectiveItemSync } = await import(pathToFileURL(join(PROJECT, 'lib', 'state.js')).href) const mounted = [] const ctx = { @@ -161,7 +162,7 @@ test('commands: /codex-skills, /codex-skill all|one persist and report', async ( plugin: () => ({ apply() {} }), // nested http plugin: stub, never applied systemPrompt: { section: () => {} }, } - const plugin = await import(join(PROJECT, 'lib', 'index.js')) + const plugin = await import(pathToFileURL(join(PROJECT, 'lib', 'index.js')).href) plugin.apply(ctx, { codexHome }) const raw = (inv) => ({ rawInput: inv }) diff --git a/test/zstd-frame.test.mjs b/test/zstd-frame.test.mjs index 3a1ccf0..4c0da45 100644 --- a/test/zstd-frame.test.mjs +++ b/test/zstd-frame.test.mjs @@ -1,16 +1,16 @@ import { test } from 'node:test' import assert from 'node:assert/strict' -import { execFileSync } from 'node:child_process' -import { compressChecksummedFrame } from '../lib/zstd-frame.mjs' +import { compressChecksummedFrame, decompressFrames } from '../lib/zstd-frame.mjs' test('checksummed Zstandard frames round-trip independently and when concatenated', () => { const first = Buffer.from('{"type":"session","version":4}\n') const second = Buffer.from('{"type":"turn/start","seq":0}\n') const frames = [compressChecksummedFrame(first), compressChecksummedFrame(second)] - const decode = input => execFileSync('zstd', ['--quiet', '--decompress', '--stdout'], { input }) - assert.deepEqual(decode(frames[0]), first) - assert.deepEqual(decode(Buffer.concat(frames)), Buffer.concat([first, second])) + assert.deepEqual(decompressFrames(frames[0]), first) + // DSH's session store appends one frame per batch, so concatenation must + // decode as the whole stream — a plain zstd decode stops after frame one. + assert.deepEqual(decompressFrames(Buffer.concat(frames)), Buffer.concat([first, second])) const corrupt = Buffer.from(frames[1]) corrupt[corrupt.length - 1] ^= 1 - assert.throws(() => decode(corrupt), 'a corrupted checksum must fail') + assert.throws(() => decompressFrames(corrupt), 'a corrupted checksum must fail') }) From baf33a593c8439ca35f955ee88e1ba757a976d10 Mon Sep 17 00:00:00 2001 From: neo Date: Wed, 11 Nov 2026 19:41:10 +0800 Subject: [PATCH 02/18] chore: ignore packed git bundles --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 6625018..af77609 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ node_modules/ *.tgz .DS_Store .npm-cache/ +*.bundle From 5532312789d7d11a2d5edac5d9aafd12ebda1c03 Mon Sep 17 00:00:00 2001 From: neo Date: Wed, 11 Nov 2026 19:43:26 +0800 Subject: [PATCH 03/18] chore: point repository/homepage/bugs at nlsp60/dsh-codex-sync --- package.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 4a77fe0..441500d 100644 --- a/package.json +++ b/package.json @@ -22,12 +22,12 @@ "main": "lib/index.js", "repository": { "type": "git", - "url": "git+https://github.com/Walvez/dsh-codex-sync.git" + "url": "git+https://github.com/nlsp60/dsh-codex-sync.git" }, "bugs": { - "url": "https://github.com/Walvez/dsh-codex-sync/issues" + "url": "https://github.com/nlsp60/dsh-codex-sync/issues" }, - "homepage": "https://github.com/Walvez/dsh-codex-sync", + "homepage": "https://github.com/nlsp60/dsh-codex-sync", "exports": { ".": { "default": "./lib/index.js" From 56068d9f8825c28cffc09257023485c10089f1cd Mon Sep 17 00:00:00 2001 From: neo Date: Wed, 11 Nov 2026 20:19:40 +0800 Subject: [PATCH 04/18] =?UTF-8?q?fix:=201.9.1=20=E2=80=94=20do=20not=20abo?= =?UTF-8?q?rt=20the=20import=20when=20a=20chat=20is=20open=20in=20DSH?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DSH's JSONL backend keeps one write handle per Session id and refuses a second (`session "…" is already owned by an active write handle`), which is exactly the state of a chat that is open in the GUI while it is being re-imported. - survive the busy case: one retry after 300 ms (the handle is released when the view switches away), then skip that session with a [busy] hint instead of failing the whole batch; every other append error still fails loud - report `busy N` in the result line plus an actionable hint - lib/persistence-facade.mjs exports isSessionBusyError (by name or message) - tests: a busy session is skipped while its siblings still update; other append errors still reject --- CHANGELOG.md | 11 +++++++++ lib/import-service.js | 39 ++++++++++++++++++++++++++++--- lib/persistence-facade.mjs | 19 +++++++++++++++ package.json | 2 +- test/import-service.test.mjs | 45 ++++++++++++++++++++++++++++++++++-- 5 files changed, 110 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e8be3ea..fa750b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 1.9.1 — 2026-11-11 + +- **Updating a chat that is open in DSH no longer aborts the whole import.** + DSH's JSONL backend keeps one write handle per Session id and refuses a second + (`session "…" is already owned by an active write handle`), which is exactly + what happens when the chat you are re-importing is open in the GUI. The + importer now retries once (the handle is released when the view switches) and + then records `[busy] …` + a hint instead of failing the batch; every other + append error still fails loud. +- Result line reports `busy N` so a partial run is visible. + ## 1.9.0 — 2026-11-11 - **Goal mode now survives the trip in both directions.** diff --git a/lib/import-service.js b/lib/import-service.js index 921c646..3fb2a61 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -26,7 +26,7 @@ import { listCodexSessions, parseCodexSession, isSubagentThread } from './codex- import { loadCodexIndex, codexTitleOf, codexProjectOf, codexProjectNameForPath, codexOriginOf, baseName } from './codex-index.mjs' import { buildDshEvents, deriveImportTitle } from './convert.mjs' import { migrateToCurrent } from './session-migrate.mjs' -import { normalizePersistence } from './persistence-facade.mjs' +import { normalizePersistence, isSessionBusyError } from './persistence-facade.mjs' import { attachSessionsToWorkspaces, listImportedSessions } from './attach-workspaces.mjs' export const DEFAULT_MAX_SESSION_BYTES = 2 * 1024 * 1024 * 1024 @@ -306,6 +306,24 @@ export function diffImportEvents(oldEvents, nextEvents) { return suffix } +/** + * Append through the persistence facade, retrying once when the Session is + * momentarily owned by another write handle (the GUI releases it as soon as the + * view switches away). A still-busy Session is reported by the caller. + * @param {object} persistence - normalized persistence + * @param {string} id - session id + * @param {Array} events - events to append + */ +async function appendWithBusyRetry(persistence, id, events) { + try { + await persistence.append(id, events) + } catch (error) { + if (!isSessionBusyError(error)) throw error + await new Promise((resolve) => setTimeout(resolve, 300)) + await persistence.append(id, events) + } +} + /** * Import codex sessions into dsh persistence. * @param {object} ctx - cordis context (reads workspaceRegistry via ctx.get). @@ -399,6 +417,7 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo let updated = 0 let skipped = 0 let empty = 0 + let busy = 0 for (const candidate of selected) { const { messages } = candidate.parsed if (messages.length === 0) { @@ -460,7 +479,18 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo lines.push(` [would-update] ${candidate.id} +${suffix.length + goalTail.length} events`) continue } - await persistence.append(candidate.id, [...suffix, ...goalTail]) + try { + await appendWithBusyRetry(persistence, candidate.id, [...suffix, ...goalTail]) + } catch (error) { + // A chat that is open in the GUI holds this Host's write handle for its + // Session, and the backend refuses a second one. Skip it (with a hint) + // instead of aborting the whole batch; other durability failures still + // fail loud. + if (!isSessionBusyError(error)) throw error + busy += 1 + lines.push(` [busy] ${candidate.id}: 该对话正在 DSH 中打开,关闭它(或切到别的对话)后重新导入本会话`) + continue + } updated += 1 lines.push(` [updated] ${candidate.id} +${suffix.length + goalTail.length} events`) continue @@ -475,7 +505,10 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo lines.push(` [imported] ${candidate.id} ${candidate.cwd ?? '(no cwd)'} ${messages.length} messages -> ${currentEvents.length} events`) } const verb = dryRun ? 'would-import' : 'imported' - lines.push(`[codex] result: ${verb} ${imported}, updated ${updated}, skipped ${skipped}, empty ${empty}, subagent-skipped ${skippedSubagent}, oversized-skipped ${skippedBig}, unreadable ${unreadable}`) + lines.push(`[codex] result: ${verb} ${imported}, updated ${updated}, skipped ${skipped}, empty ${empty}, busy ${busy}, subagent-skipped ${skippedSubagent}, oversized-skipped ${skippedBig}, unreadable ${unreadable}`) + if (busy > 0) { + lines.push(` [hint] ${busy} 个会话正在 DSH 中打开(写句柄被占用),本次未更新;关闭这些对话后重新导入即可补齐`) + } if (skippedSubagent > 0) { lines.push(` [hint] ${skippedSubagent} codex 子代理线程已过滤(默认,避免会话列表塞满); 需要时用 /import-codex --include-subagents 或配置 importSubagents: true`) } diff --git a/lib/persistence-facade.mjs b/lib/persistence-facade.mjs index 5977aee..18bf8ff 100644 --- a/lib/persistence-facade.mjs +++ b/lib/persistence-facade.mjs @@ -119,6 +119,25 @@ function wrapLegacy(persistence) { }) } +/** + * True when a write was refused because the Session is already open for + * writing in this Host process. + * + * DSH's JSONL backend keeps one write handle per Session id (`claimWrite` + * throws `SessionAlreadyOwnedError`). A chat that is open in the GUI holds that + * handle, so a re-import cannot append to it until the chat is closed or the + * view switches away. `SessionAlreadyExistsError` shows up the same way when a + * concurrent create still owns the id — for an import both mean "in use". + * @param {unknown} error + * @returns {boolean} + */ +export function isSessionBusyError(error) { + const name = error?.name + if (name === 'SessionAlreadyOwnedError' || name === 'SessionAlreadyExistsError') return true + const message = typeof error?.message === 'string' ? error.message : '' + return message.includes('already owned by an active write handle') || message.includes('already exists') +} + /** * Return the plugin's familiar persistence API for a DSH service object. * @param {object|null|undefined} persistence - the service from `ctx.get('sessionPersistence')`. diff --git a/package.json b/package.json index 441500d..0f1751b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.9.0", + "version": "1.9.1", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index a9749c3..042160e 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -99,7 +99,7 @@ test('import-codex: sub-agent threads are filtered by default', async () => { const lines = await importCodex(ctx, persistence, {}, root) const report = lines.join('\n') - assert.match(report, /\[codex\] result: imported 1, updated 0, skipped 0, empty 0, subagent-skipped 1/) + assert.match(report, /\[codex\] result: imported 1, updated 0, skipped 0, empty 0, busy 0, subagent-skipped 1/) assert.ok(store.has(main), 'main session imported') assert.ok(!store.has(sub), 'sub-agent thread must NOT be imported by default') assert.equal(metas.get(main)?.agentPreset, 'cordis', 'imported sessions resume under the working cordis preset') @@ -153,6 +153,47 @@ test('import-codex: re-import follows a Codex goal that changed to paused', asyn assert.equal(goals[1].data.goal.revision, 2) }) +test('import-codex: a chat open in the GUI (active write handle) is skipped, not fatal', async () => { + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-busy-')) + const busyId = makeSession(root, 'busy') + const freeId = makeSession(root, 'free') + const { persistence, ctx, store } = stubPersistence() + // Both already imported; both gained a Codex turn that must be appended. + store.set(busyId, []) + store.set(freeId, []) + appendMessages(root, 'busy', [{ role: 'user', text: 'user-busy-2' }]) + appendMessages(root, 'free', [{ role: 'user', text: 'user-free-2' }]) + + // DSH keeps ONE write handle per Session id; an open chat owns it. + const realAppend = persistence.append.bind(persistence) + persistence.append = async (id, events) => { + if (id === busyId) { + const error = new Error(`session "${id}" is already owned by an active write handle`) + error.name = 'SessionAlreadyOwnedError' + throw error + } + return realAppend(id, events) + } + + const lines = await importCodex(ctx, persistence, {}, root) + const report = lines.join('\n') + assert.match(report, /busy 1/, 'the busy session is counted, the batch is not aborted') + assert.match(report, /\[busy\] codex-sess-busy: 该对话正在 DSH 中打开/) + assert.match(report, /updated 1/, 'the other session still updated') + assert.equal(store.get(busyId).length, 0, 'busy session untouched') + assert.ok(store.get(freeId).length > 0, 'free session appended') +}) + +test('import-codex: other append failures still fail loud', async () => { + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-flush2-')) + const id = makeSession(root, 'boom') + const { persistence, ctx, store } = stubPersistence() + store.set(id, []) + appendMessages(root, 'boom', [{ role: 'user', text: 'user-boom-2' }]) + persistence.append = async () => { throw new Error('disk full') } + await assert.rejects(() => importCodex(ctx, persistence, {}, root), /disk full/) +}) + test('catalog: nests sub-agents under parent and marks imported', async () => { const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) const mainId = makeSession(root, 'main') @@ -196,7 +237,7 @@ test('import-codex: dryRun lists candidates but writes nothing', async () => { const report = lines.join('\n') assert.match(report, /\[codex\] dry-run: no sessions will be written/) assert.ok(report.includes(`[would-import] ${main}`), 'dry-run lists the main session') - assert.match(report, /would-import 1, updated 0, skipped 0, empty 0, subagent-skipped 1/) + assert.match(report, /would-import 1, updated 0, skipped 0, empty 0, busy 0, subagent-skipped 1/) assert.equal(store.size, 0, 'dry-run must not create sessions') }) From f2981d2121cbc31a64f1947fb5940e5c32203bda Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 14:47:46 +0800 Subject: [PATCH 05/18] =?UTF-8?q?fix:=201.9.2=20=E2=80=94=20imported=20cha?= =?UTF-8?q?ts=20no=20longer=20open=20in=20=E5=88=9B=E9=80=A0=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The importer hardcoded `agentPreset: 'cordis'` in the Session header, and `cordis` is the built-in 创造模式 (plugin-authoring) preset, so every chat synced from Codex opened in it. DSH fixes a session's preset at creation (`agentPresetProjectionDefinition.init` reads the header; later changes need an `agent-preset/selected` event and are only allowed while the session is blank). - default imported sessions to `standard` (标准模式) (`DEFAULT_IMPORT_AGENT_PRESET` in lib/import-service.js) - keep it selectable: `config.importAgentPreset`, or `/import-codex --preset ptc` - lib/dsh-writer.mjs writes the same default - tests: default is `standard`; an explicit preset wins --- CHANGELOG.md | 11 +++++++++++ lib/dsh-writer.mjs | 2 +- lib/import-service.js | 10 +++++++++- lib/index.js | 7 +++++-- package.json | 2 +- test/import-service.test.mjs | 16 +++++++++++++++- 6 files changed, 42 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa750b0..4cb512b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 1.9.2 — 2026-11-12 + +- **Imported chats no longer land in 创造模式 (the `cordis` agent preset).** + The import hardcoded `agentPreset: 'cordis'` in the Session header, so every + chat synced from Codex opened in DSH's plugin-authoring preset. Imports now + default to `standard` (标准模式) and accept a preset override: + `config.importAgentPreset`, or `/import-codex --preset ptc`. The same default + is used by `lib/dsh-writer.mjs` for CLI-side writes. + A preset is fixed at session creation, so chats imported by an older version + must be deleted and re-imported to change it. + ## 1.9.1 — 2026-11-11 - **Updating a chat that is open in DSH no longer aborts the whole import.** diff --git a/lib/dsh-writer.mjs b/lib/dsh-writer.mjs index 55a7390..e237bbf 100644 --- a/lib/dsh-writer.mjs +++ b/lib/dsh-writer.mjs @@ -81,7 +81,7 @@ export function writeSession(root, header, events) { createdAt: header.createdAt, ...(header.cwd !== undefined ? { cwd: header.cwd } : {}), delegationDepth: 0, - agentPreset: header.agentPreset || 'cordis', + agentPreset: header.agentPreset || 'standard', } const lines = [JSON.stringify(headerLine)] for (let seq = 0; seq < events.length; seq++) { diff --git a/lib/import-service.js b/lib/import-service.js index 3fb2a61..5159867 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -30,6 +30,14 @@ import { normalizePersistence, isSessionBusyError } from './persistence-facade.m import { attachSessionsToWorkspaces, listImportedSessions } from './attach-workspaces.mjs' export const DEFAULT_MAX_SESSION_BYTES = 2 * 1024 * 1024 * 1024 +/** + * Agent preset imported sessions run under. DSH names the built-in presets + * `standard` (标准模式), `ptc`, `minimal` and `cordis` (创造模式); the preset is + * fixed at session creation and decides which tools and prompt sections the + * session gets, so an import must not silently place every Codex chat in the + * plugin-authoring (创造模式) preset. + */ +export const DEFAULT_IMPORT_AGENT_PRESET = 'standard' /** * Rewrite the JSONL/db title helpers into one index-backed lookup. @@ -446,7 +454,7 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo ...(candidate.cwd !== undefined ? { cwd: candidate.cwd } : {}), agentPreset: typeof options.agentPreset === 'string' && options.agentPreset.length > 0 ? options.agentPreset - : 'cordis', + : DEFAULT_IMPORT_AGENT_PRESET, } // Fail LOUDLY instead of falling back to a v0 write: real DSH persistence // rejects v0 anyway ("encodeCurrent requires Session format v3"/"v4"), so diff --git a/lib/index.js b/lib/index.js index 0b56a36..2211bd3 100644 --- a/lib/index.js +++ b/lib/index.js @@ -178,7 +178,7 @@ export function apply(ctx, config = {}) { if (persistence === undefined) { return { kind: 'success', text: 'sessionPersistence 服务未加载,无法导入' } } - const lines = await importCodex(ctx, persistence, { importSubagents: config.importSubagents === true }, codexHome) + const lines = await importCodex(ctx, persistence, { importSubagents: config.importSubagents === true, agentPreset: config.importAgentPreset }, codexHome) return { kind: 'success', text: lines.join('\n') } } @@ -258,6 +258,9 @@ export function apply(ctx, config = {}) { if (typeof options.ids === 'string' && options.ids.length > 0) { options.ids = options.ids.split(',').map((s) => s.trim()).filter(Boolean) } + if (typeof options.preset === 'string' && options.preset.length > 0) { + options.agentPreset = options.preset + } if (options.list === true || options['list'] === true) { const catalog = await listImportCatalog(persistence, options, codexHome) return { kind: 'success', text: JSON.stringify(catalog, null, 2) } @@ -793,7 +796,7 @@ export function apply(ctx, config = {}) { const ids = Array.isArray(payload.ids) ? payload.ids.map(String) : [] const includeSubagents = payload.includeSubagents === true try { - const lines = await importCodex(inner, persistence, { ids, importSubagents: includeSubagents }, codexHome) + const lines = await importCodex(inner, persistence, { ids, importSubagents: includeSubagents, agentPreset: config.importAgentPreset }, codexHome) sendJson(res, 200, { ok: true, text: lines.join('\n') }) } catch (error) { sendJson(res, 500, { error: String(error?.message ?? error) }) diff --git a/package.json b/package.json index 0f1751b..c28b00b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.9.1", + "version": "1.9.2", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index 042160e..9929dd0 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -102,10 +102,24 @@ test('import-codex: sub-agent threads are filtered by default', async () => { assert.match(report, /\[codex\] result: imported 1, updated 0, skipped 0, empty 0, busy 0, subagent-skipped 1/) assert.ok(store.has(main), 'main session imported') assert.ok(!store.has(sub), 'sub-agent thread must NOT be imported by default') - assert.equal(metas.get(main)?.agentPreset, 'cordis', 'imported sessions resume under the working cordis preset') + assert.equal(metas.get(main)?.agentPreset, 'standard', 'imported sessions use the standard preset, not 创造模式') assert.match(report, /--include-subagents/, 'report hints the opt-in flag') }) +test('import-codex: the imported agent preset is selectable', async () => { + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-preset-')) + const id = makeSession(root, 'preset') + const { persistence, ctx, metas } = stubPersistence() + + await importCodex(ctx, persistence, { agentPreset: 'ptc' }, root) + assert.equal(metas.get(id)?.agentPreset, 'ptc', 'explicit preset wins') + + const other = makeSession(root, 'preset2') + const second = stubPersistence() + await importCodex(second.ctx, second.persistence, {}, root) + assert.equal(second.metas.get(other)?.agentPreset, 'standard', 'default stays standard') +}) + test('import-codex: an unfinished Codex goal becomes an active DSH goal', async () => { const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-goal-')) const id = makeSession(root, 'goal') From 1df3e1e8cdc77962df191a6efda8a2fab047bb69 Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 14:57:55 +0800 Subject: [PATCH 06/18] =?UTF-8?q?fix:=201.9.3=20=E2=80=94=20the=20replayed?= =?UTF-8?q?=20goal=20chain=20must=20pass=20DSH's=20goal=20fold?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `@deepseek-ai/dsh-goal` validates a goal log strictly: `create` must be revision 1, phase active, zero rounds; every later change is exactly revision+1 and keeps `createdAt` and `roundsStarted`; `pause`/`block` only apply to an active goal; `resume` is the only path back to active; and a goal id may be created ONCE per session (`seenGoalIds`). The importer broke the last rule in two ways, so the goal projection on re-imported chats failed with "goal create requires a fresh active revision-one goal with zero rounds" and goal mode never took effect: - `diffImportEvents` slices the rebuilt log up to its end, so the trailing goal `create` came back with every re-imported turn → duplicate create. Goal events are now filtered out of the diffed suffix (they are appended only by the goal helper). - a Codex goal that moved back to active was written as a second `create` instead of `resume`. Re-imports now read the stored goal (phase, revision, createdAt, updatedAt) back from the log and continue it with the transitions the fold admits; an impossible move out of `complete` appends nothing. Tests exercise the real fold: create → pause → blocked → resume must stay admissible (operations and revisions asserted), and a re-imported turn must not duplicate the create. Verified on the real rollout that failed before: one `create#1:active`, `foldGoal` accepts it. --- CHANGELOG.md | 20 ++++ lib/import-service.js | 176 ++++++++++++++++++++--------------- package.json | 2 +- test/import-service.test.mjs | 56 +++++++++++ 4 files changed, 177 insertions(+), 77 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4cb512b..6cbb245 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 1.9.3 — 2026-11-12 + +- **The replayed goal chain is now admissible for DSH's real goal fold.** + `@deepseek-ai/dsh-goal` validates strictly: `create` must be revision 1 / phase + active / zero rounds, every later change is exactly revision + 1 and preserves + `createdAt` + `roundsStarted`, `pause`/`block` only apply to an active goal, + `resume` is the only way back to active, and a goal id may be created only + once per session (`seenGoalIds`). The importer violated the last rule twice: + a re-import whose diffed suffix spanned the rebuilt log re-appended the goal + `create` (⇒ `goal create requires a fresh active revision-one goal with zero + rounds`, which left the goal projection broken), and a Codex goal that changed + back to active was written as a second `create` instead of `resume`. + Now: goal events never travel in the diffed suffix (`diffImportEvents` filters + them), re-imports read the stored goal back from the log and continue it + (`resume`/`pause`/`block`/`complete` with the right revision), and an + impossible move (anything out of `complete`) appends nothing. +- Tests fold the produced log with the **real** `foldGoal` from + `@deepseek-ai/dsh-goal` — create → pause → blocked → resume stays admissible — + plus a regression test that a re-imported turn does not duplicate the create. + ## 1.9.2 — 2026-11-12 - **Imported chats no longer land in 创造模式 (the `cordis` agent preset).** diff --git a/lib/import-service.js b/lib/import-service.js index 5159867..276e343 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -49,104 +49,128 @@ function resolveImportTitle(codexHome, rawId, headerTitle, messages) { } /** - * Replay a Codex goal as the `goal/change` events DSH's goal service reads. + * Codex goal status → the DSH goal phase it stands for. Unknown statuses are + * treated as `active` so an unfinished goal is never silently dropped. + * @param {string|undefined} status + * @returns {'active'|'paused'|'blocked'|'complete'} + */ +function codexGoalPhase(status) { + const wanted = String(status ?? 'active').toLowerCase() + if (wanted === 'paused') return 'paused' + if (wanted === 'complete' || wanted === 'completed') return 'complete' + if (wanted === 'blocked') return 'blocked' + return 'active' +} + +/** + * Operations that move an existing goal from `from` to `to`, following the + * transitions `@deepseek-ai/dsh-goal`'s fold admits: `pause` only from active, + * `block` only from active, `resume` only into active, `complete` from any + * phase except complete. Blocked/paused therefore resume first. + * @returns {string[]|undefined} operations, or undefined when the move is impossible + */ +function goalOperations(from, to) { + if (from === to) return [] + if (from === 'complete') return undefined + if (to === 'complete') return ['complete'] + const ops = [] + if (from === 'paused' || from === 'blocked') ops.push('resume') + if (to === 'paused') ops.push('pause') + else if (to === 'blocked') ops.push('block') + return ops +} + +/** + * Replay a Codex goal as the `goal/change` events DSH's goal service folds. * - * Codex stores one snapshot per mutation (`thread_goal_updated`), so the import - * only needs the final state: `create` (always, phase active because that is how - * DSH accepts a new goal) followed by the transition that reaches the recorded - * status — `pause`, `resume`, `complete`. `blocked` maps to `block`. + * The fold is strict, so this must reproduce an admissible log rather than a + * plausible one: `create` is only accepted as revision 1 / phase active / zero + * rounds, every later change is exactly revision+1 and preserves `createdAt` + * and `roundsStarted`, and a goal id may only be created once per session + * (`seenGoalIds`). When `previous` names the goal already stored in the session, + * the chain continues from it instead of creating a second goal. * - * `blocked`/`complete` keep their semantic; unknown Codex statuses are treated - * as active so an unfinished goal is never silently dropped. * @param {string} sessionId * @param {{objective: string, status: string, createdAt?: number, updatedAt?: number}} | undefined goal * @param {number} time - fallback timestamps (ms) + * @param {{phase: string, revision: number, createdAt: number, updatedAt: number}} [previous] * @returns {Array} goal/change events (seq assigned by the caller) */ -function codexGoalEvents(sessionId, goal, time) { +function codexGoalEvents(sessionId, goal, time, previous) { if (goal === undefined) return [] const objective = String(goal.objective ?? '').trim() if (objective.length === 0) return [] - const createdAt = goal.createdAt ?? time - const updatedAt = goal.updatedAt ?? time + const target = codexGoalPhase(goal.status) + const ops = goalOperations(previous === undefined ? 'active' : previous.phase, target) + if (ops === undefined) return [] const id = `goal-${sessionId}` - const base = { - id, - revision: 1, - objective, - phase: 'active', - maxGoalRounds: 256, - } - const events = [{ - type: 'goal/change', - time: createdAt, - data: { kind: 'goal/change', version: 1, operation: 'create', goal: { ...base }, roundsStarted: 0, createdAt, updatedAt: createdAt }, - }] - const status = String(goal.status ?? 'active').toLowerCase() - const transition = status === 'paused' - ? { operation: 'pause', phase: 'paused' } - : status === 'complete' || status === 'completed' - ? { operation: 'complete', phase: 'complete' } - : status === 'blocked' - ? { operation: 'block', phase: 'blocked' } - : undefined - if (transition === undefined) return events - events.push({ - type: 'goal/change', - time: updatedAt, - data: { - kind: 'goal/change', - version: 1, - operation: transition.operation, - goal: { - ...base, - revision: 2, - phase: transition.phase, - ...(transition.phase === 'blocked' - ? { blockedReason: { code: 'imported', message: 'Codex 侧目标处于 blocked 状态(导入时保留)' } } - : {}), + const createdAt = previous === undefined ? (goal.createdAt ?? time) : previous.createdAt + const wantedAt = Math.max(goal.updatedAt ?? time, createdAt) + const events = [] + let revision = previous === undefined ? 0 : previous.revision + let cursor = previous === undefined ? createdAt : Math.max(previous.updatedAt, createdAt) + const push = (operation, phase, at) => { + revision += 1 + events.push({ + type: 'goal/change', + time: at, + data: { + kind: 'goal/change', + version: 1, + operation, + goal: { + id, + revision, + objective, + phase, + maxGoalRounds: 256, + ...(phase === 'blocked' + ? { blockedReason: { code: 'imported', message: 'Codex 侧目标处于 blocked 状态(导入时保留)' } } + : {}), + }, + roundsStarted: 0, + createdAt, + updatedAt: at, }, - roundsStarted: 0, - createdAt, - updatedAt, - }, - }) + }) + } + if (previous === undefined) push('create', 'active', createdAt) + for (const operation of ops) { + cursor = Math.max(cursor, wantedAt) + if (operation === 'resume') push('resume', 'active', cursor) + else if (operation === 'pause') push('pause', 'paused', cursor) + else if (operation === 'block') push('block', 'blocked', cursor) + else if (operation === 'complete') push('complete', 'complete', cursor) + } return events } /** * Goal events to append to an ALREADY imported session so it follows a Codex - * goal change: no goal stored yet → the full `create` (+ transition); stored - * phase already matches → nothing; otherwise only the transition. + * goal change. The stored goal (if any) is read back from the session log, so a + * re-import continues that goal instead of creating a second one. * + * @param {string} sessionId * @param {Array} oldEvents - what the DSH session already holds * @param {object|undefined} goal - the Codex goal snapshot * @param {number} time - fallback timestamp (ms) */ -function codexGoalSyncEvents(oldEvents, goal, time) { +function codexGoalSyncEvents(sessionId, oldEvents, goal, time) { if (goal === undefined) return [] const stored = [...oldEvents].reverse().find((event) => event?.type === 'goal/change') - if (stored === undefined) return codexGoalEvents('', goal, time).map((event) => { - // id is rewritten by the caller (needs the session id) - return { ...event, data: { ...event.data, goal: { ...event.data.goal } } } - }) - const storedPhase = stored.data?.goal?.phase - const full = codexGoalEvents('', goal, time) - const status = String(goal.status ?? 'active').toLowerCase() - const wanted = status === 'paused' - ? 'paused' - : status === 'complete' || status === 'completed' - ? 'complete' - : status === 'blocked' - ? 'blocked' - : 'active' - if (storedPhase === wanted) return [] - const revision = (typeof stored.data?.goal?.revision === 'number' ? stored.data.goal.revision : 1) + 1 - const transition = full[full.length - 1] - return [{ - ...transition, - data: { ...transition.data, goal: { ...transition.data.goal, revision } }, - }] + const previous = stored === undefined ? undefined : { + phase: stored.data?.goal?.phase, + revision: stored.data?.goal?.revision, + createdAt: stored.data?.createdAt, + updatedAt: stored.data?.updatedAt, + } + if (previous !== undefined && (typeof previous.phase !== 'string' + || typeof previous.revision !== 'number' + || typeof previous.createdAt !== 'number' + || typeof previous.updatedAt !== 'number')) { + return [] + } + return codexGoalEvents(sessionId, goal, time, previous) } /** Project label for one thread: Codex's project name, else the cwd's folder. */ @@ -239,7 +263,7 @@ export function diffImportEvents(oldEvents, nextEvents) { const oldTurn = lastTurnNumber(oldEvents) const remap = (slice, turnOffset, seqBase) => slice - .filter((e) => e.type !== 'session/title') + .filter((e) => e.type !== 'session/title' && e.type !== 'goal/change') .map((event, i) => { const data = event.data && typeof event.data === 'object' ? { ...event.data } : event.data if (data && typeof data.turn === 'number') data.turn = data.turn + turnOffset @@ -476,7 +500,7 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo continue } const suffix = diffImportEvents(oldEvents, currentEvents) - const goalTail = codexGoalSyncEvents(oldEvents, candidate.parsed.header.goal, lastMessageTime) + const goalTail = codexGoalSyncEvents(candidate.id, oldEvents, candidate.parsed.header.goal, lastMessageTime) .map((event, i) => ({ ...event, seq: (suffix[suffix.length - 1]?.seq ?? oldEvents[oldEvents.length - 1]?.seq ?? 0) + 1 + i })) if (suffix.length === 0 && goalTail.length === 0) { skipped += 1 diff --git a/package.json b/package.json index c28b00b..2a5a0aa 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.9.2", + "version": "1.9.3", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index 9929dd0..0928370 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -11,6 +11,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, appendFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { importCodex, listImportCatalog } from '../lib/import-service.js' +import { foldGoal } from '@deepseek-ai/dsh-goal' // Build a raw response_item event (NOT a string) so the file body below can be // JSON.stringify'd exactly once per line. @@ -140,6 +141,61 @@ test('import-codex: an unfinished Codex goal becomes an active DSH goal', async assert.equal(goals[1].data.goal.phase, 'paused') }) +test('import-codex: the goal chain is accepted by the real DSH goal fold', async () => { + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-goalfold-')) + const id = makeSession(root, 'goalfold') + const goalLine = (status, updatedAt) => JSON.stringify({ + type: 'event_msg', + timestamp: '2026-08-17T10:00:04.000Z', + payload: { type: 'thread_goal_updated', threadId: 'sess-goalfold', goal: { threadId: 'sess-goalfold', objective: '让目标真的生效', status, createdAt: 1787000000, updatedAt } }, + }) + const file = join(root, 'sessions', '2026', '08', '17', 'rollout-goalfold.jsonl') + appendFileSync(file, goalLine('active', 1787000100) + '\n') + const { persistence, ctx, store } = stubPersistence() + + // First import: create only. + await importCodex(ctx, persistence, {}, root) + // Codex pauses, then blocks, then resumes: every hop must stay admissible. + for (const [status, at] of [['paused', 1787000200], ['blocked', 1787000300], ['active', 1787000400]]) { + appendFileSync(file, goalLine(status, at) + '\n') + await importCodex(ctx, persistence, {}, root) + const fold = foldGoal(store.get(id) ?? []) + assert.equal(fold.goal?.id, `goal-${id}`) + assert.equal(fold.goal?.phase, status) + } + const goals = (store.get(id) ?? []).filter((e) => e.type === 'goal/change') + assert.deepEqual(goals.map((e) => e.data.operation), ['create', 'pause', 'resume', 'block', 'resume']) + assert.deepEqual(goals.map((e) => e.data.goal.revision), [1, 2, 3, 4, 5]) +}) + +test('import-codex: a re-imported new turn does not duplicate the goal create', async () => { + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-goaldup-')) + const id = makeSession(root, 'goaldup') + const file = join(root, 'sessions', '2026', '08', '17', 'rollout-goaldup.jsonl') + appendFileSync(file, JSON.stringify({ + type: 'event_msg', + timestamp: '2026-08-17T10:00:04.000Z', + payload: { type: 'thread_goal_updated', threadId: 'sess-goaldup', goal: { threadId: 'sess-goaldup', objective: '不要重复创建', status: 'active', createdAt: 1787000000, updatedAt: 1787000100 } }, + }) + '\n') + const { persistence, ctx, store } = stubPersistence() + await importCodex(ctx, persistence, {}, root) + + // Codex continues the thread: the diffed suffix also spans the trailing goal + // events of the rebuilt log, so the goal create must be filtered out of it — + // a goal id may only be created once per session. + appendMessages(root, 'goaldup', [ + { role: 'user', text: 'user-goaldup-2' }, + { role: 'assistant', text: 'assistant-goaldup-2' }, + ]) + + await importCodex(ctx, persistence, {}, root) + const goals = (store.get(id) ?? []).filter((e) => e.type === 'goal/change') + assert.equal(goals.length, 1, 'no duplicate create on re-import') + const fold = foldGoal(store.get(id) ?? []) + assert.equal(fold.goal?.phase, 'active') + assert.equal(fold.goal?.revision, 1) +}) + test('import-codex: re-import follows a Codex goal that changed to paused', async () => { const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-goal2-')) const id = makeSession(root, 'goal2') From 9c6f223ccb617db597da54c21eba6de11dd893b7 Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 15:15:01 +0800 Subject: [PATCH 07/18] =?UTF-8?q?feat:=201.10.0=20=E2=80=94=20=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=B7=B2=E5=90=8C=E6=AD=A5=E5=AF=B9=E8=AF=9D=EF=BC=88?= =?UTF-8?q?=E6=8C=89=E9=A1=B9=E7=9B=AE=E5=88=86=E7=BB=84=EF=BC=8C=E5=8B=BE?= =?UTF-8?q?=E9=80=89=E5=88=A0=E9=99=A4=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DSH 没有删除 Session 的接口(workspace 控制器只有 archive/unarchive/pin/unpin), 所以「归档」之后会话文件仍在,重新导入仍会被判定为已存在。新增面板把这件事做对: - client: ImportPicker 增加 manage 模式(同步设置 → 管理已同步),复用导入视图的 项目分组/搜索/三态勾选框,底部按钮换成红色「删除 N」,删前二次确认;行内不再重复 标注「已导入」,只保留「有更新」。 - host: GET /dsh-codex-sync/catalog?only=imported 只返回已导入线程 (listImportCatalog 新增 onlyImported),POST /dsh-codex-sync/delete 走 lib/delete-imported.mjs。 - lib/delete-imported.mjs: 删除会话目录 + projection 缓存,并在删除前通过 workspaceRegistry.unarchiveSession 清掉归档标记(否则同 id 重导会被隐藏; SQLite 索引按「索引有、磁盘无」自行收敛)。只允许 codex- 前缀;正在 DSH 中打开的 会话拒绝删除;不在存储里的 id 记为 missing;dryRun 只报告不动手;Codex 原始对话 永不触碰。 - tests: 6 个新用例(删除产物+缓存+归档标记、拒绝原生会话、拒绝正在打开的会话、 missing、dryRun、路径定位),全套 88 项。 --- CHANGELOG.md | 19 +++++ lib/client.js | 132 ++++++++++++++++++++++++++++------ lib/delete-imported.mjs | 128 +++++++++++++++++++++++++++++++++ lib/import-service.js | 5 +- lib/index.js | 26 ++++++- package.json | 2 +- scripts/run-tests.mjs | 1 + test/delete-imported.test.mjs | 114 +++++++++++++++++++++++++++++ 8 files changed, 404 insertions(+), 23 deletions(-) create mode 100644 lib/delete-imported.mjs create mode 100644 test/delete-imported.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cbb245..cd1480c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 1.10.0 — 2026-11-12 + +- **New: 管理已同步 (manage synced chats)** — a picker that lists the chats this + plugin imported, grouped by Codex project exactly like the import view, with + checkboxes and a delete button (Sync settings → 管理已同步). + DSH itself has **no** delete-Session API — the workspace controller only + offers archive/unarchive/pin/unpin — so `archive` keeps the artifact and a + later re-import still sees the old Session. This panel removes it for real: + the session directory, its projection-cache entry, and the archive flag (the + SQLite index reconciles itself). + Safety: only `codex-*` ids are accepted (a chat created in DSH can never be + removed this way), a chat that is open in DSH is refused instead of deleted, + ids that are not in the store are reported as missing, and `dryRun` reports + without touching anything. The Codex original is never touched. +- Host: `GET /dsh-codex-sync/catalog?only=imported` (catalog restricted to + already-imported threads), `POST /dsh-codex-sync/delete` → `lib/delete-imported.mjs`. +- Tests: 6 new cases (removal + cache + archive flag, native-session refusal, + open-chat refusal, missing id, dryRun, path lookup). 88 total. + ## 1.9.3 — 2026-11-12 - **The replayed goal chain is now admissible for DSH's real goal fold.** diff --git a/lib/client.js b/lib/client.js index f55947d..9b8ef72 100644 --- a/lib/client.js +++ b/lib/client.js @@ -233,6 +233,12 @@ const Icons = { chat: () => svgIcon([ h('path', { key: 1, d: 'M7.9 20A9 9 0 1 0 4 16.1L2 22Z' }) ], '0 0 24 24', 12), + trash: () => svgIcon([ + h('polyline', { key: 1, points: '3 6 5 6 21 6' }), + h('path', { key: 2, d: 'M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6' }), + h('path', { key: 3, d: 'M10 11v6M14 11v6' }), + h('path', { key: 4, d: 'M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2' }) + ], '0 0 24 24', 13), chevronRight: () => svgIcon([ h('polyline', { key: 1, points: '9 18 15 12 9 6' }) ], '0 0 24 24', 11), @@ -920,6 +926,10 @@ const ACTION_INFO = { zh: '重新从宿主机读取所有同步开关与配置的最新真实值并刷新界面。', en: 'Re-sync all switch states and configuration values from the host.', }, + manage: { + zh: '按项目列出本插件从 Codex 同步进来的对话,勾选后可删除 DSH 侧会话(Codex 原始对话不受影响,可重新导入)。', + en: 'Lists the chats synced from Codex by project, with checkboxes to delete the DSH copy. The original Codex thread is untouched and can be imported again.', + }, } /** Per-setting explainers shown by the ⓘ icon (bilingual). */ @@ -1017,6 +1027,15 @@ function labels(lang) { descMcpMirror: '监听 ~/.codex/config.toml 的 [mcp_servers.*] 并镜像到 DSH,支持逐项开关与热启停。', pickerTitle: '导入 Codex 会话', pickerTitleExport: '导出 DSH 会话到 Codex', + pickerTitleManage: '管理已同步的对话', + manageNow: '管理已同步', + descManageNow: '列出本插件从 Codex 同步进来的对话(按项目分组),勾选后可删除;删除只影响 DSH 侧,不会改动 Codex 原始会话。', + deleteN: '删除', + confirmDeleteTitle: '确认删除已同步对话', + confirmDeleteBody: (count) => `即将删除 ${count} 个已同步到 DSH 的对话。这会移除 DSH 侧会话文件与其缓存,Codex 里的原始对话不受影响,之后可以重新导入。删除后如果侧边栏还显示旧条目,重启 dsh 即可。`, + confirmDeleteBtn: '确认删除', + deletedOk: '已删除已同步对话', + deleteHint: 'DSH 侧的会话文件已移除,Codex 原始对话保持不动。若侧边栏仍显示旧条目,重启 dsh 后消失。', confirmExportTitle: '确认导出', confirmExportBody: (count) => `即将导出 ${count} 个会话。由于插件无法覆盖或追加原 Codex 对话,导出将创建全新的 Codex 会话副本;子代理会话将作为独立会话导出,无法与父会话合并。导出的对话重启 Codex 可见。`, confirmExportBtn: '确认导出', @@ -1100,6 +1119,15 @@ function labels(lang) { descMcpMirror: 'Mirrors [mcp_servers.*] from ~/.codex/config.toml with per-item switches and hot start/stop.', pickerTitle: 'Import Codex sessions', pickerTitleExport: 'Export DSH sessions to Codex', + pickerTitleManage: 'Manage synced chats', + manageNow: 'Manage synced', + descManageNow: 'Lists the chats this plugin synced from Codex, grouped by project, with checkboxes to delete. Deletion only touches the DSH side; the original Codex thread is untouched.', + deleteN: 'Delete', + confirmDeleteTitle: 'Confirm deletion', + confirmDeleteBody: (count) => `About to delete ${count} synced chat(s) from DSH. This removes the DSH session files and their caches; the original Codex threads are untouched and can be imported again later. If the sidebar still lists them, restart dsh.`, + confirmDeleteBtn: 'Delete', + deletedOk: 'Synced chats removed', + deleteHint: 'The DSH session files were removed; the Codex originals are untouched. Restart dsh if the sidebar still lists them.', confirmExportTitle: 'Confirm export', confirmExportBody: (count) => `About to export ${count} session(s). Because the plugin cannot overwrite or append to original Codex threads, exporting will create new, independent Codex conversation copies; subagents will export separately and cannot merge into parent sessions. Exported conversations will be visible after restarting Codex.`, confirmExportBtn: 'Confirm export', @@ -1189,7 +1217,8 @@ function walkSessions(nodes, fn) { } } -function isNodeSelectable(n, isExport) { +function isNodeSelectable(n, isExport, isManage) { + if (isManage) return n.imported === true if (isExport) { if (n.isCodexWorkspace === false) return false if (n.alreadyCodex || n.fromCodex) { @@ -1200,11 +1229,11 @@ function isNodeSelectable(n, isExport) { return !n.alreadyCodex && (!n.imported || n.stale) } -function collectSelectable(projects, isExport = false) { +function collectSelectable(projects, isExport = false, isManage = false) { const ids = [] for (const p of projects || []) { walkSessions(p.sessions, (n) => { - if (isNodeSelectable(n, isExport)) ids.push(n.id) + if (isNodeSelectable(n, isExport, isManage)) ids.push(n.id) }) } return ids @@ -1284,6 +1313,7 @@ function TriBox({ state, disabled }) { function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { const t = labels(lang) const isExport = mode === 'export' + const isManage = mode === 'manage' const [hideSub, setHideSub] = useState(true) const [showCodex, setShowCodex] = useState(false) const [query, setQuery] = useState('') @@ -1300,14 +1330,14 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { try { const url = isExport ? `/dsh-codex-sync/export-catalog?includeCodex=${includeCodex ? '1' : '0'}&includeSubagents=${includeSubagents ? '1' : '0'}` - : `/dsh-codex-sync/catalog?includeSubagents=${includeSubagents ? '1' : '0'}` + : `/dsh-codex-sync/catalog?includeSubagents=${includeSubagents ? '1' : '0'}${isManage ? '&only=imported' : ''}` const res = await fetch(url, { credentials: 'same-origin' }) const data = await res.json().catch(() => null) if (!res.ok || !data || !Array.isArray(data.projects)) { throw new Error((data && data.error) || String(res.status)) } setCatalog(data) - const validSelectable = new Set(collectSelectable(data.projects, isExport)) + const validSelectable = new Set(collectSelectable(data.projects, isExport, isManage)) setSelected((prev) => { const next = {} for (const id of Object.keys(prev)) { @@ -1325,7 +1355,7 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { useEffect(() => { void load(!hideSub, showCodex) }, [hideSub, showCodex, isExport]) const projects = filterCatalog(catalog?.projects, query) - const selectable = collectSelectable(projects, isExport) + const selectable = collectSelectable(projects, isExport, isManage) const selectedCount = selectable.filter((id) => selected[id]).length const allState = triState(selectedCount, selectable.length) @@ -1333,7 +1363,7 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { setSelected((prev) => { const next = Object.assign({}, prev) walkSessions(nodes, (n) => { - if (isNodeSelectable(n, isExport)) next[n.id] = on + if (isNodeSelectable(n, isExport, isManage)) next[n.id] = on }) return next }) @@ -1379,6 +1409,34 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { } } + const executeDelete = async () => { + const ids = selectable.filter((id) => selected[id]) + if (ids.length === 0 || busy) return + setBusy(true) + setError(null) + try { + const res = await fetch('/dsh-codex-sync/delete', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ids }), + credentials: 'same-origin', + }) + const data = await res.json().catch(() => null) + if (!res.ok || !data?.ok) { + throw new Error(data?.error || String(res.status)) + } + setBusy(false) + setConfirmingExport(false) + setDone(true) + setSelected({}) + void load(!hideSub, showCodex) + } catch (e) { + setBusy(false) + setConfirmingExport(false) + setError(e?.message || t.error) + } + } + const executeImport = async (ids) => { if (ids.length === 0 || busy) return setBusy(true) @@ -1420,6 +1478,10 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { const onConfirmClick = () => { const ids = selectable.filter((id) => selected[id]) if (ids.length === 0 || busy) return + if (isManage) { + setConfirmingExport(true) + return + } if (isExport) { setConfirmingExport(true) return @@ -1430,10 +1492,10 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { const renderNodes = (nodes, depth) => nodes.map((n) => { const hasKids = (n.children || []).length > 0 const open = expanded[n.id] === true - const selfSelectable = isNodeSelectable(n, isExport) + const selfSelectable = isNodeSelectable(n, isExport, isManage) const kidSelectable = [] walkSessions(n.children, (c) => { - if (isNodeSelectable(c, isExport)) kidSelectable.push(c.id) + if (isNodeSelectable(c, isExport, isManage)) kidSelectable.push(c.id) }) const totalSelectable = (selfSelectable ? 1 : 0) + kidSelectable.length const selfOn = selfSelectable && !!selected[n.id] @@ -1469,7 +1531,8 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { tags.push(h('span', { key: 'status', style: styles.importedTag }, 'Codex')) } else if (n.stale) { tags.push(h('span', { key: 'status', style: styles.updatedTag }, t.updated)) - } else if (n.imported) { + } else if (n.imported && !isManage) { + // Every row in the manage view is imported; the tag would be noise. tags.push(h('span', { key: 'status', style: styles.importedTag }, t.imported)) } if (n.isSubagent) { @@ -1522,7 +1585,7 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { : projects.length === 0 ? h('div', { style: { padding: '32px 16px', color: 'var(--dsw-alias-label-tertiary)', textAlign: 'center', fontSize: '13px' } }, t.empty) : projects.map((p) => { - const ids = collectSelectable([p], isExport) + const ids = collectSelectable([p], isExport, isManage) const projectSelectedCount = ids.filter((id) => selected[id]).length const st = ids.length === 0 ? ((p.sessions || []).length ? (!isExport ? 'checked' : 'empty') : 'empty') @@ -1564,8 +1627,8 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { return h('div', { style: styles.overlay }, h('div', { style: Object.assign({}, styles.dialog, { maxHeight: 'none', width: 'min(400px, 90vw)', textAlign: 'center', padding: '20px' }) }, h('div', { style: { display: 'flex', justifyContent: 'center', marginBottom: '10px' } }, Icons.checkCircle()), - h('div', { style: { fontSize: '15px', fontWeight: 600, color: 'var(--dsw-alias-label-primary)', marginBottom: '8px' } }, isExport ? t.exportedOk : t.importedOk), - h('div', { style: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)', lineHeight: '1.5', marginBottom: '18px' } }, isExport ? t.exportHint : t.reloadHint), + h('div', { style: { fontSize: '15px', fontWeight: 600, color: 'var(--dsw-alias-label-primary)', marginBottom: '8px' } }, isManage ? t.deletedOk : isExport ? t.exportedOk : t.importedOk), + h('div', { style: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)', lineHeight: '1.5', marginBottom: '18px' } }, isManage ? t.deleteHint : isExport ? t.exportHint : t.reloadHint), h('div', { style: { display: 'flex', justifyContent: 'center', gap: '10px' } }, isExport ? h('button', { type: 'button', style: styles.primaryBtn, onClick: onClose }, t.done) @@ -1594,9 +1657,13 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { style: Object.assign({}, styles.dialog, { maxHeight: 'none', width: 'min(440px, 90vw)', padding: '20px' }), onKeyDown: (e) => { if (e.key === 'Escape' && !busy) setConfirmingExport(false) }, }, - h('div', { style: { fontSize: '15px', fontWeight: 600, color: 'var(--dsw-alias-label-primary)', marginBottom: '10px' } }, t.confirmExportTitle), + h('div', { style: { fontSize: '15px', fontWeight: 600, color: 'var(--dsw-alias-label-primary)', marginBottom: '10px' } }, isManage ? t.confirmDeleteTitle : t.confirmExportTitle), h('div', { style: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)', lineHeight: '1.6', marginBottom: '18px' } }, - typeof t.confirmExportBody === 'function' ? t.confirmExportBody(selectedCount) : t.confirmExportBody + typeof t.confirmExportBody === 'function' && !isManage + ? t.confirmExportBody(selectedCount) + : isManage + ? t.confirmDeleteBody(selectedCount) + : t.confirmExportBody ), h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: '8px' } }, h('button', { @@ -1609,8 +1676,8 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { type: 'button', style: Object.assign({}, styles.primaryBtn, busy ? { opacity: 0.5, cursor: 'not-allowed', boxShadow: 'none' } : {}), disabled: busy, - onClick: () => { void executeExport() }, - }, busy ? t.loading : t.confirmExportBtn), + onClick: () => { if (isManage) { void executeDelete() } else { void executeExport() } }, + }, busy ? t.loading : (isManage ? t.confirmDeleteBtn : t.confirmExportBtn)), ), ), ) @@ -1690,10 +1757,14 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { h('button', { type: 'button', style: styles.ghostBtn, onClick: onClose }, t.cancel), h('button', { type: 'button', - style: Object.assign({}, styles.primaryBtn, (busy || selectedCount === 0) ? { opacity: 0.5, cursor: 'not-allowed', boxShadow: 'none' } : {}), + style: Object.assign({}, styles.primaryBtn, (busy || selectedCount === 0) + ? { opacity: 0.5, cursor: 'not-allowed', boxShadow: 'none' } + : isManage + ? { background: 'var(--dsw-alias-state-error-primary, #dc2626)' } + : {}), disabled: busy || selectedCount === 0, onClick: onConfirmClick, - }, (isExport ? t.exportN : t.importN) + ' ' + selectedCount), + }, (isManage ? t.deleteN : isExport ? t.exportN : t.importN) + ' ' + selectedCount), ), ), ) @@ -2058,7 +2129,7 @@ function ItemSyncPanel({ lang, kind, items, groupDefault, mirrorStatus, hardDeny ) } -function SyncSettingsModal({ lang, setLang, settings, toggleSetting, itemsData, itemsLoading, onToggleItem, onSetAll, onOpenImport, onOpenExport, onShowStatus, onOpenManage, onOpenPath, onRefresh, onClose }) { +function SyncSettingsModal({ lang, setLang, settings, toggleSetting, itemsData, itemsLoading, onToggleItem, onSetAll, onOpenImport, onOpenExport, onOpenManageImported, onShowStatus, onOpenManage, onOpenPath, onRefresh, onClose }) { const t = labels(lang) // Second-level navigation: null = main page; 'skill' | 'mcp' = manager page. const [subpage, setSubpage] = useState(null) @@ -2279,6 +2350,26 @@ function SyncSettingsModal({ lang, setLang, settings, toggleSetting, itemsData, ? h('div', { style: Object.assign({}, styles.modalTooltip, { top: 'calc(100% + 4px)', left: '0', right: '0', zIndex: 1500 }) }, ACTION_INFO.refresh[lang]) : null ), + h('div', { style: { position: 'relative' } }, + h('button', { + type: 'button', + className: 'codex-sync-card', + style: Object.assign({}, styles.actionCard, { width: '100%' }), + onClick: onOpenManageImported, + }, + h('span', { style: styles.actionCardIcon }, Icons.trash(15)), + h('span', { style: styles.actionCardLabel }, t.manageNow), + h('span', { + style: Object.assign({}, styles.infoIconWrapper, { marginLeft: 'auto' }), + onMouseEnter: (e) => { e.stopPropagation(); setTooltipId('action_manage') }, + onMouseLeave: (e) => { e.stopPropagation(); setTooltipId(null) }, + onClick: (e) => { e.stopPropagation(); e.preventDefault() }, + }, Icons.info(12)) + ), + tooltipId === 'action_manage' && ACTION_INFO.manage?.[lang] + ? h('div', { style: Object.assign({}, styles.modalTooltip, { top: 'calc(100% + 4px)', left: '0', right: '0', zIndex: 1500 }) }, ACTION_INFO.manage[lang]) + : null + ), ) ), @@ -2843,6 +2934,7 @@ function SyncMenu({ runCommand, wide }) { onSetAll: setAllItems, onOpenImport: () => { setSettingsOpen(false); setPickerMode('import'); setPickerOpen(true) }, onOpenExport: () => { setSettingsOpen(false); setPickerMode('export'); setPickerOpen(true) }, + onOpenManageImported: () => { setSettingsOpen(false); setPickerMode('manage'); setPickerOpen(true) }, onShowStatus: showStatus, onOpenManage: openManage, onOpenPath: handleOpenPath, diff --git a/lib/delete-imported.mjs b/lib/delete-imported.mjs new file mode 100644 index 0000000..7da7cfa --- /dev/null +++ b/lib/delete-imported.mjs @@ -0,0 +1,128 @@ +/** + * Delete chats this plugin imported from Codex. + * + * DSH exposes no "delete a Session" API — the workspace controller only offers + * archive/unarchive/pin/unpin — so a real removal means deleting the durable + * artifact. Everything else is derived and self-heals: + * - the SQLite session index reconciles away rows whose artifact is gone, + * - the projection cache file is dropped here, + * - the archive set is cleared through the registry BEFORE the artifact goes, + * because a re-import of the same id would otherwise stay hidden. + * + * Only `codex-*` ids are touched: the prefix is what the importer writes, so a + * chat the user created in DSH can never be removed through this path. + */ +import { existsSync } from 'node:fs' +import { readdir, rm } from 'node:fs/promises' +import { homedir } from 'node:os' +import { join } from 'node:path' + +import { normalizePersistence } from './persistence-facade.mjs' + +/** Every imported Session id starts with this prefix (see import-service). */ +export const IMPORTED_ID_PREFIX = 'codex-' + +/** Durable session store root used by the JSONL persistence backend. */ +export function defaultSessionsRoot() { + return join(homedir(), '.dsh', 'sessions') +} + +/** Materialized projection cache written per Session id. */ +export function defaultProjectionCache() { + return join(homedir(), '.dsh', 'storages', 'session_projcache', 'sessions') +} + +/** + * Find the artifact directory of one Session: `//`. + * @param {string} root - session store root + * @param {string} id - Session id + * @returns {Promise} absolute directory, or undefined + */ +export async function locateSessionDir(root, id) { + let entries + try { + entries = await readdir(root, { withFileTypes: true }) + } catch { + return undefined + } + for (const entry of entries) { + if (!entry.isDirectory()) continue + const candidate = join(root, entry.name, id) + if (existsSync(candidate)) return candidate + } + return undefined +} + +/** + * Delete imported Sessions by id. + * @param {object} ctx - cordis context (reads workspaceRegistry / agents) + * @param {object} persistence - ctx.sessionPersistence (only `list` is used) + * @param {string[]} ids - Session ids to delete + * @param {{sessionsRoot?: string, projectionCache?: string, dryRun?: boolean}} [options] + * @returns {Promise<{lines: string[], deleted: string[], refused: Array<[string, string]>, missing: string[]}>} + */ +export async function deleteImportedSessions(ctx, persistence, ids, options = {}) { + const root = options.sessionsRoot ?? defaultSessionsRoot() + const cache = options.projectionCache ?? defaultProjectionCache() + const dryRun = options.dryRun === true + const registry = ctx.get('workspaceRegistry') + const agents = ctx.get('agents') + const normalized = normalizePersistence(persistence) + const known = new Set(normalized === undefined + ? [] + : (await normalized.list()).map((meta) => meta.id)) + + const lines = [] + const deleted = [] + const refused = [] + const missing = [] + for (const raw of ids) { + const id = String(raw) + if (!id.startsWith(IMPORTED_ID_PREFIX)) { + refused.push([id, '不是本插件导入的会话(只允许删除 codex-* 会话)']) + continue + } + if (!known.has(id)) { + missing.push(id) + continue + } + const live = typeof agents?.get === 'function' ? agents.get(id) : undefined + if (live !== undefined) { + refused.push([id, '对话正在 DSH 中打开,关闭它之后才能删除']) + continue + } + const dir = await locateSessionDir(root, id) + if (dir === undefined) { + missing.push(id) + continue + } + if (dryRun) { + deleted.push(id) + lines.push(` [would-delete] ${id} ${dir}`) + continue + } + // Clear the archive set first: while the artifact still exists the registry + // knows the Session, and an archived id would hide a later re-import. + try { + await registry?.unarchiveSession?.(id) + } catch { /* not archived / registry absent — nothing to undo */ } + try { + await rm(dir, { recursive: true, force: true }) + } catch (error) { + refused.push([id, String(error?.message ?? error)]) + continue + } + try { + await rm(join(cache, `${id}.json`), { force: true }) + } catch { /* cache is derived; a stale file is harmless */ } + deleted.push(id) + lines.push(` [deleted] ${id}`) + } + + const verb = dryRun ? 'would-delete' : 'deleted' + const summary = [`[codex] ${verb} ${deleted.length}, missing ${missing.length}, refused ${refused.length}`] + if (refused.length > 0) summary.push(...refused.map(([id, why]) => ` [refused] ${id}: ${why}`)) + if (missing.length > 0) summary.push(` [hint] ${missing.length} 个会话不在 DSH 的会话存储里(可能已删除),已跳过`) + if (deleted.length > 0 && !dryRun) summary.push(' [hint] 侧边栏列表由 dsh 自己维护,若仍显示旧条目,重启 dsh 或点「刷新列表」') + return { lines: [...lines, ...summary], deleted, refused, missing } +} diff --git a/lib/import-service.js b/lib/import-service.js index 276e343..7a7ece4 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -628,7 +628,10 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j } } - const visible = includeSubagents ? flat : flat.filter((s) => !s.isSubagent) + const included = includeSubagents ? flat : flat.filter((s) => !s.isSubagent) + // The delete view only cares about what this plugin already wrote, so it asks + // for the same tree with the not-yet-imported threads dropped. + const visible = options.onlyImported === true ? included.filter((s) => s.imported) : included const visByRaw = new Map(visible.map((s) => [s.rawId, s])) const roots = [] for (const node of visible) { diff --git a/lib/index.js b/lib/index.js index 2211bd3..e33b8c4 100644 --- a/lib/index.js +++ b/lib/index.js @@ -34,6 +34,7 @@ import { join } from 'node:path' import { bridgeInstructionsSection, bridgeConfigSection } from './bridge.js' import { registerCodexSkillProvider, registerPluginSkillProvider } from './skill-provider.js' import { importCodex, attachAllImported, listImportCatalog } from './import-service.js' +import { deleteImportedSessions } from './delete-imported.mjs' import { unifyWorkspaceTitles } from './attach-workspaces.mjs' import { codexProjectNameForPath, loadCodexIndex } from './codex-index.mjs' import { exportToCodex, listExportCatalog } from './export-codex.js' @@ -743,8 +744,9 @@ export function apply(ctx, config = {}) { const persistence = inner.get('sessionPersistence') if (persistence === undefined) return sendJson(res, 503, { error: 'sessionPersistence unavailable' }) const include = url.searchParams.get('includeSubagents') === '1' || url.searchParams.get('includeSubagents') === 'true' + const onlyImported = url.searchParams.get('only') === 'imported' try { - const catalog = await listImportCatalog(persistence, { importSubagents: include }, codexHome) + const catalog = await listImportCatalog(persistence, { importSubagents: include, onlyImported }, codexHome) sendJson(res, 200, catalog) } catch (error) { sendJson(res, 500, { error: String(error?.message ?? error) }) @@ -763,6 +765,28 @@ export function apply(ctx, config = {}) { } return } + if (sub === '/delete' && req.method === 'POST') { + if (!ef('enableImport', true)) return sendJson(res, 403, { error: 'import disabled' }) + const persistence = inner.get('sessionPersistence') + if (persistence === undefined) return sendJson(res, 503, { error: 'sessionPersistence unavailable' }) + let payload = {} + try { + payload = JSON.parse(await readBody(req) || '{}') + } catch { + return sendJson(res, 400, { error: 'invalid JSON' }) + } + const ids = Array.isArray(payload.ids) ? payload.ids.map(String) : [] + try { + const result = await deleteImportedSessions(inner, persistence, ids, { + dryRun: payload.dryRun === true, + ...(typeof config.sessionsRoot === 'string' ? { sessionsRoot: config.sessionsRoot } : {}), + }) + sendJson(res, 200, { ok: true, text: result.lines.join('\n'), deleted: result.deleted }) + } catch (error) { + sendJson(res, 500, { error: String(error?.message ?? error) }) + } + return + } if (sub === '/export' && req.method === 'POST') { if (!ef('enableImport', true)) return sendJson(res, 403, { error: 'export disabled' }) const persistence = inner.get('sessionPersistence') diff --git a/package.json b/package.json index 2a5a0aa..9e00915 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.9.3", + "version": "1.10.0", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs index 1ede450..64f726c 100644 --- a/scripts/run-tests.mjs +++ b/scripts/run-tests.mjs @@ -13,6 +13,7 @@ const suites = [ 'test/codex-index.test.mjs', 'test/attach-workspaces.test.mjs', 'test/import-service.test.mjs', + 'test/delete-imported.test.mjs', 'test/plugin-skill.test.mjs', 'test/export-codex.test.mjs', 'test/item-sync.test.mjs', diff --git a/test/delete-imported.test.mjs b/test/delete-imported.test.mjs new file mode 100644 index 0000000..41e43cf --- /dev/null +++ b/test/delete-imported.test.mjs @@ -0,0 +1,114 @@ +/** + * delete-imported: only `codex-*` Sessions are removable, an open one is + * refused, and the artifact + projection cache go while the Codex original is + * untouched. Hermetic — throwaway session store and cache. + */ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { deleteImportedSessions, locateSessionDir } from '../lib/delete-imported.mjs' + +function store() { + const root = mkdtempSync(join(tmpdir(), 'cx-del-store-')) + const cache = mkdtempSync(join(tmpdir(), 'cx-del-cache-')) + return { root, cache } +} + +/** Lay out `///session.v4.jsonl.zstd` like the backend. */ +function placeSession(root, projectKey, id) { + const dir = join(root, projectKey, id) + mkdirSync(dir, { recursive: true }) + writeFileSync(join(dir, 'session.v4.jsonl.zstd'), 'artifact') + return dir +} + +function stubPersistence(ids) { + return { async list() { return ids.map((id) => ({ id })) } } +} + +function stubCtx({ live = [], unarchived = [] } = {}) { + return { + get(name) { + if (name === 'agents') return { get: (id) => (live.includes(id) ? { id } : undefined) } + if (name === 'workspaceRegistry') return { async unarchiveSession(id) { unarchived.push(id) } } + return undefined + }, + } +} + +test('delete: removes the artifact, the cache entry and the archive flag', async () => { + const { root, cache } = store() + const id = 'codex-abc' + const dir = placeSession(root, '--D-proj--', id) + writeFileSync(join(cache, `${id}.json`), '{}') + const unarchived = [] + + const result = await deleteImportedSessions(stubCtx({ unarchived }), stubPersistence([id]), [id], { + sessionsRoot: root, + projectionCache: cache, + }) + + assert.deepEqual(result.deleted, [id]) + assert.equal(existsSync(dir), false, 'session directory removed') + assert.equal(existsSync(join(cache, `${id}.json`)), false, 'projection cache removed') + assert.deepEqual(unarchived, [id], 'archive flag cleared before deletion') + assert.match(result.lines.join('\n'), /\[deleted\] codex-abc/) +}) + +test('delete: refuses ids this plugin did not import', async () => { + const { root, cache } = store() + const dir = placeSession(root, '--D-proj--', 'session-mine') + const result = await deleteImportedSessions(stubCtx(), stubPersistence(['session-mine']), ['session-mine'], { + sessionsRoot: root, + projectionCache: cache, + }) + assert.deepEqual(result.deleted, []) + assert.equal(result.refused.length, 1) + assert.match(result.refused[0][1], /codex-/) + assert.equal(existsSync(dir), true, 'a native session is never touched') +}) + +test('delete: refuses a chat that is open in DSH', async () => { + const { root, cache } = store() + const id = 'codex-open' + const dir = placeSession(root, '--D-proj--', id) + const result = await deleteImportedSessions(stubCtx({ live: [id] }), stubPersistence([id]), [id], { + sessionsRoot: root, + projectionCache: cache, + }) + assert.deepEqual(result.deleted, []) + assert.match(result.refused[0][1], /正在 DSH 中打开/) + assert.equal(existsSync(dir), true) +}) + +test('delete: an unknown id is reported as missing, not as a failure', async () => { + const { root, cache } = store() + const result = await deleteImportedSessions(stubCtx(), stubPersistence([]), ['codex-gone'], { + sessionsRoot: root, + projectionCache: cache, + }) + assert.deepEqual(result.missing, ['codex-gone']) + assert.equal(result.refused.length, 0) +}) + +test('delete: dryRun reports without touching the store', async () => { + const { root, cache } = store() + const id = 'codex-dry' + const dir = placeSession(root, '--D-proj--', id) + const result = await deleteImportedSessions(stubCtx(), stubPersistence([id]), [id], { + sessionsRoot: root, + projectionCache: cache, + dryRun: true, + }) + assert.deepEqual(result.deleted, [id]) + assert.equal(existsSync(dir), true, 'dry run keeps the artifact') +}) + +test('locateSessionDir: finds the project folder that holds the id', async () => { + const { root } = store() + const dir = placeSession(root, '--D-another--', 'codex-loc') + assert.equal(await locateSessionDir(root, 'codex-loc'), dir) + assert.equal(await locateSessionDir(root, 'codex-nope'), undefined) +}) From 27fcf19de29cdcf3db7d0f6c0b933adaab74decf Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 15:25:00 +0800 Subject: [PATCH 08/18] =?UTF-8?q?fix:=201.10.1=20=E2=80=94=20=E5=BE=85?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E5=88=97=E8=A1=A8=E9=87=8C=E5=90=8C=E4=B8=80?= =?UTF-8?q?=E5=AF=B9=E8=AF=9D=E9=87=8D=E5=A4=8D=E5=87=BA=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex 会把一个线程分页写成多个 rollout 文件:基础 `rollout--.jsonl[.zst]` 加上后续 `rollout--_` 分段,它们带着同一个 `session_meta.payload.id`,只包含增量轮次。导入器早已按 id 合并,但 `listImportCatalog` 是「一个文件一行」,于是这些线程在导入/管理面板里按分段数重复 出现(本机 6 个线程、多出 8 行)。 - lib/import-service.js: 目录按会话 id 折叠——同一 id 只产出一行,`createdAt` 取最早、 `lastTime` 取最新(保证「有更新」判定正确),并补齐 cwd/parentRawId。 - test: 新增「分段线程只出现一行」用例,断言 lastTime 覆盖最新分段。 - 实机验证:目录从 87 行降到 79 行,重复 id 为 0。 --- CHANGELOG.md | 12 ++++++++++++ lib/import-service.js | 23 ++++++++++++++++++++--- package.json | 2 +- test/import-service.test.mjs | 23 +++++++++++++++++++++++ 4 files changed, 56 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd1480c..77cf409 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 1.10.1 — 2026-11-12 + +- **Fixed: the import picker listed the same chat two or three times.** Codex + paginates one thread into several rollout files — the base + `rollout--.jsonl[.zst]` plus `rollout--_` segments + that carry the same `session_meta.payload.id` and only the delta turns. The + importer already merged them, but `listImportCatalog` built one row per FILE, + so those threads appeared once per segment (6 threads / 8 extra rows here). + Rows are now folded per thread id: one row, spanning first to newest segment, + with the later segment widening `lastTime` so the “有更新” (stale) flag stays + correct. + ## 1.10.0 — 2026-11-12 - **New: 管理已同步 (manage synced chats)** — a picker that lists the chats this diff --git a/lib/import-service.js b/lib/import-service.js index 7a7ece4..e7239c1 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -566,6 +566,11 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j const maxBytes = options.maxSessionBytes ?? DEFAULT_MAX_SESSION_BYTES const includeSubagents = options.importSubagents === true const existing = new Set((await persistence.list()).map((meta) => meta.id)) + // Codex paginates one thread into several rollout files (base `…-` plus + // `…-_` continuation segments). They all carry the same + // `session_meta.payload.id`, so the picker must fold them into ONE row — + // listing a file per row showed the same chat two or three times. + const bySessionId = new Map() const flat = [] let skippedBig = 0 let unreadable = 0 @@ -602,19 +607,31 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j const parentRawId = parsed.header.parentThreadId ? String(parsed.header.parentThreadId) : (origin?.parentThreadId ?? null) - flat.push({ + const created = parsed.header.createdAt ?? 0 + const seen = bySessionId.get(id) + if (seen !== undefined) { + // Another segment of the same thread: widen the span, keep the rest. + if (lastTime > seen.lastTime) seen.lastTime = lastTime + if (created > 0 && (seen.createdAt === 0 || created < seen.createdAt)) seen.createdAt = created + if (seen.parentRawId === null && parentRawId !== null) seen.parentRawId = parentRawId + if (seen.cwd === null && typeof parsed.header.cwd === 'string') seen.cwd = parsed.header.cwd + continue + } + const node = { rawId, id, parentRawId, cwd: typeof parsed.header.cwd === 'string' ? parsed.header.cwd : null, - createdAt: parsed.header.createdAt ?? 0, + createdAt: created, lastTime, title, isSubagent: isInternal, imported: existing.has(id), stale: false, children: [], - }) + } + bySessionId.set(id, node) + flat.push(node) } for (const node of flat) { diff --git a/package.json b/package.json index 9e00915..d54eb82 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.10.0", + "version": "1.10.1", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index 0928370..7a6abe0 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -369,6 +369,29 @@ test('import-codex: paginated rollout segments of one thread merge into a single assert.ok(users.some((t) => t.includes('user-main-seg')), 'continuation segment messages imported in the same session') }) +test('catalog: paginated segments of one thread appear as ONE row', async () => { + // The picker used to build a row per FILE, so a thread Codex continued into + // `rollout--_.jsonl` showed up two or three times with the + // same title. Segments share `session_meta.payload.id`, so they must fold. + const root = mkdtempSync(join(tmpdir(), 'cx-sync-catalog-seg-')) + const dir = join(root, 'sessions', '2026', '08', '17') + mkdirSync(dir, { recursive: true }) + const segment = (name, at, text) => [ + { type: 'session_meta', payload: { id: 'sess-seg', cwd: '/tmp/proj', timestamp: at, source: 'cli' } }, + { type: 'response_item', timestamp: at, payload: { type: 'message', id: `m-${name}`, role: 'user', content: [{ type: 'input_text', text }] } }, + { type: 'response_item', timestamp: at, payload: { type: 'message', id: `a-${name}`, role: 'assistant', content: [{ type: 'output_text', text: `a-${name}` }] } }, + ] + writeFileSync(join(dir, 'rollout-seg.jsonl'), segment('base', '2026-08-17T10:00:00.000Z', 'base-ask').map((e) => JSON.stringify(e)).join('\n') + '\n') + writeFileSync(join(dir, 'rollout-seg_01a2.jsonl'), segment('fork', '2026-08-18T10:00:00.000Z', 'fork-ask').map((e) => JSON.stringify(e)).join('\n') + '\n') + const { persistence, ctx } = stubPersistence() + + const catalog = await listImportCatalog(persistence, {}, root) + const rows = catalog.projects.flatMap((p) => p.sessions) + assert.equal(rows.length, 1, 'one thread → one row') + assert.equal(rows[0].id, 'codex-sess-seg') + assert.ok(rows[0].lastTime >= Date.parse('2026-08-18T10:00:00.000Z'), 'span covers the newest segment') +}) + test('import-codex: writes the session in the installed current format, not v0 (issue #2)', async () => { // DSH persistence rejects older formats on write ("encodeCurrent requires // Session format v4" on DSH 0.10.x), so the importer must migrate the From 48136c4824ea01f0c6e9c8422674ab3d6c3bc453 Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 15:35:55 +0800 Subject: [PATCH 09/18] =?UTF-8?q?fix:=201.10.2=20=E2=80=94=20=E5=AF=BC?= =?UTF-8?q?=E5=85=A5=E7=9A=84=E4=BC=9A=E8=AF=9D=E5=8F=AF=E8=83=BD=E9=9D=99?= =?UTF-8?q?=E9=BB=98=E4=B8=8D=E6=8C=82=E5=B7=A5=E4=BD=9C=E5=8C=BA=EF=BC=88?= =?UTF-8?q?=E4=BE=A7=E8=BE=B9=E6=A0=8F=E6=89=BE=E4=B8=8D=E5=88=B0=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `workspace.attachSession()` 在注册表把 id 过滤掉时(归档会话永远进不了 `workspace.sessionIds`)会**正常返回、不报错**,导入器把它当成成功,于是会话既不在任何 工作区、侧边栏也就没有位置显示——表现就是「导入成功但对应项目下找不到」。 - lib/attach-workspaces.mjs: attach 后用 `workspace.sessionIds.includes(id)` 校验; 失败先重试一次(写入后 header 索引可能滞后 300ms);仍未挂上则输出 `[ungrouped] → <工作区>: <原因>`,并追加提示「关闭该对话后运行 /attach-workspaces」。 - test: 新增「注册表静默不收(归档)时报告 ungrouped」用例;fake registry 补 sessionIds,便于断言。 - 现场核对(本机):`codex-01a1c47b…` 会话文件确实写入 `...\ZBWX\2.0\zbwx-frontend-v2`,live host 的 persistence.list() 也能看到它,但 `workspace.json` 里没有任何工作区收录它 → 正是上面的静默失败。 --- CHANGELOG.md | 15 +++++++++++++++ lib/attach-workspaces.mjs | 27 +++++++++++++++++++++++---- package.json | 2 +- test/attach-workspaces.test.mjs | 31 +++++++++++++++++++++++++++++++ 4 files changed, 70 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 77cf409..c640b3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.10.2 — 2026-11-12 + +- **Fixed: an imported chat could silently stay without a workspace, so the + sidebar showed it nowhere.** `workspace.attachSession()` returns without error + when the registry filters the id back out (an archived Session never reaches + `workspace.sessionIds`), and the importer counted that as success. Attach is + now verified against `workspace.sessionIds`, retried once (the header index can + lag right after a write), and every session that stays ungrouped is reported as + `[ungrouped] → : ` plus a hint to run + `/attach-workspaces` after closing the chat. +- Note: DSH allows two workspaces with the same display title (different paths), + so one Codex project that spans several repo roots can show up as several + same-named groups; the chat may sit in the sibling group rather than the one + you were looking at. + ## 1.10.1 — 2026-11-12 - **Fixed: the import picker listed the same chat two or three times.** Codex diff --git a/lib/attach-workspaces.mjs b/lib/attach-workspaces.mjs index 8373209..a2ebf17 100644 --- a/lib/attach-workspaces.mjs +++ b/lib/attach-workspaces.mjs @@ -62,6 +62,7 @@ export async function attachSessionsToWorkspaces(ctx, sessions, options = {}) { if (registry === undefined) return [] const projectNameOf = options.projectNameOf const lines = [] + const unattached = [] const byCwd = new Map() for (const session of sessions) { if (typeof session.cwd !== 'string' || session.cwd.length === 0) continue @@ -86,10 +87,22 @@ export async function attachSessionsToWorkspaces(ctx, sessions, options = {}) { await workspace.setTitle(title) } for (const id of ids) { - try { - await workspace.attachSession(id) - } catch (error) { - lines.push(` [skipped] ${id} attach to ${cwd}: ${error.message}`) + let attached = false + for (let attempt = 0; attempt < 2 && !attached; attempt += 1) { + if (attempt > 0) await new Promise((resolve) => setTimeout(resolve, 300)) + try { + await workspace.attachSession(id) + attached = true + } catch (error) { + if (attempt > 0) unattached.push({ id, title, reason: error.message }) + } + } + // `attachSession` is a silent no-op when the registry filters the id back + // out (an archived session never reaches `workspace.sessionIds`), and a + // silent no-op leaves the chat with no group to appear in — the symptom + // is "导入成功但侧边栏找不到". + if (attached && Array.isArray(workspace.sessionIds) && !workspace.sessionIds.includes(id)) { + unattached.push({ id, title, reason: '工作区未收录该会话(可能处于归档状态)' }) } } const action = existing === undefined ? 'created' : 'reused' @@ -103,6 +116,12 @@ export async function attachSessionsToWorkspaces(ctx, sessions, options = {}) { } } } + for (const { id, title, reason } of unattached) { + lines.push(` [ungrouped] ${id} → ${title}: ${reason}`) + } + if (unattached.length > 0) { + lines.push(` [hint] ${unattached.length} 个会话没能挂到工作区,侧边栏可能看不到它们;先关闭该对话,再运行 /attach-workspaces 重试`) + } return lines } diff --git a/package.json b/package.json index d54eb82..3b40851 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.10.1", + "version": "1.10.2", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/test/attach-workspaces.test.mjs b/test/attach-workspaces.test.mjs index 2f66f85..343166a 100644 --- a/test/attach-workspaces.test.mjs +++ b/test/attach-workspaces.test.mjs @@ -41,6 +41,7 @@ function fakeRegistry() { path, title, attached: [], + get sessionIds() { return workspace.attached }, setTitle: async (next) => { workspace.title = next }, attachSession: async (id) => { workspace.attached.push(id) }, } @@ -110,6 +111,36 @@ test('attach renames only auto-generated titles, leaving custom ones alone', asy assert.equal(workspace.title, '我的项目') }) +test('attach reports a session the workspace refuses to store (silent no-op)', async () => { + // `attachSession` resolves and returns without error when the registry filters + // the id back out (an archived Session never reaches `workspace.sessionIds`). + // That silent no-op is exactly "imported fine but nowhere in the sidebar". + const home = codexHomeWithProject() + invalidateCodexIndex(home) + const index = loadCodexIndex(home) + const registry = fakeRegistry() + registry.create = async (path, title) => { + const workspace = { + path, + title, + attached: [], + get sessionIds() { return [] }, + setTitle: async (next) => { workspace.title = next }, + attachSession: async () => {}, + } + return workspace + } + const ctx = { get: (name) => (name === 'workspaceRegistry' ? registry : undefined) } + + const lines = await attachSessionsToWorkspaces(ctx, [{ id: 'codex-archived', cwd: 'D:/ws/ZBWX/2.0/zbwx-frontend-v2' }], { + projectNameOf: (cwd) => codexProjectNameForPath(index, cwd), + }) + const report = lines.join('\n') + assert.match(report, /\[ungrouped\] codex-archived/) + assert.match(report, /归档/, 'names the likely cause') + assert.match(report, /\/attach-workspaces/, 'tells the user how to retry') +}) + test('unifyWorkspaceTitles strips path-form titles but keeps custom ones', async () => { const home = codexHomeWithProject() invalidateCodexIndex(home) From 0c51e54465878a79e3127e0c83bb1a30b29cc889 Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 15:46:22 +0800 Subject: [PATCH 10/18] =?UTF-8?q?fix:=201.10.3=20=E2=80=94=20=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=B7=B2=E5=90=8C=E6=AD=A5=EF=BC=9A=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E7=BB=93=E6=9E=9C=E5=A6=82=E5=AE=9E=E6=98=BE=E7=A4=BA=EF=BC=88?= =?UTF-8?q?=E5=90=AB=E8=A2=AB=E6=8B=92=E7=BB=9D=E7=9A=84=E5=8E=9F=E5=9B=A0?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 11 +++++++++++ lib/client.js | 37 +++++++++++++++++++++++++++++++++---- package.json | 2 +- 3 files changed, 45 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c640b3a..fd65412 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 1.10.3 — 2026-11-12 + +- **Fixed: 管理已同步 looked like it did nothing.** The host answers `ok: true` + even when every id was refused (the usual reason: the chat is open in DSH, so + the Host holds its write handle and refuses deletion), and the panel ignored + the returned lines — so a refused delete displayed “已删除已同步对话”. The + result view now shows the host's report (`[deleted] …` / `[refused] …`) and + says “没有删除任何会话” when nothing was removed, so the reason is visible. + Verified against the running Host: deleting an open chat returns + `[refused] … : 对话正在 DSH 中打开,关闭它之后才能删除`. + ## 1.10.2 — 2026-11-12 - **Fixed: an imported chat could silently stay without a workspace, so the diff --git a/lib/client.js b/lib/client.js index 9b8ef72..789e3f0 100644 --- a/lib/client.js +++ b/lib/client.js @@ -1035,6 +1035,7 @@ function labels(lang) { confirmDeleteBody: (count) => `即将删除 ${count} 个已同步到 DSH 的对话。这会移除 DSH 侧会话文件与其缓存,Codex 里的原始对话不受影响,之后可以重新导入。删除后如果侧边栏还显示旧条目,重启 dsh 即可。`, confirmDeleteBtn: '确认删除', deletedOk: '已删除已同步对话', + deleteNone: '没有删除任何会话', deleteHint: 'DSH 侧的会话文件已移除,Codex 原始对话保持不动。若侧边栏仍显示旧条目,重启 dsh 后消失。', confirmExportTitle: '确认导出', confirmExportBody: (count) => `即将导出 ${count} 个会话。由于插件无法覆盖或追加原 Codex 对话,导出将创建全新的 Codex 会话副本;子代理会话将作为独立会话导出,无法与父会话合并。导出的对话重启 Codex 可见。`, @@ -1127,6 +1128,7 @@ function labels(lang) { confirmDeleteBody: (count) => `About to delete ${count} synced chat(s) from DSH. This removes the DSH session files and their caches; the original Codex threads are untouched and can be imported again later. If the sidebar still lists them, restart dsh.`, confirmDeleteBtn: 'Delete', deletedOk: 'Synced chats removed', + deleteNone: 'Nothing was deleted', deleteHint: 'The DSH session files were removed; the Codex originals are untouched. Restart dsh if the sidebar still lists them.', confirmExportTitle: 'Confirm export', confirmExportBody: (count) => `About to export ${count} session(s). Because the plugin cannot overwrite or append to original Codex threads, exporting will create new, independent Codex conversation copies; subagents will export separately and cannot merge into parent sessions. Exported conversations will be visible after restarting Codex.`, @@ -1324,6 +1326,7 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { const [busy, setBusy] = useState(false) const [confirmingExport, setConfirmingExport] = useState(false) const [done, setDone] = useState(false) + const [deleteReport, setDeleteReport] = useState(null) const load = async (includeSubagents, includeCodex) => { setError(null) @@ -1425,6 +1428,11 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { if (!res.ok || !data?.ok) { throw new Error(data?.error || String(res.status)) } + const removed = Array.isArray(data.deleted) ? data.deleted.length : 0 + // The host answers 200 even when every id was refused (a chat that is open + // in DSH). Showing "deleted" without the host's lines hid the reason and + // looked like the button did nothing. + setDeleteReport({ removed, text: typeof data.text === 'string' ? data.text : '' }) setBusy(false) setConfirmingExport(false) setDone(true) @@ -1624,11 +1632,32 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { }) if (done) { + const refusedOnly = isManage && deleteReport !== null && deleteReport.removed === 0 return h('div', { style: styles.overlay }, - h('div', { style: Object.assign({}, styles.dialog, { maxHeight: 'none', width: 'min(400px, 90vw)', textAlign: 'center', padding: '20px' }) }, - h('div', { style: { display: 'flex', justifyContent: 'center', marginBottom: '10px' } }, Icons.checkCircle()), - h('div', { style: { fontSize: '15px', fontWeight: 600, color: 'var(--dsw-alias-label-primary)', marginBottom: '8px' } }, isManage ? t.deletedOk : isExport ? t.exportedOk : t.importedOk), - h('div', { style: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)', lineHeight: '1.5', marginBottom: '18px' } }, isManage ? t.deleteHint : isExport ? t.exportHint : t.reloadHint), + h('div', { style: Object.assign({}, styles.dialog, { maxHeight: 'none', width: 'min(480px, 92vw)', textAlign: 'center', padding: '20px' }) }, + h('div', { style: { display: 'flex', justifyContent: 'center', marginBottom: '10px' } }, refusedOnly ? Icons.info(18) : Icons.checkCircle()), + h('div', { style: { fontSize: '15px', fontWeight: 600, color: 'var(--dsw-alias-label-primary)', marginBottom: '8px' } }, + isManage + ? (refusedOnly ? t.deleteNone : t.deletedOk) + : isExport ? t.exportedOk : t.importedOk), + isManage && deleteReport !== null && deleteReport.text.length > 0 + ? h('pre', { + style: { + fontSize: '11px', + lineHeight: 1.5, + textAlign: 'left', + whiteSpace: 'pre-wrap', + wordBreak: 'break-word', + maxHeight: '180px', + overflow: 'auto', + margin: '0 0 14px', + padding: '8px 10px', + borderRadius: '6px', + background: 'var(--dsw-alias-bg-l2, rgba(127,127,127,0.08))', + color: 'var(--dsw-alias-label-secondary)', + }, + }, deleteReport.text) + : h('div', { style: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)', lineHeight: '1.5', marginBottom: '18px' } }, isManage ? t.deleteHint : isExport ? t.exportHint : t.reloadHint), h('div', { style: { display: 'flex', justifyContent: 'center', gap: '10px' } }, isExport ? h('button', { type: 'button', style: styles.primaryBtn, onClick: onClose }, t.done) diff --git a/package.json b/package.json index 3b40851..bd0c88e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.10.2", + "version": "1.10.3", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", From 143f7080110255c8bb4d6ffd3eba5e8ae5828f5d Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 15:53:34 +0800 Subject: [PATCH 11/18] =?UTF-8?q?feat:=201.10.4=20=E2=80=94=20=E8=BF=87?= =?UTF-8?q?=E6=BB=A4=20Codex=20=E4=BE=A7=E8=BE=B9=E8=81=8A=E5=A4=A9?= =?UTF-8?q?=EF=BC=88fork=20=E7=BA=BF=E7=A8=8B=EF=BC=89=EF=BC=8C=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E4=B8=8E=E5=88=97=E8=A1=A8=E9=83=BD=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E5=87=BA=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 15 +++++++++++++++ lib/codex-reader.mjs | 11 +++++++++++ lib/import-service.js | 22 ++++++++++++++++++++-- package.json | 2 +- test/codex-reader.test.mjs | 25 +++++++++++++++++++++++++ test/import-service.test.mjs | 25 +++++++++++++++++++++++++ 6 files changed, 97 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd65412..ac3a3ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.10.4 — 2026-11-12 + +- **Codex side chats are no longer synced or listed.** When Codex Desktop opens a + conversation in its side panel it forks the thread: the new rollout carries + `session_meta.payload.forked_from_id` (and a `history_base` naming the parent), + the same name and the same history prefix — so the picker showed two rows with + one title (“继续 WeKnora 插件化集成”) and importing the fork duplicated the chat. + The reader now records `forkedFromId` (a paginated continuation segment points + `history_base` at ITSELF, which is the same thread, not a fork), and both the + catalog and the importer drop forked threads. The import result reports + `side-chat-skipped N` with a hint. On this machine that is 27 threads, and the + catalog now has no duplicate titles. +- Note: a side chat imported by an older build stays in DSH; remove it with + 管理已同步. + ## 1.10.3 — 2026-11-12 - **Fixed: 管理已同步 looked like it did nothing.** The host answers `ok: true` diff --git a/lib/codex-reader.mjs b/lib/codex-reader.mjs index 93b15ed..bb7290b 100644 --- a/lib/codex-reader.mjs +++ b/lib/codex-reader.mjs @@ -213,6 +213,17 @@ export async function parseCodexSession(file) { if (payload.parent_thread_id !== undefined) header.parentThreadId = payload.parent_thread_id if (payload.agent_nickname !== undefined) header.agentNickname = payload.agent_nickname if (payload.thread_source !== undefined) header.threadSource = payload.thread_source + // Codex Desktop's side chat: the conversation is forked into its own + // thread (`forked_from_id`, or a `history_base` naming another thread) and + // repeats the parent's name and history prefix. Paginated continuation + // segments carry `history_base` too, but pointing at THEMSELVES, so the + // self-reference is what separates a fork from a segment. + const forkedFrom = typeof payload.forked_from_id === 'string' + ? payload.forked_from_id + : (typeof payload.history_base?.thread_id === 'string' ? payload.history_base.thread_id : undefined) + if (typeof forkedFrom === 'string' && forkedFrom.length > 0 && forkedFrom !== payload.id) { + header.forkedFromId = forkedFrom + } const created = Date.parse(payload.timestamp) header.createdAt = Number.isNaN(created) ? undefined : created continue diff --git a/lib/import-service.js b/lib/import-service.js index e7239c1..2cbc2e6 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -377,6 +377,7 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo const candidates = [] let skippedBig = 0 let skippedSubagent = 0 + let skippedSideChat = 0 let unreadable = 0 for (const file of listCodexSessions(join(codexHome, 'sessions'))) { let size @@ -405,6 +406,13 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo skippedSubagent += 1 continue } + // Codex Desktop's side chat forks a conversation into a thread of its own + // (`forked_from_id`): same name, same history prefix, no new conversation. + // Importing it would duplicate the chat, so it is never synced or listed. + if (typeof parsed.header.forkedFromId === 'string' && parsed.header.forkedFromId.length > 0) { + skippedSideChat += 1 + continue + } candidates.push({ file, id: `codex-${parsed.header.id}`, @@ -537,13 +545,16 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo lines.push(` [imported] ${candidate.id} ${candidate.cwd ?? '(no cwd)'} ${messages.length} messages -> ${currentEvents.length} events`) } const verb = dryRun ? 'would-import' : 'imported' - lines.push(`[codex] result: ${verb} ${imported}, updated ${updated}, skipped ${skipped}, empty ${empty}, busy ${busy}, subagent-skipped ${skippedSubagent}, oversized-skipped ${skippedBig}, unreadable ${unreadable}`) + lines.push(`[codex] result: ${verb} ${imported}, updated ${updated}, skipped ${skipped}, empty ${empty}, busy ${busy}, subagent-skipped ${skippedSubagent}, side-chat-skipped ${skippedSideChat}, oversized-skipped ${skippedBig}, unreadable ${unreadable}`) if (busy > 0) { lines.push(` [hint] ${busy} 个会话正在 DSH 中打开(写句柄被占用),本次未更新;关闭这些对话后重新导入即可补齐`) } if (skippedSubagent > 0) { lines.push(` [hint] ${skippedSubagent} codex 子代理线程已过滤(默认,避免会话列表塞满); 需要时用 /import-codex --include-subagents 或配置 importSubagents: true`) } + if (skippedSideChat > 0) { + lines.push(` [hint] ${skippedSideChat} 个 Codex 侧边聊天(fork 出来的副本)已跳过:它们与母会话同名同历史,同步会重复`) + } if (skippedBig > 0) { lines.push(` [hint] ${skippedBig} file(s) > ${Math.round(maxBytes / 1024 / 1024)} MiB were skipped; raise config maxSessionBytes to include them`) } @@ -574,6 +585,7 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j const flat = [] let skippedBig = 0 let unreadable = 0 + let skippedSideChat = 0 const index = loadCodexIndex(codexHome) for (const file of listCodexSessions(join(codexHome, 'sessions'))) { let size @@ -595,6 +607,12 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j continue } if (parsed.header.id === undefined) continue + // Codex Desktop's side chat is a fork of another thread (same name, same + // history prefix); it is never synced, so the picker must not list it either. + if (typeof parsed.header.forkedFromId === 'string' && parsed.header.forkedFromId.length > 0) { + skippedSideChat += 1 + continue + } const rawId = String(parsed.header.id) const id = `codex-${rawId}` const title = resolveImportTitle(codexHome, rawId, parsed.header.title, parsed.messages) ?? id @@ -691,7 +709,7 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j }) } projects.sort((a, b) => b.latest - a.latest) - return { projects, skippedBig, unreadable } + return { projects, skippedBig, unreadable, skippedSideChat } } /** diff --git a/package.json b/package.json index bd0c88e..ca34f23 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.10.3", + "version": "1.10.4", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/test/codex-reader.test.mjs b/test/codex-reader.test.mjs index 9cb2a81..c687016 100644 --- a/test/codex-reader.test.mjs +++ b/test/codex-reader.test.mjs @@ -273,6 +273,31 @@ test('reader: the last thread_goal_updated becomes the session goal', async () = assert.equal(header.goal.tokensUsed, 1234) }) +test('reader: a forked thread (codex side chat) is marked, a paginated segment is not', async () => { + // Codex Desktop's side chat: `forked_from_id` names the conversation it forked. + const forked = nextFile('forked') + write(forked, rolloutOf([ + { type: 'session_meta', payload: { id: 'sess-child', cwd: '/tmp/p', timestamp: '2026-08-17T09:59:00Z', forked_from_id: 'sess-parent' } }, + ])) + const child = (await parseCodexSession(forked)).header + assert.equal(child.forkedFromId, 'sess-parent') + + // A paginated continuation segment carries `history_base` pointing at ITSELF; + // that is the same thread, not a side chat. + const segment = nextFile('segment') + write(segment, rolloutOf([ + { type: 'session_meta', payload: { id: 'sess-self', cwd: '/tmp/p', timestamp: '2026-08-17T09:59:00Z', history_base: { thread_id: 'sess-self', end_ordinal: 12 } } }, + ])) + assert.equal((await parseCodexSession(segment)).header.forkedFromId, undefined) + + // `history_base` naming ANOTHER thread is a fork too. + const viaBase = nextFile('forked-base') + write(viaBase, rolloutOf([ + { type: 'session_meta', payload: { id: 'sess-b', cwd: '/tmp/p', timestamp: '2026-08-17T09:59:00Z', history_base: { thread_id: 'sess-a' } } }, + ])) + assert.equal((await parseCodexSession(viaBase)).header.forkedFromId, 'sess-a') +}) + test('legacy schema: tool_use blocks inside message content still map to tool-calls', async () => { const events = [ msg('T1', '2026-08-17T10:00:01Z', 'user', [{ type: 'input_text', text: '读文件' }]), diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index 7a6abe0..976d221 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -392,6 +392,31 @@ test('catalog: paginated segments of one thread appear as ONE row', async () => assert.ok(rows[0].lastTime >= Date.parse('2026-08-18T10:00:00.000Z'), 'span covers the newest segment') }) +test('catalog: a Codex side chat (forked thread) is neither listed nor imported', async () => { + // Codex Desktop forks a conversation into its own thread for a side chat; it + // repeats the parent's name and history, so syncing it duplicates the chat. + const root = mkdtempSync(join(tmpdir(), 'cx-sync-side-')) + const main = makeSession(root, 'parent') + const dir = join(root, 'sessions', '2026', '08', '17') + writeFileSync(join(dir, 'rollout-side.jsonl'), [ + { type: 'session_meta', payload: { id: 'sess-side', cwd: '/tmp/proj', timestamp: '2026-08-17T11:00:00.000Z', forked_from_id: 'sess-parent' } }, + rawEvent({ type: 'message', id: 'm-side', role: 'user', content: [{ type: 'input_text', text: 'user-side-1' }] }), + rawEvent({ type: 'message', id: 'a-side', role: 'assistant', content: [{ type: 'output_text', text: 'assistant-side-1' }] }), + ].map((e) => JSON.stringify(e)).join('\n') + '\n') + const { persistence, ctx, store } = stubPersistence() + + const catalog = await listImportCatalog(persistence, {}, root) + const ids = catalog.projects.flatMap((p) => p.sessions).map((s) => s.id) + assert.ok(ids.includes(main), 'the real chat is listed') + assert.ok(!ids.includes('codex-sess-side'), 'the side chat is not listed') + assert.equal(catalog.skippedSideChat, 1) + + const lines = await importCodex(ctx, persistence, {}, root) + assert.ok(!store.has('codex-sess-side'), 'the side chat is not imported') + assert.match(lines.join('\n'), /side-chat-skipped 1/) + assert.match(lines.join('\n'), /侧边聊天/) +}) + test('import-codex: writes the session in the installed current format, not v0 (issue #2)', async () => { // DSH persistence rejects older formats on write ("encodeCurrent requires // Session format v4" on DSH 0.10.x), so the importer must migrate the From 786e8c68453d5dfa0cd2ba6c52796aaf61a20adb Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 16:00:13 +0800 Subject: [PATCH 12/18] =?UTF-8?q?fix:=201.10.5=20=E2=80=94=20=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=B7=B2=E5=90=8C=E6=AD=A5=E8=A1=A5=E5=85=A8=EF=BC=88?= =?UTF-8?q?=E4=BE=A7=E8=BE=B9=E8=81=8A=E5=A4=A9=E4=B8=8E=E5=AD=A4=E5=84=BF?= =?UTF-8?q?=E5=AF=BC=E5=85=A5=E4=B9=9F=E8=83=BD=E5=88=97=E5=87=BA=E5=B9=B6?= =?UTF-8?q?=E5=88=A0=E9=99=A4=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 12 +++++++++ lib/import-service.js | 51 +++++++++++++++++++++++++++++++++--- package.json | 2 +- test/import-service.test.mjs | 29 ++++++++++++++++++++ 4 files changed, 89 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac3a3ae..efe1cda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 1.10.5 — 2026-11-12 + +- **Fixed: 管理已同步 could not show some imported chats, so they were + undeletable.** 1.10.4 filtered Codex side chats out of the catalog, and the + manage view is catalog-driven — a side chat an older build had imported then + vanished from the list entirely (the reported case: `codex-01a1c47b…`). The + `only=imported` view now keeps side chats, and it also lists **orphaned + imports** — sessions this plugin wrote whose Codex thread no longer exists — + taking their title from the DSH session log. The import view keeps hiding side + chats. +- Fixed a crash when grouping an orphan (no cwd → `cwd.length` on null). + ## 1.10.4 — 2026-11-12 - **Codex side chats are no longer synced or listed.** When Codex Desktop opens a diff --git a/lib/import-service.js b/lib/import-service.js index 2cbc2e6..a77d4b0 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -28,6 +28,7 @@ import { buildDshEvents, deriveImportTitle } from './convert.mjs' import { migrateToCurrent } from './session-migrate.mjs' import { normalizePersistence, isSessionBusyError } from './persistence-facade.mjs' import { attachSessionsToWorkspaces, listImportedSessions } from './attach-workspaces.mjs' +import { IMPORTED_ID_PREFIX } from './delete-imported.mjs' export const DEFAULT_MAX_SESSION_BYTES = 2 * 1024 * 1024 * 1024 /** @@ -608,8 +609,11 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j } if (parsed.header.id === undefined) continue // Codex Desktop's side chat is a fork of another thread (same name, same - // history prefix); it is never synced, so the picker must not list it either. - if (typeof parsed.header.forkedFromId === 'string' && parsed.header.forkedFromId.length > 0) { + // history prefix); it is never synced, so the picker must not list it. + // The 管理已同步 view still needs it: a side chat an older build imported has + // to stay deletable (the filter is applied after the tree is built). + const isSideChat = typeof parsed.header.forkedFromId === 'string' && parsed.header.forkedFromId.length > 0 + if (isSideChat && options.onlyImported !== true) { skippedSideChat += 1 continue } @@ -652,12 +656,50 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j flat.push(node) } + // 管理已同步 must list EVERY chat this plugin wrote, including ones the import + // view deliberately hides (side chats forked by Codex) and ones whose Codex + // thread no longer exists — otherwise they could never be deleted. + if (options.onlyImported === true) { + const listed = new Set(flat.map((node) => node.id)) + for (const meta of await persistence.list()) { + if (typeof meta?.id !== 'string' || !meta.id.startsWith(IMPORTED_ID_PREFIX) || listed.has(meta.id)) continue + const orphan = { + rawId: meta.id.slice(IMPORTED_ID_PREFIX.length), + id: meta.id, + parentRawId: null, + cwd: typeof meta.cwd === 'string' ? meta.cwd : null, + createdAt: typeof meta.createdAt === 'number' ? meta.createdAt : 0, + lastTime: 0, + title: meta.id, + isSubagent: false, + sideChat: false, + orphan: true, + imported: true, + stale: false, + children: [], + } + listed.add(orphan.id) + flat.push(orphan) + } + } + for (const node of flat) { if (!node.imported || typeof persistence.inspect !== 'function') continue try { const view = await persistence.inspect(node.id) - const lastDsh = view?.events?.length ? (view.events[view.events.length - 1].time ?? 0) : 0 + const events = view?.events ?? [] + const lastDsh = events.length > 0 ? (events[events.length - 1].time ?? 0) : 0 node.stale = node.lastTime > lastDsh + 500 + if (node.orphan === true) { + // No Codex thread to name it from: reuse the title DSH stored. + for (let i = events.length - 1; i >= 0; i -= 1) { + if (events[i]?.type === 'session/title') { + const named = events[i].data?.title + if (typeof named === 'string' && named.length > 0) node.title = named + break + } + } + } } catch { node.stale = false } @@ -702,7 +744,8 @@ export async function listImportCatalog(persistence, options = {}, codexHome = j walk(sorted) const cwd = group.cwd projects.push({ - cwd: cwd.length > 0 ? cwd : null, + // An orphaned import (its Codex thread is gone) has no cwd to group by. + cwd: typeof cwd === 'string' && cwd.length > 0 ? cwd : null, label: group.label, sessions: sorted, latest, diff --git a/package.json b/package.json index ca34f23..d718c3d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.10.4", + "version": "1.10.5", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index 976d221..c7dcb32 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -417,6 +417,35 @@ test('catalog: a Codex side chat (forked thread) is neither listed nor imported' assert.match(lines.join('\n'), /侧边聊天/) }) +test('catalog: 管理已同步 still lists side chats and orphaned imports so they stay deletable', async () => { + const root = mkdtempSync(join(tmpdir(), 'cx-sync-manage-')) + makeSession(root, 'live') + const dir = join(root, 'sessions', '2026', '08', '17') + // A side chat (forked) plus an import whose Codex thread is gone entirely. + writeFileSync(join(dir, 'rollout-side.jsonl'), [ + { type: 'session_meta', payload: { id: 'sess-side', cwd: '/tmp/proj', timestamp: '2026-08-17T11:00:00.000Z', forked_from_id: 'sess-parent' } }, + rawEvent({ type: 'message', id: 'm-side', role: 'user', content: [{ type: 'input_text', text: 'user-side-1' }] }), + ].map((e) => JSON.stringify(e)).join('\n') + '\n') + const { persistence, ctx, store } = stubPersistence() + await importCodex(ctx, persistence, {}, root) + + // Simulate the orphan: DSH holds a codex session Codex no longer has. + const orphanId = 'codex-gone-1111' + store.set(orphanId, [ + { type: 'session/title', seq: 0, time: Date.now(), data: { title: '被 Codex 删除的会话' } }, + ]) + + const manage = await listImportCatalog(persistence, { onlyImported: true }, root) + const ids = manage.projects.flatMap((p) => p.sessions).map((s) => s.id) + assert.ok(ids.includes(orphanId), 'orphaned import is listed for deletion') + const orphan = manage.projects.flatMap((p) => p.sessions).find((s) => s.id === orphanId) + assert.equal(orphan.title, '被 Codex 删除的会话', 'title comes from the DSH session log') + + const importView = await listImportCatalog(persistence, {}, root) + const importIds = importView.projects.flatMap((p) => p.sessions).map((s) => s.id) + assert.ok(!importIds.includes('codex-sess-side'), 'the import view still hides side chats') +}) + test('import-codex: writes the session in the installed current format, not v0 (issue #2)', async () => { // DSH persistence rejects older formats on write ("encodeCurrent requires // Session format v4" on DSH 0.10.x), so the importer must migrate the From 8f4d6f451df009bd622ffb2143dedf939be6f3ed Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 16:12:14 +0800 Subject: [PATCH 13/18] =?UTF-8?q?feat:=201.10.6=20=E2=80=94=20=E9=97=AE?= =?UTF-8?q?=E7=AD=94=E5=9B=9E=E5=A4=8D=E5=8F=8C=E5=90=91=E6=98=A0=E5=B0=84?= =?UTF-8?q?=EF=BC=88Codex=20=E4=BF=A1=E5=B0=81=20=E2=87=84=20DSH=20?= =?UTF-8?q?=E7=AD=94=E6=A1=88=E5=8D=A1=E7=89=87=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 19 +++++++++++ lib/convert.mjs | 63 +++++++++++++++++++++++++++++++++++-- lib/export-codex.js | 54 +++++++++++++++++++++++++++++++ package.json | 2 +- test/convert-order.test.mjs | 46 +++++++++++++++++++++++++++ test/export-codex.test.mjs | 51 +++++++++++++++++++++++++++++- 6 files changed, 231 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index efe1cda..7147689 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 1.10.6 — 2026-11-12 + +- **Question answers survive the round trip in both directions.** + - Codex → DSH: Codex stores an answer as bare markup + (`[{questionItemId, question, answer}]`), + which DSH printed as source text. The converter now recognises that envelope + and emits a `user/message` with `source.kind = 'user-question-reply'` plus the + `{questions, answers}` JSON DSH's user-questions UI reads, so it renders as an + answered-question card (the Host folds exactly this shape to settle a + question). + - DSH → Codex: `dshEventsToCodexMessages` writes that card back as the Codex + envelope instead of the raw JSON, rebuilding `questionItemId` as + `["request_user_input_async","call_…",]` so a re-import yields the same + card. + - Verified on a real rollout (234 messages): 2 answer cards, no markup left; + round trip keeps callId, question id, question and answer identical. +- Tests: envelope → card (incl. a skipped answer and plain text staying plain), + card → envelope, and the full round trip. 97 total. + ## 1.10.5 — 2026-11-12 - **Fixed: 管理已同步 could not show some imported chats, so they were diff --git a/lib/convert.mjs b/lib/convert.mjs index b00dead..a3a2dae 100644 --- a/lib/convert.mjs +++ b/lib/convert.mjs @@ -21,6 +21,60 @@ /** Placeholder text for tool results the source tool never recorded. */ export const TOOL_RESULT_PLACEHOLDER = '[工具结果未记录:源工具不保存调用结果,仅保留调用信息]' +/** Codex wraps a question answer in this envelope; DSH has no renderer for it. */ +const QUESTION_REPLY_ENVELOPE = /^\s*\s*([\s\S]*?)\s*<\/send_user_message_question_reply>\s*$/u + +/** + * Translate a Codex question-reply message into the payload DSH's user-questions + * UI reads back. Codex stores the answer as a bare envelope + * (`[{questionItemId, question, answer}]`), + * which DSH would print as literal markup; a `user/message` carrying + * `source.kind = 'user-question-reply'` and the `{questions, answers}` JSON is + * rendered as an answered-question card instead. + * @param blocks - the normalized content blocks of one user message + * @returns {{callId: string, content: Array}|undefined} the card payload + */ +export function questionReplyPayload(blocks) { + if (!Array.isArray(blocks) || blocks.length !== 1 || blocks[0]?.type !== 'text') return undefined + const matched = QUESTION_REPLY_ENVELOPE.exec(typeof blocks[0].text === 'string' ? blocks[0].text : '') + if (matched === null) return undefined + let items + try { + items = JSON.parse(matched[1]) + } catch { + return undefined + } + if (!Array.isArray(items) || items.length === 0) return undefined + const questions = [] + const answers = [] + let callId + for (let i = 0; i < items.length; i += 1) { + const item = items[i] + if (item === null || typeof item !== 'object') return undefined + const question = typeof item.question === 'string' ? item.question.trim() : '' + if (question.length === 0) continue + const id = typeof item.questionItemId === 'string' && item.questionItemId.length > 0 + ? item.questionItemId + : `codex-question-${i}` + questions.push({ id, question }) + const answer = typeof item.answer === 'string' ? item.answer.trim() : '' + answers.push({ id, selected: answer.length > 0 ? [answer] : [] }) + if (callId === undefined) { + // The item id is `["request_user_input_async","call_…",0]`; keep the call id + // so the card can be paired with its tool call when one was imported. + try { + const parsed = JSON.parse(id) + if (Array.isArray(parsed) && typeof parsed[1] === 'string' && parsed[1].length > 0) callId = parsed[1] + } catch { /* not the composite id — fall back below */ } + } + } + if (questions.length === 0) return undefined + return { + callId: callId ?? 'codex-question', + content: [{ type: 'text', text: JSON.stringify({ questions, answers }) }], + } +} + /** * Fold normalized messages into a balanced DSH event list (seq 0..n-1). * @param messages - normalized message stream in chronological order. @@ -91,10 +145,15 @@ export function buildDshEvents(messages, options = {}) { // 无法打开(issue #2)。 openStepFor(turn, step, message.time) if (message.blocks.length > 0) { + // A Codex question answer is recorded as markup; DSH renders it as an + // answered-question card only when the message says so in its source. + const reply = questionReplyPayload(message.blocks) push('user/message', message.time, { role: 'user', - source: { kind: 'user' }, - content: message.blocks, + source: reply === undefined + ? { kind: 'user' } + : { kind: 'user-question-reply', callId: reply.callId, outcome: 'answered' }, + content: reply === undefined ? message.blocks : reply.content, id: randomId(), }, 'append') if (firstUserSeq === undefined) firstUserSeq = events.length - 1 diff --git a/lib/export-codex.js b/lib/export-codex.js index 5435e20..f2d6304 100644 --- a/lib/export-codex.js +++ b/lib/export-codex.js @@ -70,6 +70,55 @@ function eventAssistantText(event) { return blockText(inner) } +/** + * The Codex form of a DSH question-reply message. + * + * DSH records an answered question as a `user/message` whose `source.kind` is + * `user-question-reply` and whose text is `{questions, answers}` JSON. Codex has + * no such field: it stores the answer as a bare + * `[{questionItemId, question, answer}]` + * envelope, and that is also what its UI understands. Exporting the JSON verbatim + * would show raw JSON in Codex, so translate it. + * @param {object} event - a DSH `user/message` event + * @returns {string|undefined} the envelope text, or undefined for other messages + */ +export function codexQuestionReplyText(event) { + const source = event?.data?.source + if (source?.kind !== 'user-question-reply') return undefined + let payload + try { + payload = JSON.parse(eventUserText(event)) + } catch { + return undefined + } + if (payload === null || typeof payload !== 'object' || !Array.isArray(payload.questions) || payload.questions.length === 0) { + return undefined + } + const answers = Array.isArray(payload.answers) ? payload.answers : [] + const items = [] + for (let i = 0; i < payload.questions.length; i += 1) { + const question = payload.questions[i] + const prompt = typeof question?.question === 'string' ? question.question : '' + if (prompt.length === 0) continue + const id = typeof question?.id === 'string' ? question.id : `codex-question-${i}` + const answer = answers.find((item) => item?.id === id) ?? {} + const selected = Array.isArray(answer.selected) ? answer.selected.filter((v) => typeof v === 'string') : [] + const custom = typeof answer.custom === 'string' ? answer.custom.trim() : '' + items.push({ + // Codex names the answer slot as + // `["request_user_input_async","call_…",]`, so a re-import rebuilds + // the same id and the same card. + questionItemId: typeof source.callId === 'string' && source.callId.length > 0 + ? JSON.stringify(['request_user_input_async', source.callId, i]) + : id, + question: prompt, + answer: [...selected, ...(custom.length > 0 ? [custom] : [])].join(','), + }) + } + if (items.length === 0) return undefined + return `\n${JSON.stringify(items)}\n\n` +} + /** * Fold a DSH event log into Codex response_item messages (text only). * @param {object[]} events @@ -78,6 +127,11 @@ export function dshEventsToCodexMessages(events) { const out = [] for (const event of events ?? []) { if (event.type === 'user/message') { + const reply = codexQuestionReplyText(event) + if (reply !== undefined) { + out.push({ role: 'user', text: reply, time: event.time ?? Date.now() }) + continue + } const text = eventUserText(event).trim() if (text && !skipUserText(text)) out.push({ role: 'user', text, time: event.time ?? Date.now() }) } else if (event.type === 'assistant/message') { diff --git a/package.json b/package.json index d718c3d..757f6f5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.10.5", + "version": "1.10.6", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/test/convert-order.test.mjs b/test/convert-order.test.mjs index 36a591b..e555ceb 100644 --- a/test/convert-order.test.mjs +++ b/test/convert-order.test.mjs @@ -102,3 +102,49 @@ test('multiple consecutive user turns each open their own leading step', () => { assert.equal(kinds[i - 1], 'step/start', `user/message at ${i} preceded by step/start`) } }) + +test('convert: a Codex question-reply envelope becomes a rendered answer card', () => { + const item = { + questionItemId: '["request_user_input_async","call_4326ec8a195049adb5882d6e601f5425",0]', + question: '是否允许 ai-service 持有专用 manage_channels 凭据?', + answer: '允许专用 manage_channels 凭据(推荐)', + } + // Codex stores the answer as markup; DSH only renders a card when the message + // says it is a question reply, so the importer must translate it. + const envelope = '\n' + JSON.stringify([item]) + '\n\n' + const events = buildDshEvents([ + { role: 'user', time: 1000, blocks: [{ type: 'text', text: envelope }] }, + { role: 'assistant', time: 2000, blocks: [{ type: 'text', text: '收到' }] }, + ], { toolEvents: true }) + + const user = events.find((e) => e.type === 'user/message') + assert.equal(user.surfaceOp, 'append', 'the reply card reads append-origin messages') + assert.deepEqual(user.data.source, { + kind: 'user-question-reply', + callId: 'call_4326ec8a195049adb5882d6e601f5425', + outcome: 'answered', + }) + const payload = JSON.parse(user.data.content[0].text) + assert.equal(payload.questions[0].question, item.question) + assert.deepEqual(payload.answers[0].selected, [item.answer]) + assert.ok(!JSON.stringify(user.data.content).includes('send_user_message_question_reply'), 'no raw markup left') + assertSurfaceInsideSteps(events) +}) + +test('convert: a skipped question answer and plain text keep their own shapes', () => { + const skipped = { + questionItemId: '["request_user_input_async","call_skip",0]', + question: '要发布到哪个环境?', + answer: '', + } + const events = buildDshEvents([ + { role: 'user', time: 1000, blocks: [{ type: 'text', text: '' + JSON.stringify([skipped]) + '' }] }, + { role: 'user', time: 2000, blocks: [{ type: 'text', text: '普通提问' }] }, + ], { toolEvents: true }) + + const replies = events.filter((e) => e.type === 'user/message') + assert.equal(replies[0].data.source.kind, 'user-question-reply') + assert.deepEqual(JSON.parse(replies[0].data.content[0].text).answers[0].selected, [], 'a skipped answer selects nothing') + assert.deepEqual(replies[1].data.source, { kind: 'user' }, 'plain text stays a normal user message') + assert.equal(replies[1].data.content[0].text, '普通提问') +}) diff --git a/test/export-codex.test.mjs b/test/export-codex.test.mjs index d61a437..6510287 100644 --- a/test/export-codex.test.mjs +++ b/test/export-codex.test.mjs @@ -3,7 +3,8 @@ import assert from 'node:assert/strict' import { mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { buildRolloutJsonl, codexGoalSnapshot, dshEventsToCodexMessages, exportToCodex, goalOf, listExportCatalog, titleOf } from '../lib/export-codex.js' +import { buildRolloutJsonl, codexGoalSnapshot, codexQuestionReplyText, dshEventsToCodexMessages, exportToCodex, goalOf, listExportCatalog, titleOf } from '../lib/export-codex.js' +import { questionReplyPayload } from '../lib/convert.mjs' test('dshEventsToCodexMessages keeps user and assistant text', () => { const msgs = dshEventsToCodexMessages([ @@ -375,3 +376,51 @@ test('listExportCatalog & exportToCodex: handle unchanged, updated, and missing assert.match(dryLines.join('\n'), /\[would-export\] codex-codex-uuid-1 4 messages -> .* \(new copy; original Codex thread not overwritten\)/) assert.match(dryLines.join('\n'), /would-export 1, skipped 0, empty 0/) }) + +test('export: a DSH question answer is written as the Codex reply envelope', () => { + const callId = 'call_4326ec8a195049adb5882d6e601f5425' + const questionId = '["request_user_input_async","call_4326ec8a195049adb5882d6e601f5425",0]' + const event = { + type: 'user/message', + time: 100, + surfaceOp: 'append', + data: { + role: 'user', + id: 'm-1', + source: { kind: 'user-question-reply', callId, outcome: 'answered' }, + content: [{ + type: 'text', + text: JSON.stringify({ + questions: [{ id: questionId, question: '是否允许专用凭据?' }], + answers: [{ id: questionId, selected: ['允许'], custom: '' }], + }), + }], + }, + } + + const text = codexQuestionReplyText(event) + assert.ok(text.startsWith(''), 'codex reads this envelope') + assert.ok(text.trimEnd().endsWith('')) + assert.ok(!text.includes('"questions"'), 'the DSH JSON must not leak into the rollout') + const items = JSON.parse(text.split('\n')[1]) + assert.deepEqual(items, [{ questionItemId: questionId, question: '是否允许专用凭据?', answer: '允许' }]) + + const msgs = dshEventsToCodexMessages([event]) + assert.equal(msgs.length, 1) + assert.equal(msgs[0].text, text, 'the reply is exported as one user message') + + // Round trip: the exported envelope imports back as the same answered card. + const back = questionReplyPayload([{ type: 'text', text }]) + const payload = JSON.parse(back.content[0].text) + assert.equal(back.callId, callId) + assert.equal(payload.questions[0].id, questionId) + assert.equal(payload.questions[0].question, '是否允许专用凭据?') + assert.deepEqual(payload.answers[0].selected, ['允许']) +}) + +test('export: a plain user message still exports as plain text', () => { + const msgs = dshEventsToCodexMessages([ + { type: 'user/message', time: 1, data: { source: { kind: 'user' }, content: [{ type: 'text', text: '普通提问' }] } }, + ]) + assert.deepEqual(msgs, [{ role: 'user', text: '普通提问', time: 1 }]) +}) From ba72eb7808075d7b2a1797dea147f67c16295a28 Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 16:31:07 +0800 Subject: [PATCH 14/18] =?UTF-8?q?fix:=201.10.7=20=E2=80=94=20=E9=97=AE?= =?UTF-8?q?=E7=AD=94=E5=8D=A1=E7=89=87=E4=B8=8D=E5=86=8D=E5=8D=A1=E4=BD=8F?= =?UTF-8?q?=20v0=E2=86=92v4=20=E8=BF=81=E7=A7=BB=EF=BC=88=E8=BF=81?= =?UTF-8?q?=E7=A7=BB=E6=9C=9F=E9=99=8D=E7=BA=A7=E4=B8=BA=20user=EF=BC=8C?= =?UTF-8?q?=E8=BF=81=E7=A7=BB=E5=90=8E=E6=81=A2=E5=A4=8D=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 15 ++++++++++++ lib/convert.mjs | 44 ++++++++++++++++++++++++++++++++++++ lib/import-service.js | 9 +++++++- package.json | 2 +- test/import-service.test.mjs | 33 +++++++++++++++++++++++++++ 5 files changed, 101 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7147689..aead64e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.10.7 — 2026-11-12 + +- **Fixed: importing any chat with an answered question failed** with + `cannot safely transform unclassified message source`. The v2→v3 migration + stage validates `source.kind` against a closed set that does not contain + `user-question-reply`, while the *current* (v4) write gate does accept it — so + 1.10.6's card shape broke the v0→v4 chain. The importer now writes those + messages through the migration as plain `user` messages and restores the reply + kind on the migrated events (matched by message id), which the current gate + validates and the questions projection reads. +- Re-imported the thread that failed (`codex-01a1b4be…`): 6262 messages → + 60893 events, **48 answer cards**, no migration error. +- Test: import a reply envelope end to end, assert the stored source survived and + the log still encodes/restores in the installed format. 98 tests total. + ## 1.10.6 — 2026-11-12 - **Question answers survive the round trip in both directions.** diff --git a/lib/convert.mjs b/lib/convert.mjs index a3a2dae..36a47b1 100644 --- a/lib/convert.mjs +++ b/lib/convert.mjs @@ -75,6 +75,50 @@ export function questionReplyPayload(blocks) { } } +/** + * Temporarily downgrade `user-question-reply` sources to `user` before the + * v0→v4 migration chain runs. + * + * The chain's v2→v3 stage validates `source.kind` against a closed set that does + * not contain `user-question-reply` ("cannot safely transform unclassified + * message source"), while the current (v4) write gate does accept it — the + * user-questions projection reads exactly that kind. So the reply is written + * through the migration as a plain user message and the kind is restored on the + * migrated events. + * @param events - the v0 event list about to be migrated (mutated in place) + * @returns {Map} message id → original reply source + */ +export function hideReplySources(events) { + const hidden = new Map() + for (const event of events ?? []) { + if (event?.type !== 'user/message') continue + const source = event.data?.source + if (source?.kind !== 'user-question-reply' || typeof event.data?.id !== 'string') continue + hidden.set(event.data.id, source) + event.data.source = { kind: 'user' } + } + return hidden +} + +/** + * Put the `user-question-reply` kinds back on the migrated events. + * @param events - current-format events (mutated in place) + * @param hidden - the map returned by {@link hideReplySources} + * @returns {number} how many sources were restored + */ +export function restoreReplySources(events, hidden) { + if (!(hidden instanceof Map) || hidden.size === 0) return 0 + let restored = 0 + for (const event of events ?? []) { + if (event?.type !== 'user/message') continue + const source = hidden.get(event.data?.id) + if (source === undefined) continue + event.data.source = source + restored += 1 + } + return restored +} + /** * Fold normalized messages into a balanced DSH event list (seq 0..n-1). * @param messages - normalized message stream in chronological order. diff --git a/lib/import-service.js b/lib/import-service.js index a77d4b0..45cd9ac 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -24,7 +24,7 @@ import { join } from 'node:path' import { listCodexSessions, parseCodexSession, isSubagentThread } from './codex-reader.mjs' import { loadCodexIndex, codexTitleOf, codexProjectOf, codexProjectNameForPath, codexOriginOf, baseName } from './codex-index.mjs' -import { buildDshEvents, deriveImportTitle } from './convert.mjs' +import { buildDshEvents, deriveImportTitle, hideReplySources, restoreReplySources } from './convert.mjs' import { migrateToCurrent } from './session-migrate.mjs' import { normalizePersistence, isSessionBusyError } from './persistence-facade.mjs' import { attachSessionsToWorkspaces, listImportedSessions } from './attach-workspaces.mjs' @@ -493,6 +493,12 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo // rejects v0 anyway ("encodeCurrent requires Session format v3"/"v4"), so // a silent fallback would break the import while hiding the root cause // (missing migration packages / data-dependent migration failure). + // The v2→v3 migration stage only classifies a closed set of `source.kind` + // values, so an answered question travels through the chain as a plain user + // message and gets its `user-question-reply` kind back on the migrated + // events (the current write gate accepts it — the questions projection + // reads it to settle the question). + const hiddenReplies = hideReplySources(events) const { header: currentHeader, events: currentEvents } = (() => { try { return migrateToCurrent(importHeader, events) @@ -500,6 +506,7 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo throw new Error(`import-codex: session ${candidate.id} could not be migrated to the current session format: ${error.message}`) } })() + restoreReplySources(currentEvents, hiddenReplies) if (existing.has(candidate.id)) { let oldEvents = [] try { diff --git a/package.json b/package.json index 757f6f5..b9e23f9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.10.6", + "version": "1.10.7", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index c7dcb32..da11df3 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -738,3 +738,36 @@ test('import-codex: a failed flush surfaces instead of reporting success', async ) assert.deepEqual(ops, ['append', 'flush', 'close'], 'cleanup attempted before surfacing the error') }) + +test('import-codex: a question answer survives migration and passes the current write gate', async () => { + // Regression: the v2→v3 stage rejects unknown `source.kind` values + // ("cannot safely transform unclassified message source"), which aborted the + // whole import once answers were converted to reply cards. + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-reply-')) + const id = makeSession(root, 'reply') + const item = { + questionItemId: '["request_user_input_async","call_4326ec8a195049adb5882d6e601f5425",0]', + question: '是否允许专用 manage_channels 凭据?', + answer: '允许专用 manage_channels 凭据(推荐)', + } + appendMessages(root, 'reply', [ + { role: 'user', text: '\n' + JSON.stringify([item]) + '\n\n' }, + { role: 'assistant', text: 'assistant-reply-2' }, + ]) + const { persistence, ctx, store, metas } = stubPersistence() + + await importCodex(ctx, persistence, {}, root) + const reply = (store.get(id) ?? []).find((e) => e.type === 'user/message' && e.data?.source?.kind === 'user-question-reply') + assert.ok(reply !== undefined, 'the answer is stored as a reply card, not plain text') + assert.equal(reply.data.source.callId, 'call_4326ec8a195049adb5882d6e601f5425') + assert.equal(reply.surfaceOp, 'append') + const payload = JSON.parse(reply.data.content[0].text) + assert.deepEqual(payload.answers[0].selected, [item.answer]) + + // The written log must still be writable/readable in the installed format. + const { sessionFormatCatalog } = await import('@deepseek-ai/dsh-session-format-catalog') + for (const event of store.get(id) ?? []) sessionFormatCatalog.encodeCurrentEvent(event) + const { restoreReleasedV4Artifact } = await import('@deepseek-ai/dsh-session-format-v3-to-v4') + const { KNOWN_SESSION_EVENT_TYPES } = await import('@deepseek-ai/dsh-session') + restoreReleasedV4Artifact({ header: metas.get(id), events: store.get(id) ?? [], inheritedEventCount: 0 }, KNOWN_SESSION_EVENT_TYPES) +}) From a3c310a288583a556642d651dfb4ac79d9d4be2f Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 16:38:44 +0800 Subject: [PATCH 15/18] =?UTF-8?q?feat:=201.10.8=20=E2=80=94=20=E5=8D=95?= =?UTF-8?q?=E4=B8=AA=E4=BC=9A=E8=AF=9D=E8=BF=81=E7=A7=BB=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E5=8F=AA=E8=B7=B3=E8=BF=87=E5=B9=B6=E6=B1=87=E6=8A=A5=EF=BC=8C?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E4=B8=AD=E6=96=AD=E6=95=B4=E6=89=B9=E5=AF=BC?= =?UTF-8?q?=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 13 +++++++++++++ lib/import-service.js | 30 ++++++++++++++++++------------ package.json | 2 +- test/import-service.test.mjs | 28 ++++++++++++++++++++++++++-- 4 files changed, 58 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aead64e..c3e7f2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.10.8 — 2026-11-12 + +- **One untransformable chat no longer aborts the whole import.** Until now a + single session the migration chain could not convert threw out of + `importCodex`, so nothing else in the batch was written (that is exactly how + 1.10.6's reply-card regression killed an import of ~90 chats). The failure is + now per session: it is reported as + `[skipped-migration] : `, counted as `migration-failed N` in the + result line, followed by a hint, and the remaining chats import normally. + The v0 fallback stays impossible — a v0 log cannot be written at all. +- `options.migrateToCurrent` is an injectable seam so the skip path is covered by + a test (forced failure on one session, the other still imported). 99 tests. + ## 1.10.7 — 2026-11-12 - **Fixed: importing any chat with an answered question failed** with diff --git a/lib/import-service.js b/lib/import-service.js index 45cd9ac..68effbf 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -459,6 +459,7 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo let skipped = 0 let empty = 0 let busy = 0 + const migrationFailed = [] for (const candidate of selected) { const { messages } = candidate.parsed if (messages.length === 0) { @@ -489,23 +490,25 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo ? options.agentPreset : DEFAULT_IMPORT_AGENT_PRESET, } - // Fail LOUDLY instead of falling back to a v0 write: real DSH persistence - // rejects v0 anyway ("encodeCurrent requires Session format v3"/"v4"), so - // a silent fallback would break the import while hiding the root cause - // (missing migration packages / data-dependent migration failure). + // A conversion fallback to v0 stays impossible (real DSH persistence refuses + // v0 with "encodeCurrent requires Session format v3"/"v4"), but one session + // whose data the migration chain cannot transform must not abort the batch: + // it is reported and skipped so the remaining chats still import. // The v2→v3 migration stage only classifies a closed set of `source.kind` // values, so an answered question travels through the chain as a plain user // message and gets its `user-question-reply` kind back on the migrated // events (the current write gate accepts it — the questions projection // reads it to settle the question). const hiddenReplies = hideReplySources(events) - const { header: currentHeader, events: currentEvents } = (() => { - try { - return migrateToCurrent(importHeader, events) - } catch (error) { - throw new Error(`import-codex: session ${candidate.id} could not be migrated to the current session format: ${error.message}`) - } - })() + let migrated + try { + migrated = (options.migrateToCurrent ?? migrateToCurrent)(importHeader, events) + } catch (error) { + migrationFailed.push({ id: candidate.id, reason: String(error?.message ?? error) }) + lines.push(` [skipped-migration] ${candidate.id}: ${error?.message ?? error}`) + continue + } + const { header: currentHeader, events: currentEvents } = migrated restoreReplySources(currentEvents, hiddenReplies) if (existing.has(candidate.id)) { let oldEvents = [] @@ -553,7 +556,10 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo lines.push(` [imported] ${candidate.id} ${candidate.cwd ?? '(no cwd)'} ${messages.length} messages -> ${currentEvents.length} events`) } const verb = dryRun ? 'would-import' : 'imported' - lines.push(`[codex] result: ${verb} ${imported}, updated ${updated}, skipped ${skipped}, empty ${empty}, busy ${busy}, subagent-skipped ${skippedSubagent}, side-chat-skipped ${skippedSideChat}, oversized-skipped ${skippedBig}, unreadable ${unreadable}`) + lines.push(`[codex] result: ${verb} ${imported}, updated ${updated}, skipped ${skipped}, empty ${empty}, busy ${busy}, migration-failed ${migrationFailed.length}, subagent-skipped ${skippedSubagent}, side-chat-skipped ${skippedSideChat}, oversized-skipped ${skippedBig}, unreadable ${unreadable}`) + if (migrationFailed.length > 0) { + lines.push(` [hint] ${migrationFailed.length} 个会话无法转换到当前会话格式,已跳过(其余已正常导入);可用 /repair-sessions --fix 修复已导入会话,或把上面的报错发给我定位`) + } if (busy > 0) { lines.push(` [hint] ${busy} 个会话正在 DSH 中打开(写句柄被占用),本次未更新;关闭这些对话后重新导入即可补齐`) } diff --git a/package.json b/package.json index b9e23f9..b9f7065 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.10.7", + "version": "1.10.8", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index da11df3..7c155f5 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -12,6 +12,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { importCodex, listImportCatalog } from '../lib/import-service.js' import { foldGoal } from '@deepseek-ai/dsh-goal' +import { migrateToCurrent as migrateToCurrentReal } from '../lib/session-migrate.mjs' // Build a raw response_item event (NOT a string) so the file body below can be // JSON.stringify'd exactly once per line. @@ -100,7 +101,7 @@ test('import-codex: sub-agent threads are filtered by default', async () => { const lines = await importCodex(ctx, persistence, {}, root) const report = lines.join('\n') - assert.match(report, /\[codex\] result: imported 1, updated 0, skipped 0, empty 0, busy 0, subagent-skipped 1/) + assert.match(report, /\[codex\] result: imported 1, updated 0, skipped 0, empty 0, busy 0, migration-failed 0, subagent-skipped 1/) assert.ok(store.has(main), 'main session imported') assert.ok(!store.has(sub), 'sub-agent thread must NOT be imported by default') assert.equal(metas.get(main)?.agentPreset, 'standard', 'imported sessions use the standard preset, not 创造模式') @@ -307,7 +308,7 @@ test('import-codex: dryRun lists candidates but writes nothing', async () => { const report = lines.join('\n') assert.match(report, /\[codex\] dry-run: no sessions will be written/) assert.ok(report.includes(`[would-import] ${main}`), 'dry-run lists the main session') - assert.match(report, /would-import 1, updated 0, skipped 0, empty 0, busy 0, subagent-skipped 1/) + assert.match(report, /would-import 1, updated 0, skipped 0, empty 0, busy 0, migration-failed 0, subagent-skipped 1/) assert.equal(store.size, 0, 'dry-run must not create sessions') }) @@ -771,3 +772,26 @@ test('import-codex: a question answer survives migration and passes the current const { KNOWN_SESSION_EVENT_TYPES } = await import('@deepseek-ai/dsh-session') restoreReleasedV4Artifact({ header: metas.get(id), events: store.get(id) ?? [], inheritedEventCount: 0 }, KNOWN_SESSION_EVENT_TYPES) }) + +test('import-codex: one session the migration cannot transform is skipped, the rest still import', async () => { + // The v2→v3 stage rejected `user-question-reply` and aborted the WHOLE batch; + // a single untransformable chat must now be reported and skipped instead. + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-migskip-')) + const good = makeSession(root, 'good') + const bad = makeSession(root, 'bad') + const { persistence, ctx, store } = stubPersistence() + + const lines = await importCodex(ctx, persistence, { + migrateToCurrent(header, events) { + if (header.id === bad) throw new Error('cannot safely transform unclassified message source') + return migrateToCurrentReal(header, events) + }, + }, root) + + const report = lines.join('\n') + assert.match(report, /\[skipped-migration\] codex-sess-bad: cannot safely transform unclassified message source/) + assert.match(report, /migration-failed 1/) + assert.match(report, /imported 1/, 'the other session still imported') + assert.ok(store.has(good), 'the healthy session was written') + assert.ok(!store.has(bad), 'the untransformable one was not written') +}) From 407234ca2beaed46347abe3d8c3e748c153bd17e Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 16:41:09 +0800 Subject: [PATCH 16/18] =?UTF-8?q?fix:=201.10.9=20=E2=80=94=20=E8=BF=87?= =?UTF-8?q?=E6=BB=A4=E8=BF=BD=E5=8A=A0=E5=9C=A8=E6=AD=A3=E6=96=87=E5=90=8E?= =?UTF-8?q?=E7=9A=84=20=20=E8=AE=B0=E5=BF=86=E5=BC=95?= =?UTF-8?q?=E7=94=A8=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 15 +++++++++++++++ lib/codex-reader.mjs | 24 ++++++++++++++++++++++-- package.json | 2 +- test/codex-reader.test.mjs | 25 +++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3e7f2d..e8a27c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.10.9 — 2026-11-12 + +- **Memory citations no longer leak into imported transcripts.** + `MEMORY.md:405-407|note=[…]…` + is a Codex tooling block, but unlike the other envelopes it is **appended to + real content** (`… 已完成。\n…`), so the leading-tag filter + could not see it — it showed up verbatim at the end of imported answers and as + a standalone user block. The reader now cuts the envelope out of the middle of + a text block and drops the block when nothing else remained. + Measured on this machine: 259 of 1287 rollouts carry the block (417 user, 147 + assistant, 49 developer occurrences); after the fix, 125 parsed rollouts with + citations leak **0**. +- Tests: appended citation stripped from an answer, citation-only message + dropped. 100 tests total. + ## 1.10.8 — 2026-11-12 - **One untransformable chat no longer aborts the whole import.** Until now a diff --git a/lib/codex-reader.mjs b/lib/codex-reader.mjs index bb7290b..dd54499 100644 --- a/lib/codex-reader.mjs +++ b/lib/codex-reader.mjs @@ -78,7 +78,7 @@ export function listCodexSessions(root) { * `` and `` are deliberately * KEPT: the first is real content, the second carries the user's own answer. */ -const SYSTEM_BLOCK = /^<(environment_context|permissions instructions|turn_aborted|request_id|model|end_of_conversation|turn_id|recommended_plugins|skills_instructions|apps_instructions|plugins_instructions|collaboration_mode|multi_agent_mode|app-context|citation_entries|INSTRUCTIONS|skill|skills|guardian_tool_descriptions|codex_internal_context|node_repl_review_evidence|in-app-browser-context|external_browser_tabs|external_codex_apps_[a-z0-9_]*|heartbeat)(?:\s[^>]*)?>/u +const SYSTEM_BLOCK = /^<(environment_context|permissions instructions|turn_aborted|request_id|model|end_of_conversation|turn_id|recommended_plugins|skills_instructions|apps_instructions|plugins_instructions|collaboration_mode|multi_agent_mode|app-context|citation_entries|oai-mem-citation|INSTRUCTIONS|skill|skills|guardian_tool_descriptions|codex_internal_context|node_repl_review_evidence|in-app-browser-context|external_browser_tabs|external_codex_apps_[a-z0-9_]*|heartbeat)(?:\s[^>]*)?>/u /** * A codex placeholder that arrives as a user message when the incremental @@ -92,6 +92,22 @@ const AGENTS_MD_BLOCK = /^# AGENTS\.md instructions/u /** Raw image fragments (`` / ``) as standalone blocks. */ const IMAGE_BLOCK = /^\s*]*>\s*$/u const IMAGE_CLOSE = /^\s*<\/image>\s*$/u +/** + * Envelopes that Codex appends to otherwise-real text, so they have to be cut + * out of the middle of a block rather than dropped as a whole block. + */ +const TRAILING_ENVELOPES = /[\s\S]*?<\/oai-mem-citation>/gu + +/** + * Remove appended citation envelopes from one text block. + * @param text - raw block text + * @returns cleaned text, or undefined when nothing but envelopes remained + */ +function stripTrailingEnvelopes(text) { + if (!text.includes('…`), so a + // leading-tag test cannot see them; cut them out where they sit. + const cleaned = stripTrailingEnvelopes(text) + return cleaned === undefined ? undefined : { type: 'text', text: cleaned } } case 'reasoning': { const text = flattenReasoningText(block.summary ?? block.text) diff --git a/package.json b/package.json index b9f7065..0da9fba 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.10.8", + "version": "1.10.9", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", diff --git a/test/codex-reader.test.mjs b/test/codex-reader.test.mjs index c687016..37c30c9 100644 --- a/test/codex-reader.test.mjs +++ b/test/codex-reader.test.mjs @@ -222,6 +222,7 @@ test('new schema: codex desktop envelopes are dropped, real content is kept', as { type: 'input_text', text: '\nContinue working toward the objective\n' }, { type: 'input_text', text: '{"page_id":null}' }, { type: 'input_text', text: '\nstuff\n' }, + { type: 'input_text', text: '\n\nMEMORY.md:405-407|note=[ammo scope and validation boundaries]\n\n\n\n' }, { type: 'input_text', text: '' }, { type: 'input_text', text: '帮我改一下这个页面' }, ]), @@ -460,3 +461,27 @@ test('tool inputs: function arguments objects and empty strings; custom calls ke const calls = (await parseCodexSession(file)).messages.flatMap(m => m.blocks).filter(b => b.type === 'tool-call') assert.deepEqual(calls.map(b => b.arguments), ['{"text":"object"}', '', 'legacy input', 'custom input']) }) + +test('reader: an appended memory citation is cut out of real assistant text', async () => { + // Codex appends `…` AFTER real content, so + // a leading-tag filter cannot see it and the imported transcript showed the + // whole envelope. It must be removed while the answer survives. + const events = [ + msg('T1', '2026-08-17T10:00:01Z', 'user', [{ type: 'input_text', text: '部署完成了吗?' }]), + msg('T2', '2026-08-17T10:00:06Z', 'assistant', [{ + type: 'output_text', + text: '测试平台首页可访问,AI 服务本地制品已构建完成。\n\n\n\nMEMORY.md:405-407|note=[ammo scope and validation boundaries]\n\n\n\n', + }]), + msg('T3', '2026-08-17T10:00:09Z', 'assistant', [{ + type: 'output_text', + text: '\n\nMEMORY.md:1-2|note=[x]\n\n', + }]), + ] + const file = nextFile('mem-citation'); write(file, rolloutOf(events)) + const { messages } = await parseCodexSession(file) + assert.equal(messages.length, 2, 'citation-only message is dropped entirely') + const answer = messages[1].blocks[0].text + assert.match(answer, /AI 服务本地制品已构建完成/) + assert.ok(!answer.includes('oai-mem-citation'), 'no envelope left in the answer') + assert.ok(!answer.includes('MEMORY.md'), 'no citation entries left in the answer') +}) From fcfd2c3e2229a6486822e782ec099f47df077705 Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 16:43:01 +0800 Subject: [PATCH 17/18] =?UTF-8?q?feat:=201.10.10=20=E2=80=94=20=E6=89=B9?= =?UTF-8?q?=E9=87=8F=E5=AF=BC=E5=85=A5=E6=9C=89=E4=BC=9A=E8=AF=9D=E8=BF=81?= =?UTF-8?q?=E7=A7=BB=E5=A4=B1=E8=B4=A5=E6=97=B6=E7=BB=93=E6=9E=9C=E9=A1=B5?= =?UTF-8?q?=E6=98=BE=E7=A4=BA=E8=AD=A6=E7=A4=BA=EF=BC=88=E9=83=A8=E5=88=86?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E6=9C=AA=E5=AF=BC=E5=85=A5=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 11 +++++++++++ lib/client.js | 44 +++++++++++++++++++++++++++++++++++++------- package.json | 2 +- 3 files changed, 49 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e8a27c9..cff056c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 1.10.10 — 2026-11-12 + +- **A partial import now says so.** When the batch skipped sessions the + migration chain could not transform, the result page still showed a green + check and “导入完成”, so a run that imported 1 of 90 chats looked like success. + The panel now switches to a warning state (`migration-failed > 0`): warning + icon, title 「部分会话未导入」 / “Some chats were not imported”, and the + `[skipped-migration]` lines plus the hint, on a warning-tinted block. +- Reads the count from the host report (`migration-failed N`) for both the HTTP + path and the `/import-codex` command fallback. + ## 1.10.9 — 2026-11-12 - **Memory citations no longer leak into imported transcripts.** diff --git a/lib/client.js b/lib/client.js index 789e3f0..4e697ef 100644 --- a/lib/client.js +++ b/lib/client.js @@ -1063,6 +1063,7 @@ function labels(lang) { tipSubagent: '作为子代理展示仅用于归类组织;勾选后将作为独立 Codex 会话导出,不会与父会话合并', error: '无法读取目录。请完全退出并重新启动 dsh web(只刷新页面不够,后台插件不会更新)。', importedOk: '导入完成', + importedPartial: '部分会话未导入', reloadHint: '会话已写入。侧边栏列表由 dsh 自己维护,若没看到新对话,可点「刷新列表」(只重载页面,不重启 dsh)。', reloadNow: '刷新列表', reloadLater: '关闭', @@ -1156,6 +1157,7 @@ function labels(lang) { tipSubagent: 'Shown nested for organization; selected child exports separately, not merged.', error: 'Could not load catalog. Fully quit and restart dsh web (a page refresh does not reload the host plugin).', importedOk: 'Import finished', + importedPartial: 'Some chats were not imported', reloadHint: 'The sessions are written. The sidebar list is owned by dsh — if the new chats are missing, use Refresh list (a page reload, no dsh restart).', reloadNow: 'Refresh list', reloadLater: 'Close', @@ -1312,6 +1314,21 @@ function TriBox({ state, disabled }) { ) } +/** + * Read the partial-failure part of an import report: how many sessions the + * migration chain refused, and the lines that explain why. + * @param {string|undefined} text - the host's newline-separated result text + * @returns {{failed: number, lines: string[]}|null} null when nothing failed + */ +function migrationFailureReport(text) { + if (typeof text !== 'string') return null + const matched = /migration-failed (\d+)/u.exec(text) + const failed = matched === null ? 0 : Number(matched[1]) + if (!Number.isFinite(failed) || failed <= 0) return null + const lines = text.split('\n').filter((line) => /^\s*\[skipped-migration\]/u.test(line) || /^\s*\[hint\]/u.test(line)) + return { failed, lines } +} + function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { const t = labels(lang) const isExport = mode === 'export' @@ -1327,6 +1344,7 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { const [confirmingExport, setConfirmingExport] = useState(false) const [done, setDone] = useState(false) const [deleteReport, setDeleteReport] = useState(null) + const [importReport, setImportReport] = useState(null) const load = async (includeSubagents, includeCodex) => { setError(null) @@ -1461,6 +1479,7 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { throw new Error(data?.error || String(res.status)) } setBusy(false) + setImportReport(migrationFailureReport(data.text)) setDone(true) // Refresh the plugin's own catalog so the rows flip to "imported". The // sidebar list belongs to the Host, so it is not force-reloaded here — @@ -1474,6 +1493,7 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { setError(result.text || t.error) return } + setImportReport(migrationFailureReport(result?.text)) setDone(true) void load(!hideSub, showCodex) } else { @@ -1633,14 +1653,22 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { if (done) { const refusedOnly = isManage && deleteReport !== null && deleteReport.removed === 0 + // A batch that skipped sessions mid-migration is a partial success: a green + // check would hide that some chats never made it in. + const partial = !isExport && !isManage && importReport !== null + const reportText = partial + ? importReport.lines.join('\n') + : isManage && deleteReport !== null ? deleteReport.text : '' return h('div', { style: styles.overlay }, h('div', { style: Object.assign({}, styles.dialog, { maxHeight: 'none', width: 'min(480px, 92vw)', textAlign: 'center', padding: '20px' }) }, - h('div', { style: { display: 'flex', justifyContent: 'center', marginBottom: '10px' } }, refusedOnly ? Icons.info(18) : Icons.checkCircle()), + h('div', { style: { display: 'flex', justifyContent: 'center', marginBottom: '10px' } }, (refusedOnly || partial) ? Icons.info(18) : Icons.checkCircle()), h('div', { style: { fontSize: '15px', fontWeight: 600, color: 'var(--dsw-alias-label-primary)', marginBottom: '8px' } }, - isManage - ? (refusedOnly ? t.deleteNone : t.deletedOk) - : isExport ? t.exportedOk : t.importedOk), - isManage && deleteReport !== null && deleteReport.text.length > 0 + partial + ? t.importedPartial + : isManage + ? (refusedOnly ? t.deleteNone : t.deletedOk) + : isExport ? t.exportedOk : t.importedOk), + reportText.length > 0 ? h('pre', { style: { fontSize: '11px', @@ -1653,10 +1681,12 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { margin: '0 0 14px', padding: '8px 10px', borderRadius: '6px', - background: 'var(--dsw-alias-bg-l2, rgba(127,127,127,0.08))', color: 'var(--dsw-alias-label-secondary)', + background: partial + ? 'var(--dsw-alias-state-warning-bg, rgba(234,179,8,0.16))' + : 'var(--dsw-alias-bg-l2, rgba(127,127,127,0.08))', }, - }, deleteReport.text) + }, reportText) : h('div', { style: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)', lineHeight: '1.5', marginBottom: '18px' } }, isManage ? t.deleteHint : isExport ? t.exportHint : t.reloadHint), h('div', { style: { display: 'flex', justifyContent: 'center', gap: '10px' } }, isExport diff --git a/package.json b/package.json index 0da9fba..0249810 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.10.9", + "version": "1.10.10", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh", From 5b61e89b7984d33cc1e13e438e5c5f2199eea28f Mon Sep 17 00:00:00 2001 From: neo Date: Thu, 12 Nov 2026 16:46:42 +0800 Subject: [PATCH 18/18] =?UTF-8?q?feat:=201.10.11=20=E2=80=94=20busy?= =?UTF-8?q?=EF=BC=88=E5=AF=B9=E8=AF=9D=E6=89=93=E5=BC=80=E6=9C=AA=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=EF=BC=89=E4=B9=9F=E5=BD=92=E5=85=A5=E7=BB=93=E6=9E=9C?= =?UTF-8?q?=E9=A1=B5=E8=AD=A6=E7=A4=BA=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 12 ++++++++++++ lib/client.js | 35 +++++++++++++++++++++++------------ package.json | 2 +- 3 files changed, 36 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cff056c..5b1ebbd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 1.10.11 — 2026-11-12 + +- **A chat left untouched because it is open also counts as a partial outcome.** + `busy N` (the Host holds that Session's write handle) now triggers the warning + result page alongside `migration-failed N`, with its own title + 「部分会话未更新」 / “Some chats were not updated” (migration failures keep + 「部分会话未导入」). The panel lists every `[busy]` / `[skipped-migration]` line + plus the hints, so “close that chat and re-import” is visible instead of hiding + behind a green check. +- Deliberate filters (subagent / side chat / oversized) stay silent: they are not + failures. + ## 1.10.10 — 2026-11-12 - **A partial import now says so.** When the batch skipped sessions the diff --git a/lib/client.js b/lib/client.js index 4e697ef..54e8e83 100644 --- a/lib/client.js +++ b/lib/client.js @@ -1064,6 +1064,7 @@ function labels(lang) { error: '无法读取目录。请完全退出并重新启动 dsh web(只刷新页面不够,后台插件不会更新)。', importedOk: '导入完成', importedPartial: '部分会话未导入', + importedBusy: '部分会话未更新', reloadHint: '会话已写入。侧边栏列表由 dsh 自己维护,若没看到新对话,可点「刷新列表」(只重载页面,不重启 dsh)。', reloadNow: '刷新列表', reloadLater: '关闭', @@ -1158,6 +1159,7 @@ function labels(lang) { error: 'Could not load catalog. Fully quit and restart dsh web (a page refresh does not reload the host plugin).', importedOk: 'Import finished', importedPartial: 'Some chats were not imported', + importedBusy: 'Some chats were not updated', reloadHint: 'The sessions are written. The sidebar list is owned by dsh — if the new chats are missing, use Refresh list (a page reload, no dsh restart).', reloadNow: 'Refresh list', reloadLater: 'Close', @@ -1315,18 +1317,27 @@ function TriBox({ state, disabled }) { } /** - * Read the partial-failure part of an import report: how many sessions the - * migration chain refused, and the lines that explain why. + * Read the partial-outcome part of an import report. + * + * Two failures leave a chat untouched without failing the batch — the migration + * chain refused the session, or the chat is open in DSH so the Host holds its + * write handle — and both used to hide behind a green "导入完成". * @param {string|undefined} text - the host's newline-separated result text - * @returns {{failed: number, lines: string[]}|null} null when nothing failed + * @returns {{failed: number, busy: number, lines: string[]}|null} null when all good */ -function migrationFailureReport(text) { +function partialImportReport(text) { if (typeof text !== 'string') return null - const matched = /migration-failed (\d+)/u.exec(text) - const failed = matched === null ? 0 : Number(matched[1]) - if (!Number.isFinite(failed) || failed <= 0) return null - const lines = text.split('\n').filter((line) => /^\s*\[skipped-migration\]/u.test(line) || /^\s*\[hint\]/u.test(line)) - return { failed, lines } + const countOf = (label) => { + const matched = new RegExp(`${label} (\\d+)`, 'u').exec(text) + const value = matched === null ? 0 : Number(matched[1]) + return Number.isFinite(value) ? value : 0 + } + const failed = countOf('migration-failed') + const busy = countOf('busy') + if (failed <= 0 && busy <= 0) return null + const lines = text.split('\n') + .filter((line) => /^\s*\[(skipped-migration|busy|hint)\]/u.test(line)) + return { failed, busy, lines } } function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { @@ -1479,7 +1490,7 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { throw new Error(data?.error || String(res.status)) } setBusy(false) - setImportReport(migrationFailureReport(data.text)) + setImportReport(partialImportReport(data.text)) setDone(true) // Refresh the plugin's own catalog so the rows flip to "imported". The // sidebar list belongs to the Host, so it is not force-reloaded here — @@ -1493,7 +1504,7 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { setError(result.text || t.error) return } - setImportReport(migrationFailureReport(result?.text)) + setImportReport(partialImportReport(result?.text)) setDone(true) void load(!hideSub, showCodex) } else { @@ -1664,7 +1675,7 @@ function ImportPicker({ lang, runCommand, onClose, mode = 'import' }) { h('div', { style: { display: 'flex', justifyContent: 'center', marginBottom: '10px' } }, (refusedOnly || partial) ? Icons.info(18) : Icons.checkCircle()), h('div', { style: { fontSize: '15px', fontWeight: 600, color: 'var(--dsw-alias-label-primary)', marginBottom: '8px' } }, partial - ? t.importedPartial + ? (importReport.failed > 0 ? t.importedPartial : t.importedBusy) : isManage ? (refusedOnly ? t.deleteNone : t.deletedOk) : isExport ? t.exportedOk : t.importedOk), diff --git a/package.json b/package.json index 0249810..a65fb51 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-codex-sync", - "version": "1.10.10", + "version": "1.10.11", "description": "Two-way Codex↔DSH bridge: skills from ~/.codex/skills, session import with workspace attach, live MCP mirroring of mcp_servers, and a Codex-side reverse MCP installer.", "keywords": [ "dsh",