From 71a806749dfae88f6ca5cbc3cb1bc19329d01f06 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 14 Nov 2026 11:41:28 +0800 Subject: [PATCH] sessions: a paginated Codex rollout moves to a longer provider id by its row (@xMopf7RF on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @xMopf7RF on X (tweet 2121441393424113800): the Sessions page's Move refused an old Codex session with "rollout-2026-03-09T09-25-….jsonl.zst keeps its history by byte, and "magpie" is longer than the provider it names: Codex couldn't open it moved", and offered nothing else. Since 67b12956a a paginated rollout's session_meta is only rewritten at its own length (Codex keeps places in it by byte), and MoveCodexProvider refused a longer id outright. But Codex reads a paginated thread's provider from its row in the state database, never from its file (codex-rs read_thread; RetagPagedCodexThreads already moves such threads by the row alone, tried with the real codex 0.166). So now rewriteCodexProvider leaves such a line as it was and says so (kept), and moveCodexPaths moves the thread by its row. Every caller gets it: the Sessions page's Move, Resume's move first, and the sync's MoveCodexThreads/MoveRecentCodexThreads, which met the same refusal for a provider shorter than magpie. With no row to move it by, it can't move at all: it is refused as sessions.StuckError, every file put back and no trash copy left, and the API says stuck with the provider it stays on. The page then says why, that the session stays on that provider unchanged and shows in Codex when Codex uses it again, and that Delete clears it into magpie's trash, where it can be restored. New string in zh, zh-TW, ja and de. Run, at 7951989c6 (on origin/main e0889719c): - go test -count=1 -run 'TestMoveCodexProvider|TestRetagPaged|TestPortCodex' ./internal/sessions/ on mote: ok. - Old code back (codex_provider.go from e0889719c, StuckError stubbed): TestMoveCodexProviderPagedByRow and TestMoveCodexProviderPagedNoRow FAIL with the reporter's exact error text; green with the change. - node --test sessions-codex-provider-stuck, sessions-codex-provider, sessions-codex-provider-pick, i18n-keys, i18n-en-no-cjk on mote, Chromium and WebKit, five languages, 900px and 420px: 42 of 42 pass. The new GUI file with the old client.js: 0 of 20 pass. - gofmt -l on the changed packages: nothing. - Full suite (vet x3, builds x3, go test -tags nogui ./... -timeout 45m) queued on mote's suite lock; pushed before it ran, per the owner's ship-at-once rule. Its result goes in a follow-up. Not tried: a real Codex resuming a thread moved this way. The row-only move is the one RetagPagedCodexThreads makes, which was tried with codex 0.166.0 exec resume (docs/subsystems/agent-wiring.md). Not reproduced: the no-row case with real Codex, where Codex 0.166 keeps a row for every paginated thread; it is covered by a fixture only. --- docs/subsystems/gateway-routing.md | 2 +- .../gui/assets/plugins/sessions/client.js | 3 + internal/gui/assets/plugins/sessions/i18n.js | 4 + internal/gui/sessions_manage.go | 11 +- internal/gui/tests/README.md | 6 + .../sessions-codex-provider-stuck.test.cjs | 92 ++++++++++++++ internal/sessions/codex_provider.go | 87 +++++++++---- .../sessions/codex_provider_stuck_test.go | 115 ++++++++++++++++++ 8 files changed, 292 insertions(+), 28 deletions(-) create mode 100644 internal/gui/tests/sessions-codex-provider-stuck.test.cjs create mode 100644 internal/sessions/codex_provider_stuck_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 17f707b09..5d8c1c425 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -349,7 +349,7 @@ recorded as a prediction failure (`noPrediction`). - A reasoning item with its text in it (`content` parts: DeepSeek's Responses API writes `reasoning_text`, relayed to Codex as it came) is another vendor's. OpenAI's API and the ChatGPT backend take a reasoning item's `content` only empty, and refuse the whole request over one with 400 "Invalid 'input[n].content': array too long. Expected an array with maximum length 0" (`array_above_max_length`). Codex hands the item back on every later turn, so it never goes to them: for one of Codex's own models, `codexInput(body, false)` leaves it out (and a reasoning item with nothing sealed in it) on `/backend-api/codex`'s `/responses` and on `/responses/compact`, before Codex's own sign-in, its API key or a magpie Codex account (`compactOn`) is asked. Codex compacts a thread before its first turn back on its own model, and a refused compaction shows as that turn's error (jue on Discord). `passthrough` leaves it out for OpenAI, Azure OpenAI and a Codex account (`withoutReasoningText`), and for any other upstream once it has refused one (`refusesReasoningText`, `reasoningTextRefused`, #1411). OpenAI's own sealed reasoning (`encrypted_content`, no text) stays, and a DeepSeek model (`replaysReasoning`) still gets the text. `TestForeignReasoningNeverReachesOpenAI`, `TestReasoningTextLeftOutWhereRefused`, `TestReasoningTextNotSentToCodexAccount`. - A conversation that moves to another key, account or vendor carries what the one before sealed (`encrypted_content`): its reasoning, and the sealed copy an answer's other items may carry: a web search's (`web_search_call`), and with Codex's output token replay on, each message's and call's (Codex keeps those for a provider named "OpenAI" only, and signed in it reaches magpie as that provider). `forVendor` takes the copies out for a vendor not OpenAI's, reasoning and compactions aside; between ChatGPT accounts, or a ChatGPT account and an OpenAI API key, all of it goes as it came. One that can't read it says so (`foreignReasoning`: OpenAI's `invalid_encrypted_content`, "could not be verified" of reasoning and "Encrypted content could not be decrypted or parsed." of a web search; xAI's "Could not decrypt"), as a 400 or as the stream's error, and `serve` asks it again without them (`withoutSeals`): a reasoning item goes whole, any other item keeps all but its `encrypted_content` (`withoutItemSeal`), and a compaction keeps its seal. Refused again, or with nothing else sealed, the compaction OpenAI sealed goes (`withoutCompaction`), unless native compaction is on (below). What was taken out is remembered by its hash for the conversation and the key or account that refused it, for `stickKeep` (`refused`, `refusedSeals`), and its later requests there leave it out up front (`withoutRefused`); what that one sealed itself still goes along, and a request that stays where its seals were made goes as it came. A refusal doesn't say whose seal it couldn't read, so every one goes, the asked one's own from an earlier stay in the conversation too, and all are remembered. It is the same whatever moved the conversation: a key or account resting, used up or rate limited, the next member of a group, or routing's own pick once its affinity went cold, on the backend path and on `/v1/responses` alike (#3887, hheei: after such a move a `web_search_call` another ChatGPT account of the group had sealed was refused, only the reasoning was left out, and every turn failed). Codex's own sign-in, relayed as it came (`codexUpstreamOn`), is asked again the same way when the backend answers its `/responses` with a 400 (`withoutUnreadable`, after the item the refusal names, if any); it keeps no record of what was refused, and a refusal in the stream reaches Codex as it came. `TestForeignSealAcrossGroupMembers`, `TestForeignSealGrokToCodexAccount`, `TestForeignSealedItemsMoveToAnotherAccount`, `TestForeignSealedItemsAfterAColdSwitch`, `TestForeignSealedItemsRelayedToAnotherSignIn`, `TestSealsTakenOutLeaveTheRest`. - Native compaction (#1099, off by default): a provider with `nativeCompaction` on (`provider.Provider.CompactsOn`; the editor's Compaction row, `magpie provider set compaction=native`) is asked Codex's `compaction_trigger` as Codex sent it, and the compaction item it seals goes back to Codex unchanged, not as a `magpie1:` summary. Only a wire that carries it can be set so (`CarriesCompaction`): a Responses API, a ChatGPT account, GitHub Copilot (its models asked on Responses; its Claude models keep magpie's summary). The decision is made where `handle` and `codexBackend` read the input (`nativeCompactionFor`, `codexInputAs`): a group compacts natively only when every member does. Such a request, and a later one carrying a sealed compaction to a provider set so or to the provider recorded as its writer, is relayed, never translated, which would drop the item (`keepsCompaction` in `attempt`); a provider that can't be asked it on Responses answers a 400 saying so. The trigger is kept only when a key or account the request would go over (the provider's and its fallbacks', or a group's members', held and capped ones too, not one whose own list lacks the model) can be asked it on Responses (`plannedCarrier`, read from `perKeyBarred` without weighing, so a provider routed in turn isn't moved along by the decision). When the vendor lists the model only to keys that speak no Responses there, a key set to Chat say, `codexCompact` gives magpie's summary through the listed key, as with native compaction off; before, the trigger was kept and refused 400 `carrierError` with no upstream asked (#2725, ggbdpq; `TestNativeCompactionTriggerSummarisedWhenNoListedKeyCarriesIt`, `TestNativeCompactionTriggerThroughTheListedKeyThatCarriesIt`, `TestNativeCompactionDecisionLeavesTheTurnsAlone`). The key or account that answered is recorded, whoever it is: a fallback or another member that answered the trigger sealed it whatever its own setting, and only it can read the seal (#2271, JasonBuildAI: a fallback's seal went unrecorded, and the next turn was answered 200 without the compacted history; `TestNativeCompactionFallbackSealStaysWithItsWriter`). It is recorded by the hash of what it sealed (`wroteCheckpoint`, `compactions.json` beside `affinity.json`, 0600, at most 1024 for 30 days). A later request carrying it goes only to that writer (`checkpointReaders`); a writer whose own list has since dropped the model is tried still, as the last resort an account whose list lacks the model is — it sealed the model's compaction, and no other can read it (`planned.unlisted`, `TestNativeCompactionWriterWhoseListLacksTheModel`, #2642: it was refused as "switched off, removed, or no longer serves" though it was on, and switching it on changed nothing). With the writer gone from the candidates, magpie answers 400 `checkpointError` with the reason its settings give (`checkpointGone`: the provider removed, the account signed out, its sign-in lapsed, paused while others are on, switched off, kept from the model in Model settings, the key off or gone, the model disabled, or the model or group asked for not going to it), what lets the conversation go on, and whether native compaction is on for the writer's provider now, and never sends it to another key, drops it, or summarises it in its place (`TestNativeCompactionWriterGoneSaysWhy`). A call Codex makes beside the conversation, on a model of its own choosing with the conversation's history in it (`compactionAside`: the guardian's auto-review, on `codex-auto-review` or the model set for it, a memory, a subagent, a title, description, summary, prediction or suggestion), goes on without the seal when the writer isn't among its candidates (`withoutCompaction`), its instructions, turns since and tool calls kept: it isn't refused, and the conversation's own turns are still held to the writer. Relayed to Codex's own sign-in, a compaction recorded as sealed by a provider other than the Codex subscription (Copilot, an API key's) never goes as it came (`foreignToSignin`): such a side call goes without it, a turn or a `/responses/compact` is refused with `checkpointError` (echo_ts: every auto-review after a Copilot compaction was answered 400 `invalid_encrypted_content` by OpenAI; `TestForeignCompactionLeftOutOfAutoReview`). A seal with no record, or one whose provider can't be read, is the sign-in's to judge, as before. One of Codex's own models asked on the backend path is decided as a magpie model is when magpie's Codex accounts serve it (`codexAccounts`): the trigger is kept only with the codex provider's native compaction on, else `codexCompact` gives magpie's summary, which any account reads, and no writer is recorded (#2582, ump45nose; before, every such compaction was sealed natively whatever the setting, and the conversation was held to its account; `TestCodexOwnModelCompactionHonoursTheToggle`). Codex's own sign-in alone, relayed as it came, still compacts natively, unrecorded, as does `/responses/compact`; but a request carrying a compaction magpie recorded the writer of goes through routing even then (`codexSealedFor`), so with the writer switched off the one account left isn't sent it. A legacy `/responses/compact` carrying one is judged at its passthrough (`sealedCompact`): the writer on in magpie answers it signed as the writer — its own seal while the sign-in can be asked, a key's seal, a request signing with its own `chatgpt-account-id`, or an unreadable sign-in state relays as it came — and a writer gone is refused with `checkpointError`'s reason, the same words as on `/responses` (`TestNativeCompactionCompactJudgesItsWriter`, #2727). The writer matched is the account user the record holds, so two Team seats of one email read as one and such a compact relays as it came. A gateway key held to some accounts (#905) is asked of the account the compact goes to (`compactSigninHeld`): the writer when it answers it, so a writer the key may not use is refused 403 (`sealedCompactHeldError`) with nothing asked, and one it may use answers though the sign-in isn't the key's (`TestNativeCompactionCompactKeepsTheKeysAccounts`). With the writer held at its usage cap or for credits it may not spend, the answer is 429 `checkpointCappedError` (record `checkpointCappedRecord`, "native compaction's account at its usage cap"), naming that account, that the others serving the model weren't tried for the compaction, and that neither the routing mode nor how conversations stay changes that: wait for the window, raise or lift its cap, or start a new conversation (#2517, lm0711; before, it read "every account at its usage cap" though another had room; `TestNativeCompactionWriterAtItsCap`). `withoutCompaction` (the drop after a refused reasoning item) isn't used for such a request. A route carrying a compaction names its sealer (`Route.Compaction`), and Routing says that is why no other account was asked, not that it is "the only account on" for the model (#2639; `TestNativeCompactionRouteNamesItsWriter`, `routing-compaction.test.cjs`). A refusal of the trigger reaches Codex as the upstream sent it. Not tried against a real upstream; Copilot may refuse a history that holds Codex's `web_search` items. [`native_compaction.go`](../../internal/gateway/native_compaction.go), `TestNativeCompaction*`. -- A compaction magpie answers itself (`codexCompact`: a magpie model, Codex's own models through magpie's Codex accounts, a CC Switch table) goes to Codex as a `compaction` item whose `encrypted_content` is `magpie1:` and the summary in base64 (`codexsummary.Encrypted`), and `codexInputAs` sends Codex's own summary message in its place (`codexsummary.Message`: Codex's summary prefix, a newline and the summary, as a user message). Codex keeps the item in its rollout and replays it, and OpenAI refuses it once Codex talks to OpenAI itself (`invalid_encrypted_content`, LukeMa on X). So `sessions.PortCodexRollouts` writes that same message into the rollouts in its place ([`codex_portable.go`](../../internal/sessions/codex_portable.go)). A reasoning item carrying Claude's block (`magpie-claude1:`, above) is written as its summary, as the gateway sends it to OpenAI (`TestPortLineDropsClaudeBlocks`). It changes only magpie's items, keeps every other line's bytes and the file's line count, mode and time, and drops an unreadable item together with its `replacement_history_metadata` entry. Every rewritten line keeps its length (`fitLine`: a shorter one padded with spaces after its JSON, a longer one in a paginated rollout not written), as Codex keeps places in a rollout by byte: a fork's `history_base.end_byte_offset` and the state database's turn and projection offsets. A shorter parent left a fork's place past its end, and Codex refused to open the fork ("cutoff byte offset is past the source rollout", xybio on Discord); once per Codex home a pass sets each such fork's place again from the ordinal it names (`repairLineages`). `MoveCodexProvider` keeps the session_meta line's length the same way and refuses a longer provider id for a paginated rollout. It and `MoveCodexThreads` (Codex stepping off magpie) hold the thread's writer lock as Codex's own archive does, from before a file is copied until the thread's row has moved: a Codex that has the thread open writes on to the file it opened, and what it wrote after a move was lost (#3751). Such a thread is refused as one written to in the last minute is (`ErrActive`), and a Codex home without writer locks moves as before. A pass publishes as Codex publishes a compressed rollout: under `thread-writer-locks/.coordination.lock`, only with the thread's lock free, through a temp file and a rename. A thread a Codex has open is left for a later pass, and a Codex home without writer locks is left alone. It runs 2 minutes after the GUI or `magpie serve` starts and every 10 minutes after, on Codex Disconnect (3s), and as the GUI quits (3s). Each pass reads what changed since the last whole pass, plus what was held (`codex-portable.json`). A ported thread was resumed by Codex 0.162.1 against an upstream that refuses `magpie1:` as OpenAI does. Not tried: a Codex in a WSL distro, whose locks this machine can't take, so it is skipped. `TestPortCodexRollouts*`, `TestPortedCompactionReadsTheSame`. +- A compaction magpie answers itself (`codexCompact`: a magpie model, Codex's own models through magpie's Codex accounts, a CC Switch table) goes to Codex as a `compaction` item whose `encrypted_content` is `magpie1:` and the summary in base64 (`codexsummary.Encrypted`), and `codexInputAs` sends Codex's own summary message in its place (`codexsummary.Message`: Codex's summary prefix, a newline and the summary, as a user message). Codex keeps the item in its rollout and replays it, and OpenAI refuses it once Codex talks to OpenAI itself (`invalid_encrypted_content`, LukeMa on X). So `sessions.PortCodexRollouts` writes that same message into the rollouts in its place ([`codex_portable.go`](../../internal/sessions/codex_portable.go)). A reasoning item carrying Claude's block (`magpie-claude1:`, above) is written as its summary, as the gateway sends it to OpenAI (`TestPortLineDropsClaudeBlocks`). It changes only magpie's items, keeps every other line's bytes and the file's line count, mode and time, and drops an unreadable item together with its `replacement_history_metadata` entry. Every rewritten line keeps its length (`fitLine`: a shorter one padded with spaces after its JSON, a longer one in a paginated rollout not written), as Codex keeps places in a rollout by byte: a fork's `history_base.end_byte_offset` and the state database's turn and projection offsets. A shorter parent left a fork's place past its end, and Codex refused to open the fork ("cutoff byte offset is past the source rollout", xybio on Discord); once per Codex home a pass sets each such fork's place again from the ordinal it names (`repairLineages`). `MoveCodexProvider` keeps the session_meta line's length the same way. A longer provider id for a paginated rollout leaves that line as it was and moves the thread by its row in Codex's state database alone, where Codex reads a paginated thread's provider from; before, it was refused ("keeps its history by byte, and \"magpie\" is longer than the provider it names", @xMopf7RF on X). With no row to move, it is refused with nothing changed (`sessions.StuckError`), and the Sessions page says why, that the session stays on its provider, and that Delete clears it into magpie's trash (`TestMoveCodexProviderPagedByRow`, `TestMoveCodexProviderPagedNoRow`, `sessions-codex-provider-stuck.test.cjs`). It and `MoveCodexThreads` (Codex stepping off magpie) hold the thread's writer lock as Codex's own archive does, from before a file is copied until the thread's row has moved: a Codex that has the thread open writes on to the file it opened, and what it wrote after a move was lost (#3751). Such a thread is refused as one written to in the last minute is (`ErrActive`), and a Codex home without writer locks moves as before. A pass publishes as Codex publishes a compressed rollout: under `thread-writer-locks/.coordination.lock`, only with the thread's lock free, through a temp file and a rename. A thread a Codex has open is left for a later pass, and a Codex home without writer locks is left alone. It runs 2 minutes after the GUI or `magpie serve` starts and every 10 minutes after, on Codex Disconnect (3s), and as the GUI quits (3s). Each pass reads what changed since the last whole pass, plus what was held (`codex-portable.json`). A ported thread was resumed by Codex 0.162.1 against an upstream that refuses `magpie1:` as OpenAI does. Not tried: a Codex in a WSL distro, whose locks this machine can't take, so it is skipped. `TestPortCodexRollouts*`, `TestPortedCompactionReadsTheSame`. - The summary ask `codexCompact` sends a provider that isn't OpenAI's or a Codex account carries Codex's developer messages as system ones (`forVendor`, `developerItemsAsSystem`, #2955: a chat-only vendor refuses developer). A relay of a ChatGPT account takes developer alone and refuses system (sub2api, #5067), so a summary refused "System messages are not allowed", or with a relay's bare "Upstream request failed", as a 4xx or as an error event in a 200 stream (`roleRefused`), is asked once more with the roles as Codex sent them (`askAsSent`), then as text, then made by magpie, so such a refusal no longer counts toward the hold (`compactFails`). A summary with no developer message isn't asked the same twice. `TestCodexCompactSystemRefusedAsksAgainDeveloper`, `TestCodexCompactSystemRefusedEverywhereNeverHolds`. - A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (`passthrough`): Responses Lite's shape taken off (`fromLite`): its `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), its `reasoning.context` left out, its Lite marker removed from `client_metadata` (`withoutLiteMetadata`), and its `X-OpenAI-Internal-Codex-Responses-Lite` header not sent on (`liteKept`). A Codex websocket turn repeats the marker in `client_metadata`; leaving it beside a removed `reasoning.context` made a downstream Responses relay forward an inconsistent Lite request, which its ChatGPT backend refused with "requires `reasoning.context` to be `all_turns`". A subagent a Lite lead (gpt-6.1-sol) spawns on another model comes in that shape, its model name alone changed, and OpenCode Go's DeepSeek answered it 503 "Endpoint is unavailable" (TangForX on X, `TestLiteSubagentLeavesLite`). Also the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set `codexAsSent` (`magpie provider set codex=as-sent`) gets a request from Codex (`fromCodex`) as Codex sent it, its model name alone swapped, with Codex's own headers (`codexClientHeader`). That holds when Codex offers `web_search` too: the request is relayed with it, not translated for magpie's search (`searchedForIt`), which merged the developer messages into `instructions`, sent `apply_patch` as a function, left `web_search` out and added `max_output_tokens` (`codexAsSent` in `route`; maralica on Discord). `spawn_agent`'s description is still widened with the catalog's models (`spawnAgentModels`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`, `TestCodexAsSentWebSearch`, `TestFromLiteRemovesOnlyTheWebsocketLiteMarker`, `TestCodexTitleRelayKeepsLiteShapeConsistent`. - A tool a Chat request's message carries joins the request's `tools` (`liftMessageTools` in [`message_tools.go`](../../internal/gateway/message_tools.go), #2322). Pi with `supportsMidConvoToolAdditions` gives a tool it adds mid-conversation as `{"role":"system","tools":[…]}` with no content, and keeps top-level `tools` as they were at the start; no Chat API reads tools there, and `parseChat` read only the top-level ones, so the tool could be called on no route. `handle` lifts them for every Chat body before `serveAgent`, so the Chat relay, the schema fixers, redaction (the tool is a tool definition, not message text), the prompt shown and routing all see them; `parseChat` lifts too, for a body that never came through `handle` (the Claude subscription bridge's direct callers). Each tool joins once by name and the first definition wins: a top-level tool keeps its own, then the earliest message's, as `liftAdditionalTools` and a `tool_addition` (`withoutDeferredTools`) do. A system or developer message that carried only tools is left out, so it is neither relayed as an empty system message nor joined into the system text as an empty part; one with content keeps its place without `tools`. Messages stay where they are: the in-place system message the issue also asks for is not this change. `TestPiAddedToolReachesEveryRoute` sends deephbz's Pi 1.2.0 bytes through the Chat relay, Messages, Responses, Gemini and Codex, and `TestPiAddedToolOfferedToClaudeCode` through the Claude subscription bridge. diff --git a/internal/gui/assets/plugins/sessions/client.js b/internal/gui/assets/plugins/sessions/client.js index 97ddf012d..069f53822 100644 --- a/internal/gui/assets/plugins/sessions/client.js +++ b/internal/gui/assets/plugins/sessions/client.js @@ -669,7 +669,10 @@ magpie.plugin("sessions", (ctx) => { if (out.refused.length) { const first = out.refused[0], s = data.sessions.find((x) => x.id === first.id); const active = out.refused.filter((r) => r.active); + // one that can't move at all says why, and what can be done instead + const stuck = out.refused.find((r) => r.stuck), ss = stuck && data.sessions.find((x) => x.id === stuck.id); status(active.length ? t(active.length === 1 ? "{title} is still being written to; close it in {agent} and try again in a minute" : "{n} sessions are still being written to; close them in {agent} and try again in a minute", { title: s?.title || first.id, n: active.length, agent: "Codex" }) + : stuck ? t("{title} can't be moved: Codex keeps its history by byte and has no record of it in its database to move it by. It stays on {from}, unchanged, and Codex lists it when it uses {from} again. To clear it from here, delete it: it goes to magpie's trash and can be restored.", { title: ss?.title || stuck.id, from: stuck.from }) : (s?.title || first.id) + ": " + first.error, "err"); } return out; diff --git a/internal/gui/assets/plugins/sessions/i18n.js b/internal/gui/assets/plugins/sessions/i18n.js index b2800178f..56130e0df 100644 --- a/internal/gui/assets/plugins/sessions/i18n.js +++ b/internal/gui/assets/plugins/sessions/i18n.js @@ -81,6 +81,7 @@ magpie.strings({ "Made with {from}: Codex's history lists only {to}'s sessions now": "用 {from} 创建:Codex 现在的历史列表只显示 {to} 的会话", "{n} sessions moved to magpie's trash": "{n} 个会话已移到 magpie 的回收站", "{title} is still being written to; close it in {agent} and try again in a minute": "「{title}」仍在写入;请在 {agent} 中关闭它,一分钟后再试", + "{title} can't be moved: Codex keeps its history by byte and has no record of it in its database to move it by. It stays on {from}, unchanged, and Codex lists it when it uses {from} again. To clear it from here, delete it: it goes to magpie's trash and can be restored.": "「{title}」无法迁移:Codex 按字节位置保存它的历史,而它的数据库里没有这个会话的记录可供迁移。它保持在 {from} 上,不做任何改动;Codex 再次使用 {from} 时会列出它。如果想把它从这里清掉,可以删除它:它会进入 magpie 的回收站,可以恢复。", "{n} sessions are still being written to; close them in {agent} and try again in a minute": "{n} 个会话仍在写入;请在 {agent} 中关闭它们,一分钟后再试", "{title} restored": "已恢复「{title}」", "Trash is empty": "回收站是空的", @@ -179,6 +180,7 @@ magpie.strings({ "Made with {from}: Codex's history lists only {to}'s sessions now": "用 {from} 建立:Codex 現在的歷史列表只顯示 {to} 的會話", "{n} sessions moved to magpie's trash": "{n} 個會話已移到 magpie 的回收站", "{title} is still being written to; close it in {agent} and try again in a minute": "「{title}」仍在寫入;請在 {agent} 中關閉它,一分鐘後再試", + "{title} can't be moved: Codex keeps its history by byte and has no record of it in its database to move it by. It stays on {from}, unchanged, and Codex lists it when it uses {from} again. To clear it from here, delete it: it goes to magpie's trash and can be restored.": "「{title}」無法遷移:Codex 按位元組位置保存它的歷史,而它的資料庫裡沒有這個會話的紀錄可供遷移。它保持在 {from} 上,不做任何改動;Codex 再次使用 {from} 時會列出它。如果想把它從這裡清掉,可以刪除它:它會進入 magpie 的回收站,可以恢復。", "{n} sessions are still being written to; close them in {agent} and try again in a minute": "{n} 個會話仍在寫入;請在 {agent} 中關閉它們,一分鐘後再試", "{title} restored": "已恢復「{title}」", "Trash is empty": "回收站是空的", @@ -277,6 +279,7 @@ magpie.strings({ "Made with {from}: Codex's history lists only {to}'s sessions now": "{from} で作成:Codex の履歴には現在 {to} のセッションだけが表示されます", "{n} sessions moved to magpie's trash": "{n} 件のセッションを magpie のゴミ箱に移動しました", "{title} is still being written to; close it in {agent} and try again in a minute": "「{title}」はまだ書き込み中です。{agent} で閉じてから、1 分後にもう一度お試しください", + "{title} can't be moved: Codex keeps its history by byte and has no record of it in its database to move it by. It stays on {from}, unchanged, and Codex lists it when it uses {from} again. To clear it from here, delete it: it goes to magpie's trash and can be restored.": "「{title}」は移動できません:Codex はこの履歴をバイト位置で保持しており、データベースに移動の手がかりとなる記録がありません。{from} のまま変更されず、Codex が再び {from} を使うと一覧に表示されます。ここから消すには削除してください。magpie のゴミ箱に移され、復元できます。", "{n} sessions are still being written to; close them in {agent} and try again in a minute": "{n} 件のセッションはまだ書き込み中です。{agent} で閉じてから、1 分後にもう一度お試しください", "{title} restored": "「{title}」を元に戻しました", "Trash is empty": "ゴミ箱は空です", @@ -375,6 +378,7 @@ magpie.strings({ "Made with {from}: Codex's history lists only {to}'s sessions now": "Mit {from} erstellt: Der Verlauf von Codex zeigt jetzt nur Sitzungen von {to}", "{n} sessions moved to magpie's trash": "{n} Sitzungen in den Papierkorb von magpie verschoben", "{title} is still being written to; close it in {agent} and try again in a minute": "In „{title}“ wird noch geschrieben; schließen Sie die Sitzung in {agent} und versuchen Sie es in einer Minute erneut", + "{title} can't be moved: Codex keeps its history by byte and has no record of it in its database to move it by. It stays on {from}, unchanged, and Codex lists it when it uses {from} again. To clear it from here, delete it: it goes to magpie's trash and can be restored.": "„{title}“ kann nicht verschoben werden: Codex speichert den Verlauf nach Byte-Position und hat in seiner Datenbank keinen Eintrag, über den er sich verschieben ließe. Die Sitzung bleibt unverändert bei {from}, und Codex listet sie wieder, sobald es {from} verwendet. Um sie hier zu entfernen, löschen Sie sie: Sie kommt in den Papierkorb von magpie und lässt sich wiederherstellen.", "{n} sessions are still being written to; close them in {agent} and try again in a minute": "In {n} Sitzungen wird noch geschrieben; schließen Sie sie in {agent} und versuchen Sie es in einer Minute erneut", "{title} restored": "„{title}“ wiederhergestellt", "Trash is empty": "Der Papierkorb ist leer", diff --git a/internal/gui/sessions_manage.go b/internal/gui/sessions_manage.go index 18f4eaf07..e102faef3 100644 --- a/internal/gui/sessions_manage.go +++ b/internal/gui/sessions_manage.go @@ -351,10 +351,14 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } + // stuck: a session that can't move at all (sessions.StuckError), + // from the provider it stays on type refused struct { ID string `json:"id"` Error string `json:"error"` Active bool `json:"active"` + Stuck bool `json:"stuck,omitempty"` + From string `json:"from,omitempty"` } out := struct { Moved []sessions.CodexMove `json:"moved"` @@ -363,7 +367,12 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) { for _, m := range in.Moves { mv, err := sessions.MoveCodexProvider(m.ID, m.To) if err != nil { - out.Refused = append(out.Refused, refused{ID: m.ID, Error: err.Error(), Active: errors.Is(err, sessions.ErrActive)}) + r := refused{ID: m.ID, Error: err.Error(), Active: errors.Is(err, sessions.ErrActive)} + var stuck *sessions.StuckError + if errors.As(err, &stuck) { + r.Stuck, r.From = true, stuck.From + } + out.Refused = append(out.Refused, r) continue } mv.Backup = tilde(mv.Backup) diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index 2c8850f78..d56ea5a05 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -1651,6 +1651,12 @@ each back to the provider it had. No click moves the page, no left-border accent, every string in Chinese, Japanese and German. Chromium and WebKit, English and Chinese, API faked. +`sessions-codex-provider-stuck.test.cjs` checks the refusal of a Codex +session that can't move at all (a paginated rollout with no row in Codex's +database, @xMopf7RF on X): the status says why, that it stays on its +provider, and that Delete clears it into magpie's trash. All five +languages, 900px and 420px, Chromium and WebKit, API faked. + `sessions-toolbar.test.cjs` uses ten agents to check that fitting tabs stay visible at 1800px, while 900, 660 and 320px windows use a compact agent menu. Resizing keeps the current agent; search and Trash fit, the menu fits the diff --git a/internal/gui/tests/sessions-codex-provider-stuck.test.cjs b/internal/gui/tests/sessions-codex-provider-stuck.test.cjs new file mode 100644 index 000000000..c93213452 --- /dev/null +++ b/internal/gui/tests/sessions-codex-provider-stuck.test.cjs @@ -0,0 +1,92 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A Codex session that can't be moved to Codex's provider at all (a +// paginated rollout with no row in Codex's database, sessions.StuckError; +// @xMopf7RF on X) is refused with stuck and the provider it stays on. The +// page says why, in the reader's language, and what can be done instead: +// it stays where it was, and Delete clears it into magpie's trash. Every +// language, Chromium and WebKit, wide and narrow; the API is faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const at = (min) => new Date(Date.now() - min * 60e3).toISOString(); +const sess = (id, title, provider, min) => ({ + agent: "codex", id, title, cwd: "/work/app", start: at(min + 30), last: at(min), models: [], cost: 0, unpriced: 0, + resume: "codex resume " + id, path: "~/.codex/sessions/x/" + id + ".jsonl.zst", size: 2048, messages: 4, files: 1, deletable: true, + provider, uses_provider: "magpie", +}); + +function serve(lang, calls) { + const sessions = [sess("a1", "an old chat", "zai", 60 * 24 * 200)]; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/sessions/manage") { + return json({ + agents: [{ agent: "codex", count: sessions.length, deletable: true, name: "Codex", icon: "codex-color" }], + agent: "codex", sessions, terminal: false, trash: [], trashDir: "~/Library/Application Support/magpie/trash/sessions", + }); + } + if (url.pathname === "/api/sessions/codex-provider") { + calls.push(route.request().postDataJSON()); + return json({ moved: [], refused: [{ id: "a1", error: "rollout-x.jsonl.zst can't move to magpie: …", active: false, stuck: true, from: "zai" }] }); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { nav: "Sessions", button: "Move to magpie…", move: "Move", said: "an old chat can't be moved: Codex keeps its history by byte and has no record of it in its database to move it by. It stays on zai, unchanged, and Codex lists it when it uses zai again. To clear it from here, delete it: it goes to magpie's trash and can be restored." }, + zh: { nav: "会话", button: "迁移到 magpie…", move: "迁移", said: "「an old chat」无法迁移:Codex 按字节位置保存它的历史,而它的数据库里没有这个会话的记录可供迁移。它保持在 zai 上,不做任何改动;Codex 再次使用 zai 时会列出它。如果想把它从这里清掉,可以删除它:它会进入 magpie 的回收站,可以恢复。" }, + "zh-TW": { nav: "會話", button: "遷移到 magpie…", move: "遷移", said: "「an old chat」無法遷移:Codex 按位元組位置保存它的歷史,而它的資料庫裡沒有這個會話的紀錄可供遷移。它保持在 zai 上,不做任何改動;Codex 再次使用 zai 時會列出它。如果想把它從這裡清掉,可以刪除它:它會進入 magpie 的回收站,可以恢復。" }, + ja: { nav: "セッション", button: "magpie に移行…", move: "移行", said: "「an old chat」は移動できません:Codex はこの履歴をバイト位置で保持しており、データベースに移動の手がかりとなる記録がありません。zai のまま変更されず、Codex が再び zai を使うと一覧に表示されます。ここから消すには削除してください。magpie のゴミ箱に移され、復元できます。" }, + de: { nav: "Sitzungen", button: "Zu magpie umziehen…", move: "Umziehen", said: "„an old chat“ kann nicht verschoben werden: Codex speichert den Verlauf nach Byte-Position und hat in seiner Datenbank keinen Eintrag, über den er sich verschieben ließe. Die Sitzung bleibt unverändert bei zai, und Codex listet sie wieder, sobald es zai verwendet. Um sie hier zu entfernen, löschen Sie sie: Sie kommt in den Papierkorb von magpie und lässt sich wiederherstellen." }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const [lang, w] of Object.entries(words)) { + for (const width of [900, 420]) { + test(`${engine} ${lang} ${width}px: a Codex session that can't move says why and what to do instead`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 640 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + page.on("dialog", (d) => { errors.push("a browser dialog: " + d.message()); d.dismiss(); }); + const calls = []; + await page.route("**/*", serve(lang, calls)); + await page.goto("http://magpie.test/?view=providers"); + const nav = page.locator("#nav").getByRole("button", { name: w.nav, exact: true }); + if (await nav.isVisible()) await nav.click(); + else await page.goto("http://magpie.test/?view=sessions"); + const view = page.locator("#view-sessions"); + const go = view.locator(".sm-provider").getByRole("button", { name: w.button, exact: true }); + await go.click(); + const ask = page.locator("#modal .sm-provider-ask"); + await ask.waitFor(); + await ask.getByRole("button", { name: w.move, exact: true }).click(); + await ask.waitFor({ state: "detached" }); + assert.deepEqual(calls, [{ moves: [{ id: "a1", to: "magpie" }] }]); + await page.waitForFunction((x) => document.querySelector("#status")?.textContent === x, w.said) + .catch(async () => assert.equal(await page.locator("#status").textContent(), w.said)); + const wide = await page.evaluate(() => document.documentElement.scrollWidth > innerWidth); + assert.equal(wide, false, "the page scrolls sideways"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/sessions/codex_provider.go b/internal/sessions/codex_provider.go index b2201c853..c70f8e532 100644 --- a/internal/sessions/codex_provider.go +++ b/internal/sessions/codex_provider.go @@ -382,20 +382,31 @@ func moveCodexPaths(id, to string, paths []string, now time.Time) (CodexMove, er return CodexMove{}, err } mv.Backup = dir - for _, p := range paths { - changed, err := rewriteCodexProvider(p, to) - if err != nil { - // the files changed so far go back as they were - for _, it := range items { - if contains(mv.Files, it.From) { - keptCopy(filepath.Join(dir, "files", it.Name), it.From) - } + // the files changed so far go back as they were + putBack := func() { + for _, it := range items { + if contains(mv.Files, it.From) { + keptCopy(filepath.Join(dir, "files", it.Name), it.From) } + } + for _, p := range paths { + delete(cache, p) + } + saveCache() + } + byRow := "" + for _, p := range paths { + changed, kept, err := rewriteCodexProvider(p, to) + if err != nil { + putBack() return CodexMove{}, err } if changed { mv.Files = append(mv.Files, p) } + if kept && byRow == "" { + byRow = p + } } for _, p := range paths { delete(cache, p) @@ -410,9 +421,30 @@ func moveCodexPaths(id, to string, paths []string, now time.Time) (CodexMove, er } } } + // a paginated rollout whose session_meta the id doesn't fit moves by + // its row alone, which is where Codex reads its provider from; with no + // row to move, it can't be moved at all + if byRow != "" && len(mv.DB) == 0 { + putBack() + os.RemoveAll(dir) + return CodexMove{}, &StuckError{File: filepath.Base(byRow), From: mv.From, To: to} + } return mv, nil } +// StuckError is a Codex session that can't be moved to another provider: +// its rollout keeps its history by byte (paginated), the new id is longer +// than the one its session_meta names, so it can't be written in place, +// and Codex's state database has no row for it to move it by instead. +// Its files are left as they were. +type StuckError struct { + File, From, To string +} + +func (e *StuckError) Error() string { + return fmt.Sprintf("%s can't move to %s: Codex keeps its history by byte, so %q can't be written in place of %q, and Codex's database has no row for it to move it by instead. It stays on %s, as it was: Codex lists it when it uses %s again, and Delete moves it to magpie's trash, where it can be restored", e.File, e.To, e.To, e.From, e.From, e.From) +} + // errThreadOpen is a thread a Codex has open: it holds the thread's writer // lock, and writes on to the file it opened whatever takes its place. It // is ErrActive too, so it is left, and said, as one written to in the @@ -858,20 +890,24 @@ func setMetaProvider(line []byte, to string) ([]byte, bool) { // rewriteCodexProvider sets the provider of every session_meta in a rollout, // compressed or not, and says whether anything changed. The file is written -// beside it and renamed over it, with the time it had. -func rewriteCodexProvider(path, to string) (bool, error) { +// beside it and renamed over it, with the time it had. A session_meta of a +// paginated rollout that to is longer than the id it names is left as it +// is, and said (kept): Codex keeps places in such a rollout by byte, and +// reads its thread's provider from its row in the state database, never +// from the file (RetagPagedCodexThreads), so the row is its move. +func rewriteCodexProvider(path, to string) (changed, kept bool, err error) { fi, err := os.Stat(path) if err != nil { - return false, err + return false, false, err } in, err := openLines(path) if err != nil { - return false, err + return false, false, err } defer in.Close() tmp, err := os.CreateTemp(filepath.Dir(path), ".magpie-"+filepath.Base(path)+"-*") if err != nil { - return false, err + return false, false, err } done := false defer func() { @@ -884,13 +920,12 @@ func rewriteCodexProvider(path, to string) (bool, error) { var z *zstd.Encoder if packed(path) { if z, err = zstd.NewWriter(tmp); err != nil { - return false, err + return false, false, err } w = z } bw := bufio.NewWriterSize(w, 64<<10) br := bufio.NewReaderSize(in, 64<<10) - changed := false for { line, err := br.ReadBytes('\n') if len(line) > 0 { @@ -899,50 +934,50 @@ func rewriteCodexProvider(path, to string) (bool, error) { // a session_meta names its own history_mode: Codex keeps // places in a paginated rollout by byte (fitLine) if out, ok = fitLine(line, out, paginated(line)); !ok { - return false, fmt.Errorf("%s keeps its history by byte, and %q is longer than the provider it names: Codex couldn't open it moved", filepath.Base(path), to) + kept = true } } changed = changed || ok if _, werr := bw.Write(out); werr != nil { - return false, werr + return false, false, werr } } if err == io.EOF { break } if err != nil { - return false, err + return false, false, err } } if !changed { - return false, nil + return false, kept, nil } if err := bw.Flush(); err != nil { - return false, err + return false, false, err } if z != nil { if err := z.Close(); err != nil { - return false, err + return false, false, err } } if err := tmp.Chmod(fi.Mode().Perm()); err != nil { - return false, err + return false, false, err } // the user's session on the disk before it is renamed over the old // one: a machine that goes down between can leave it all zero (#1505) if err := steady.Sync(tmp); err != nil { - return false, err + return false, false, err } if err := tmp.Close(); err != nil { - return false, err + return false, false, err } in.Close() os.Chtimes(tmp.Name(), fi.ModTime(), fi.ModTime()) if err := os.Rename(tmp.Name(), path); err != nil { - return false, err + return false, false, err } done = true - return true, nil + return true, kept, nil } // moveCodexThread sets a thread's model_provider in a Codex state diff --git a/internal/sessions/codex_provider_stuck_test.go b/internal/sessions/codex_provider_stuck_test.go new file mode 100644 index 000000000..406e59a38 --- /dev/null +++ b/internal/sessions/codex_provider_stuck_test.go @@ -0,0 +1,115 @@ +package sessions + +import ( + "bytes" + "database/sql" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/klauspost/compress/zstd" +) + +// pagedPackedSetup is @xMopf7RF's case (X, 11-14): a packed, paginated +// rollout from months ago whose session_meta names a provider shorter +// than magpie, with Codex on magpie now. It gives the rollout's path and +// its bytes, and with row, the state database Codex keeps its row in. +func pagedPackedSetup(t *testing.T, row bool) (path string, b []byte, db *sql.DB) { + t.Helper() + _, codex := manageSetup(t) + src := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T15-48-28-"+mgCX+".jsonl") + plain, err := os.ReadFile(src) + if err != nil { + t.Fatal(err) + } + os.Remove(src) + plain = bytes.Replace(plain, []byte(`"model_provider":"openai"`), []byte(`"model_provider":"zai","history_mode":"paginated"`), 1) + enc, _ := zstd.NewWriter(nil) + b = enc.EncodeAll(plain, nil) + path = filepath.Join(codex, "sessions", "2026", "03", "09", "rollout-2026-03-09T09-25-41-"+mgCX+".jsonl.zst") + os.MkdirAll(filepath.Dir(path), 0o755) + if err := os.WriteFile(path, b, 0o644); err != nil { + t.Fatal(err) + } + old := time.Now().Add(-200 * 24 * time.Hour).Truncate(time.Second) + os.Chtimes(path, old, old) + os.WriteFile(filepath.Join(codex, "config.toml"), []byte("model_provider = \"magpie\"\n\n[model_providers.magpie]\nname = \"magpie\"\n"), 0o644) + if !row { + return path, b, nil + } + db, err = sql.Open("sqlite", filepath.Join(codex, "state_5.sqlite")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { db.Close() }) + if _, err := db.Exec(`CREATE TABLE threads (id TEXT PRIMARY KEY, rollout_path TEXT NOT NULL, model_provider TEXT NOT NULL, history_mode TEXT NOT NULL DEFAULT 'legacy'); + INSERT INTO threads VALUES (?, ?, 'zai', 'paginated')`, mgCX, path); err != nil { + t.Fatal(err) + } + return path, b, db +} + +// A paginated rollout keeps its history by byte, so "magpie" can't be +// written in place of a shorter id in it. The move was refused for it +// ("keeps its history by byte, and "magpie" is longer than the provider +// it names: Codex couldn't open it moved", @xMopf7RF on X), though Codex +// reads such a thread's provider from its row, never from its file: it +// moves by its row, its file as it was, and moves back the same way. +func TestMoveCodexProviderPagedByRow(t *testing.T) { + path, b, db := pagedPackedSetup(t, true) + row := func() string { + var s string + if err := db.QueryRow(`SELECT model_provider FROM threads WHERE id = ?`, mgCX).Scan(&s); err != nil { + t.Fatal(err) + } + return s + } + if m, _ := findManaged(ListAgent("codex"), mgCX); m.Provider != "zai" || m.UsesProvider != "magpie" { + t.Fatalf("listed %q, uses %q", m.Provider, m.UsesProvider) + } + mv, err := MoveCodexProvider(mgCX, "magpie") + if err != nil { + t.Fatal(err) + } + if row() != "magpie" || len(mv.DB) != 1 || len(mv.Files) != 0 || mv.From != "zai" { + t.Fatalf("row %q, moved %+v", row(), mv) + } + if now, _ := os.ReadFile(path); !bytes.Equal(now, b) { + t.Fatal("the paginated rollout was written") + } + if m, _ := findManaged(ListAgent("codex"), mgCX); m.Provider != "magpie" { + t.Fatalf("listed on %q after the move", m.Provider) + } + if _, err := MoveCodexProvider(mgCX, "zai"); err != nil || row() != "zai" { + t.Fatalf("back: %v, row %q", err, row()) + } + if now, _ := os.ReadFile(path); !bytes.Equal(now, b) { + t.Fatal("moving back wrote the rollout") + } +} + +// With no row in Codex's database to move it by, such a thread can't be +// moved: the error says why and what can be done, and nothing is left +// changed, not even a copy in magpie's trash. +func TestMoveCodexProviderPagedNoRow(t *testing.T) { + path, b, _ := pagedPackedSetup(t, false) + _, err := MoveCodexProvider(mgCX, "magpie") + var stuck *StuckError + if !errors.As(err, &stuck) || stuck.From != "zai" || stuck.To != "magpie" { + t.Fatalf("err %v", err) + } + for _, want := range []string{"history by byte", "no row", "stays on zai", "Delete"} { + if !strings.Contains(err.Error(), want) { + t.Fatalf("%q doesn't say %q", err, want) + } + } + if now, _ := os.ReadFile(path); !bytes.Equal(now, b) { + t.Fatal("a refused move changed the file") + } + if left := providerTrash(t); len(left) != 0 { + t.Fatalf("trash kept %v", left) + } +}