sessions: a paginated Codex rollout moves to a longer provider id by its row (@xMopf7RF on X)
@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. Since67b12956aa 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/maine0889719c): - go test -count=1 -run 'TestMoveCodexProvider|TestRetagPaged|TestPortCodex' ./internal/sessions/ on mote: ok. - Old code back (codex_provider.go frome0889719c, 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.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -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;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user