fix(storage): restore Codex import image attachments #6118
P2: local-persistence-dependencies.test rejects this import ("consume execution-stores, not @maka/storage/session-store"), and it is one of the two CI failures in the test job. Inline the options type, or take it from an allowed contract module.
P2: this value import pulls artifact-store.js, and with it node:sqlite, into the ./external-sessions entrypoint, so public-entrypoints.test ("only the declared entrypoints load node:sqlite") fails. ArtifactStore.create() already calls sanitizeArtifactName(input.name), so you can pass basename(path) and drop this import.
P3: if decode or projection throws here, after prepareMessages has created Artifacts, nothing purges them. The same applies if importSession throws before writing a row. Consider purging on any failure before commit.
Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.
Reviewed range: full first review of 1751c399..d2a7ac1c (merge-base with main through head d2a7ac1cf05c5a789c5b535c29af3259b57fc4ee, one author commit, 12 files). No prior findings.
The overall design looks right. The adapter records only explicit local_image parts, and their descriptors count toward the converted-bytes budget. Ordinary paths in text are never turned into attachments. Bytes are copied into Session-owned user_upload Artifacts before the transcript is published, and the source path never appears in stored messages. Missing, invalid or oversized originals keep the message and add a visible fallback note. Discarded staged imports now purge their Artifacts. The read path is careful:
O_NONBLOCK combined with isFile() rejects FIFOs and devices without hanging.Symlinks are followed and there is no directory containment. I think that is acceptable: Codex local images can legitimately be anywhere, and the magic-byte check means a non-image file such as a key file can never become an attachment. This PR does not decode data URLs or inline images; it handles only path references, so there is no inline-decoding surface to bound. The new tests would fail without the fix (the sourceImages field, the importer's Artifact argument and the attachment assertions are all new), and they passed in CI.
Findings
1. P2: CI failure caused by this PR (two storage guard tests). The test job fails in @maka/storage:
- local-persistence-dependencies.test: "production Runtime and Host use persistence contracts…". external-session-coordinator.ts:35 adds import type { SessionAuthorityStore } from '@maka/storage/session-store', which that guard forbids ("consume execution-stores, not @maka/storage/session-store"). Inline the options type, or take it from an allowed contract module.
- public-entrypoints.test: "only the declared entrypoints load node:sqlite". ./external-sessions now loads node:sqlite because external-session-images.ts:33 imports the value sanitizeArtifactName from ./artifact-store.js. ArtifactStore.create() already calls sanitizeArtifactName(input.name), so this import can be dropped: pass basename(path) and keep only the import type.
The third failure, Desktop workhub-remote-bridge "a target clearing receipt cannot erase the current remote heading", is unrelated. It also failed in about ten other recent runs, including main run 38556979642, and this PR does not touch Desktop.
2. P3: Artifacts can be orphaned when a failure happens after preparation but before commit. prepareExternalSessionImages purges only when its own loop throws. In SqliteSessionStore.createImportedSession (session-store.ts:222-229), a throw from decodeCanonicalMessage/projectSessionCatalogMessages after prepareMessages resolves leaves the copied Artifacts under a Session id that is never committed. The coordinator then reports source_unreadable. The same happens if metadata.importSession throws before writing any row (commit attempted, but drain finds no staged Session), or if the process crashes in that window. There is no orphan sweep for Artifacts whose Session does not exist. A purge in createImportedSession/the importer on any failure before commit would close the first two cases. Severity is low because the decode inputs are adapter-validated.
3. P3: The legacy user_message event is not covered. Only item_completed/UserMessage parts are recovered. The older event_msg user_message payload still keeps local_images (paths) and images as a bare [Image] placeholder (mediaOnlyUserText). That matches the scope of #6110 (Codex Desktop UserMessage), but older CLI rollouts still lose their images. Worth a follow-up or a note in the PR.
4. P3: Missing paths have no I/O count bound. The cap of 8 attachments per message only counts successful images, so missing or invalid paths do not count toward it. A rollout full of local_image parts with missing paths triggers one open() per descriptor, limited only by the converted-bytes budget. A small cap on attempts per message or per import would make this predictable.
Interaction with #6117. A test merge (git merge-tree of both heads) is textually clean. The adapter hunks are adjacent and combine into id plus ...codexUserContent(text). Semantically they are compatible: #6117 keeps the # Files mentioned by the user: block visible in displayText on purpose ("Images are not migrated here"), and this PR appends its fallback note to displayText when one exists. Once both land, an imported message will show the image thumbnails and also the raw file-path metadata block. Whichever PR lands second should consider hiding that block when every listed image was recovered (P3, follow-up).
Re-import: each import gets a fresh Session id and its own Artifact copies. A failed or discarded import purges by that id, so retries do not duplicate or collide. In-flight dedupe is unchanged.
Status. No protocol or epoch files are touched. GitHub reports the PR as MERGEABLE (state BLOCKED pending a passing CI run and review). CI test is failing because of finding 1.
Automated update from OpenAI Codex addressing the review:
storage/session-store and the image helper's value import of artifact-store. The two failing storage boundary checks now pass locally.event_msg.user_message image recovery remains outside this Codex Desktop UserMessage fix. The metadata-envelope display interaction with #6117 also remains separate.Validation: root build/lint/format/ASF headers passed; Codex adapter 41/41, Host external-session/protocol 44/44, WorkHub bridge 23/23, and the two updated regressions 2/2 passed. Storage boundary/Session/importer checks passed 45/46; the remaining durable-image test still cannot acquire the local OS control-cache directory (EPERM), as already disclosed in the PR.
For the old CI's WorkHub failure, I verified the actual target-base full CI: main run 38689914863, job 116273194703 passed that exact test. The review's cited main run 38556979642 instead failed a Side Chat E2E test. I have not established a matching baseline WorkHub failure; the new head needs CI confirmation.
P3 (nit): if discardPreparedMessages throws here, its error replaces the original prepare/decode/commit error. Consider catching (and logging) the discard failure and rethrowing the original error.
Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.
Incremental review of d2a7ac1c..09dcdb07 (head 09dcdb07692e95ea3ae5c3858957ca4a760425ec). The PR is still based on merge-base 1751c399, which is current main, so there was no rebase. The delta is one author commit, "preserve import boundaries and clean failed preparation", touching 7 files (+85/-21).
Prior findings
1. P2, CI failure from the storage guard tests: fixed. external-session-coordinator.ts no longer imports @maka/storage/session-store and declares the options shape inline. external-session-images.ts drops the value import of sanitizeArtifactName and passes basename(path). ArtifactStore.create() still sanitizes the name, so behaviour is unchanged. I built the head locally and ran the tests: local-persistence-dependencies, public-entrypoints, external-session-importer and session-store in @maka/storage, plus external-session-coordinator and external-session-protocol in @maka/runtime-host. All of them pass.
2. P3, orphaned Artifacts after preparation: mostly fixed. createImportedSession now wraps prepare, decode, projection and commit in one try/catch. If the error happens before onCommitStarted, it calls the new discardPreparedMessages hook, which the importer wires to purgeSessionArtifacts(sessionId). If the error happens after commit started, it re-reads the header. It discards only when that read fails with SessionNotFoundError. An existing result or any other read error keeps the bytes. This is the right rule:
- importSession runs as one SQLite transaction, so a not-found read means nothing was committed.
- The id comes from a freshly generated header, so the purge can only reach Artifacts this call created.
- In the theoretical id-collision case (existing), the read succeeds, so the other Session's Artifacts are not touched.
- When prepareExternalSessionImages fails, it purges by itself and then the hook purges again. purgeSessionArtifacts is a queued filter-and-delete, so the second purge is a harmless no-op.
- No other party knows the generated id before commit, so I see no race.
- The new session-store test checks that the prepared id and the discarded id match on a decode failure.
Still open: a process crash between copying and committing leaves orphans, because there is no sweep for Artifacts whose Session does not exist. That is acceptable as a follow-up.
3. P3, legacy event_msg user_message images: still open. The adapter is unchanged in this delta. A follow-up or a note in the PR is still recommended.
4. P3, no cap on read attempts: fixed. The loop now stops opening files once index >= MAX_ATTACHMENT_COUNT, so there are at most 8 open() attempts per message whether or not the paths exist. Every descriptor beyond that is counted in the "unavailable" note. The updated importer test covers this: 9 descriptors, the ninth valid, and the result is "9 … unavailable" with no attachments.
5. Interaction with #6117: unchanged. #6117 is still open (head fbef7460). My earlier note about the duplicated # Files mentioned by the user: block still applies to whichever PR lands second.
New findings
session-store.ts:254, if discardPreparedMessages throws, its error replaces the original prepare/decode/commit error. The coordinator's classification depends only on commitAttempted, so callers see no difference, but logs lose the root cause. Wrapping the discard in try/catch, or logging and rethrowing the original error, would keep it.commit_outcome_unknown and requests a drain. That is conservative and harmless.Status. No protocol or epoch files are touched. GitHub reports the PR as MERGEABLE, with state BLOCKED pending CI and review. The CI test job for this head (run 38754258326) is still queued, so there is no CI result yet. My local runs of the previously failing guard tests pass. If the Desktop workhub-remote-bridge test ("a target clearing receipt cannot erase the current remote heading") fails again, it is the known flaky test that also fails on main, and this PR does not touch Desktop.
All P0–P2 findings are resolved. The remaining items are P3 follow-ups.
Automated update from OpenAI Codex: fixed in 260a35a6910b741ed6d25c9b9a118ff392c81a8d. Prepared-message discard is now best effort, so a cleanup failure cannot replace the original import error.
The regression covers preparation, canonical decoding, and the precommit callback; it fails against the previous behavior and passes with the fix. SessionStore passed 29/29; importer passed 10/11, with the same previously disclosed OS control-cache EPERM on the durable-image test. Root build, lint, format and ASF header checks passed.
Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.
Incremental review: 09dcdb07..260a35a6910b741ed6d25c9b9a118ff392c81a8d, one commit wrapping the best-effort discardPreparedMessages cleanup in try/catch so a cleanup failure no longer replaces the original import error (packages/storage/src/session-store.ts:254), plus a test covering preparation, schema-decode and commit-callback failures with a throwing cleanup.
The previous P3 nit is fixed; the test asserts the original error is rethrown in all three stages, cleanup is attempted each time, and no session is left behind. The remaining P3 about the older user_message image format is unchanged and non-blocking. No new findings.
No protocol files touched (epoch unaffected). The PR is MERGEABLE; the required test job (CI) is still queued, so this is not a claim of green CI or an approval.
Automated CI follow-up from OpenAI Codex: I changed only the paging regression's shared harness budget from 30 to 60 seconds, with a 90-second enclosing test deadline. The 17 real Host/model submissions and all pagination/external-write assertions remain intact; product timeouts are unchanged.
The failed job captured successful responses 0–50, including 16 completed proposals and revision requests. Those proposal submissions continued at 1.27–2.10 second intervals over 24.94 seconds before the whole-operation deadline expired. This supports allowing more time for the complete test journey; it does not establish a product hang or a matching baseline failure. The target-base job passed this test in 17.8 seconds.
Root lint, formatting, build, Desktop/UI Knip, and workspace typecheck passed. The first workspace typecheck encountered stale Desktop protocol declarations; all four Desktop configurations passed with fresh caches, and the official workspace command then passed after removing only those incremental caches. Fresh focused runs before and after the change could not start the Host because the sandbox denies its OS-account storage owner-lock namespace, so the paging assertions were not exercised locally. The new CI run still needs to validate the adjusted budget.
Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.Incremental review:260a35a6..2039080c, one test-only commit. It doubles the timeouts of the ACPPlan paging preserves storeVersion…test (45s to 90s for the test, 30s to 60s for the operation). I found no P0–P2 issue, and the import fix itself is unchanged.
P3: this commit is no longer needed and leaves a stale comment after merging with main. #6129 (now on main) already fixed that flaky test by replacing the 17 full model turns with two byte-limited proposals. The commit still merges cleanly (git merge-tree against main 2c429077). However, the merged file would double main's budgets and add the comment "Seventeen real Host/model round trips share this operation budget", which no longer describes the test. It is also unrelated to the Codex image-import change. I suggest dropping this commit and rebasing onto main.
CI: the test failure on this head is runtime: bounded (stop already requested: false): owner SIGKILL terminates an admitted command before its delayed write. That is a process-timing test this PR does not touch, and the other workspaces passed. It looks like a flake, and I have re-run the failed job. The run also predates the branch's inclusion of #6129. Rebasing onto main would pick up the other CI repairs.
Automated follow-up (OpenAI Codex).
Dropped the test-only timeout commit and rebased the three image-import commits onto main 2c429077 in 7843e73fe. The Plan paging test is now identical to main, including #6129’s two byte-limited proposals and its existing timeouts; the stale seventeen-round-trip comment is gone. The Codex image-import fix and the display-envelope handling from #6117 are retained.
Root build, workspace typecheck, lint, format and Desktop/UI Knip passed. The external-session Host suite passed 33/33; affected storage suites passed 82/83. The durable-image regression remains blocked locally before its assertions by the OS-account Artifact control-cache EPERM, as previously reported. New-head CI still needs to run.
Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.Incremental review:2039080c..7843e73f, a rebase onto main2c429077. Our P3 is resolved: the ACP timeout commit is dropped, so the branch no longer touches that test. I found no P0–P2 issue, and CItestpasses on this head.
git range-diff shows the second and third commits as patch-identical. The first commit changed only in one place, its conflict with #6117. The user-message append in CodexRolloutConverter now keeps this PR's stable id, which the imported image attachments are keyed by, and uses main's ...codexUserContent(text), which keeps the raw text and adds displayText for the context envelopes. Both behaviors are preserved: images still attach to the message ID, and envelope rendering from #6117 still applies to messages that carry images.
Thanks for the contribution and for addressing the review feedback. Merging now.
Approved at @Astro-Han's explicit request: no blocking findings in the automated review of this head, and CI is green.
Astro-Han
Dante-dan
Summary
Fixes #6110.
Codex Desktop
UserMessageimports now recover explicitlocal_imageparts into durable, destination-Session-owned image Artifacts and native attachments. Source paths are read under byte and count limits; ordinary text paths are never treated as attachments. Missing, unreadable, invalid or oversized originals retain the conversation and an explicit fallback with their original image positions. Failed preparation and discarded staged imports clean up their Artifacts.Original message text is retained. The display-envelope changes from #6117 are retained from main.
Verification
2c429077after #6129 rewrote that fixture. The CLI paging test is identical to main; the three image-import commits remain.EPERM); its durable-image assertions were not reached.AI use
Select exactly one:
Tool(s) and scope: OpenAI Codex assisted with investigation, implementation, tests, and this description. The material contribution commit includes
Generated-by: OpenAI Codex.Checklist
Does this PR entail a change in behavior?