sessions: an uninstalled agent's sessions can be deleted and are not offered Resume (_SekiBetu_ on X)

OpenCode (and Cline, Grok, Kimi, Hermes) keep sessions in their own
database, so magpie never deletes them and they stay listed after the
agent is uninstalled, with only Resume. When the agent's command is gone
from PATH, its rows now get Delete (Forget: hidden through the gateway
hidden list, a trash note marked forgot, the agent's files untouched,
Restore unhides) and no resume command. Installed agents are unchanged.

Run on mote: go test -count=1 ./internal/sessions ./internal/gui ok;
go vet darwin, windows, linux -tags nogui ok; gofmt clean; GUI files
sessions-forget (new, 5 languages x chromium+webkit), sessions-gateway-delete,
sessions-manage, sessions-folder-delete, sessions-purge, sessions-row-narrow,
i18n-keys, i18n-en-no-cjk all pass.
Broken by hand: removing the hidden-row filter turned the gui Go test red;
the old client.js turned sessions-forget red (5 of 5 chromium).
Not tried: a real uninstalled OpenCode on a user's machine; the Usage
page's /api/sessions list still shows a forgotten row (manage page only);
the whole GUI suite and full go suite run after the tag.
This commit is contained in:
yetone
2026-11-12 00:09:56 +08:00
parent 535f0dd95f
commit fe20e4dbd8
10 changed files with 356 additions and 6 deletions
+8
View File
@@ -322,6 +322,14 @@ list the session), and `HasGatewayConversations` counts it.
Implementation: [`internal/sessions/gateway_delete.go`](../../internal/sessions/gateway_delete.go),
`Restore` in [`internal/sessions/manage.go`](../../internal/sessions/manage.go), and
[`internal/gui/sessions_manage.go`](../../internal/gui/sessions_manage.go).
An agent whose sessions magpie cannot delete (OpenCode, Cline, Grok, Kimi, Hermes:
rows in the agent's own database or store) and whose command is no longer on
PATH (`cliGone`) is forgettable (_SekiBetu_ on X): its rows get Delete, which
only hides them through the same hidden list (`sessions.Forget`, trash note
marked `forgot`; the agent's own files are not touched), and no Resume
(`resumeFor`). Restore unhides. With the command installed nothing changes.
Tests: `TestUninstalledAgentSessionsAreForgotten`,
`TestManageDeleteOfAnUninstalledAgentTakesItOffTheList`, `sessions-forget.test.cjs`.
A deleted Codex session also leaves the Codex app's list (zhuddan on Discord).
The app (ChatGPT.app's Codex, 26.x) lists threads from its own catalog,
`<CODEX_HOME>/sqlite/codex.db` (`codex-dev.db` for a non-prod build), table
@@ -1534,7 +1534,8 @@ magpie.plugin("sessions", (ctx) => {
if (list.length > 5) names.append(el("li", "more", t("+{n} more", { n: list.length - 5 })));
ed.append(names);
// a gateway session has no files of its agent's here: say what goes
if (list.some((s) => !s.gateway)) ed.append(el("p", "lib-confirm", t("Their files are moved to magpie's trash ({dir}), not erased: Trash puts them back. A session written to in the last minute is left alone, as {agent} may still be running it.", { dir: data.trashDir, agent: a.name })));
if (list.some((s) => !s.gateway && !s.forget)) ed.append(el("p", "lib-confirm", t("Their files are moved to magpie's trash ({dir}), not erased: Trash puts them back. A session written to in the last minute is left alone, as {agent} may still be running it.", { dir: data.trashDir, agent: a.name })));
if (list.some((s) => s.forget)) ed.append(el("p", "lib-confirm", t("{agent} isn't installed here. These sessions leave this list; its own files are not touched, and Trash puts them back.", { agent: a.name })));
if (list.some((s) => s.gateway)) ed.append(el("p", "lib-confirm sm-gw-confirm", t("A session seen only through the gateway leaves this list, and any conversation magpie recorded of it is moved to magpie's trash ({dir}): Trash puts it back. {agent}'s own files elsewhere are not touched, and Usage keeps what it spent. One with a request in the last minute is left alone.", { dir: data.trashDir, agent: a.name })));
const bar = el("div", "bar");
const go = el("button", "text primary danger-fill", t("Delete"));
@@ -1647,8 +1648,8 @@ magpie.plugin("sessions", (ctx) => {
r.append(icon(x.icon));
const who = el("div", "who");
who.append(el("div", "name", x.title || x.id));
who.append(el("div", "sub", [x.name, x.gateway ? t("Seen through the gateway") : x.cwd ? baseName(x.cwd) : "", t("deleted {when}", { when: ago(x.deleted) }),
x.gateway ? (x.size ? t("{size} recorded", { size: fmtBytes(x.size) }) : "") : fmtBytes(x.size)].filter(Boolean).join(" · ")));
who.append(el("div", "sub", [x.name, x.forgot ? t("Taken off the list") : x.gateway ? t("Seen through the gateway") : x.cwd ? baseName(x.cwd) : "", t("deleted {when}", { when: ago(x.deleted) }),
x.forgot ? "" : x.gateway ? (x.size ? t("{size} recorded", { size: fmtBytes(x.size) }) : "") : fmtBytes(x.size)].filter(Boolean).join(" · ")));
who.title = (x.items || []).map((i) => i.from).join("\n");
r.append(who);
const b = el("button", "sess-resume sm-restore");
@@ -84,6 +84,8 @@ magpie.strings({
"{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": "回收站是空的",
"{agent} isn't installed here. These sessions leave this list; its own files are not touched, and Trash puts them back.": "这台电脑上没有安装 {agent}。这些会话会从列表移除,{agent} 自己的文件不动,可在「回收站」恢复。",
"Taken off the list": "已从列表移除",
"Sessions deleted here wait in magpie's trash, to be restored.": "在此删除的会话进入 magpie 回收站,可随时恢复。",
"Deleted sessions are kept in {dir} until you erase them here; magpie never erases them by itself.": "已删除的会话保存在 {dir},在此彻底删除前不会自动清除。",
"Empty magpie's trash?": "清空 magpie 的回收站?",
@@ -180,6 +182,8 @@ magpie.strings({
"{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": "回收站是空的",
"{agent} isn't installed here. These sessions leave this list; its own files are not touched, and Trash puts them back.": "這台電腦上沒有安裝 {agent}。這些會話會從清單移除,{agent} 自己的檔案不動,可在「回收桶」還原。",
"Taken off the list": "已從清單移除",
"Sessions deleted here wait in magpie's trash, to be restored.": "在此刪除的會話進入 magpie 回收站,可隨時恢復。",
"Deleted sessions are kept in {dir} until you erase them here; magpie never erases them by itself.": "已刪除的會話儲存在 {dir},在此徹底刪除前不會自動清除。",
"Empty magpie's trash?": "清空 magpie 的回收站?",
@@ -276,6 +280,8 @@ magpie.strings({
"{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": "ゴミ箱は空です",
"{agent} isn't installed here. These sessions leave this list; its own files are not touched, and Trash puts them back.": "このコンピュータに {agent} はインストールされていません。これらのセッションは一覧から外れ、{agent} 自身のファイルには触れません。ゴミ箱から戻せます。",
"Taken off the list": "一覧から外しました",
"Sessions deleted here wait in magpie's trash, to be restored.": "ここで削除したセッションは magpie のゴミ箱に残り、元に戻せます。",
"Deleted sessions are kept in {dir} until you erase them here; magpie never erases them by itself.": "削除したセッションは、ここで消去するまで {dir} に保存されます。magpie が自動で消去することはありません。",
"Empty magpie's trash?": "magpie のゴミ箱を空にしますか?",
@@ -372,6 +378,8 @@ magpie.strings({
"{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",
"{agent} isn't installed here. These sessions leave this list; its own files are not touched, and Trash puts them back.": "{agent} ist hier nicht installiert. Diese Sitzungen verschwinden aus der Liste; die eigenen Dateien von {agent} bleiben unberührt, der Papierkorb bringt sie zurück.",
"Taken off the list": "Aus der Liste genommen",
"Sessions deleted here wait in magpie's trash, to be restored.": "Hier gelöschte Sitzungen bleiben zur Wiederherstellung im Papierkorb von magpie.",
"Deleted sessions are kept in {dir} until you erase them here; magpie never erases them by itself.": "Gelöschte Sitzungen bleiben in {dir}, bis Sie sie hier endgültig löschen; magpie löscht sie nie von selbst.",
"Empty magpie's trash?": "Papierkorb von magpie leeren?",
+9
View File
@@ -223,6 +223,11 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {
out.Agent = view.Agent
if out.Agent != "" {
list := view.Sessions
if !sessions.Deletable(out.Agent) {
// the ones taken off the list (sessions.Forget), until used again
hidden := sessions.GatewayHidden()
list = slices.DeleteFunc(slices.Clone(list), func(m sessions.Managed) bool { return hidden(m.Agent, m.ID, m.Last) })
}
var modelEffort map[string][]sessions.ModelEffort
if out.Agent == "codex" {
modelEffort = usage.CodexModelEffort(usage.All)
@@ -314,6 +319,10 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {
var err error
if g, ok := listed[id]; ok {
_, err = sessions.DeleteGateway(g.Agent, g.ID, g.ID, g.Last)
} else if sessions.Forgettable(in.Agent) {
// an uninstalled agent's rows of a database magpie only
// reads: they leave the list, its files are not touched
_, err = sessions.Forget(in.Agent, id)
} else if !sessions.Deletable(in.Agent) {
err = errors.New("magpie can't delete this agent's sessions")
} else {
+78
View File
@@ -0,0 +1,78 @@
package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/sessions"
)
// _SekiBetu_ on X: OpenCode was uninstalled and its sessions stayed on the
// management page with a Resume and no Delete. With its command gone, the
// page lists them with a Delete that takes them off the list (OpenCode's
// files are not touched) and no Resume; Restore in the trash lists them
// again. With the command there, as before: no Delete.
func TestManageDeleteOfAnUninstalledAgentTakesItOffTheList(t *testing.T) {
h := sandboxHome(t)
t.Setenv("XDG_DATA_HOME", "")
if err := os.CopyFS(filepath.Join(h, ".local", "share", "opencode"), os.DirFS("../sessions/testdata/opencode")); err != nil {
t.Fatal(err)
}
sessions.Reset()
t.Cleanup(sessions.Reset)
mux := http.NewServeMux()
sessionManageRoutes(mux, folderOnly{})
type manage struct {
Agents []struct {
Agent string `json:"agent"`
Deletable bool `json:"deletable"`
} `json:"agents"`
Sessions []struct {
ID string `json:"id"`
Resume string `json:"resume"`
Deletable bool `json:"deletable"`
Forget bool `json:"forget"`
} `json:"sessions"`
Trash []struct {
Key string `json:"key"`
Forgot bool `json:"forgot"`
} `json:"trash"`
}
call := func(method, path, body string) (m manage) {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
if w.Code != 200 {
t.Fatalf("%s %s: %d %s", method, path, w.Code, w.Body)
}
json.Unmarshal(w.Body.Bytes(), &m)
return m
}
m := call("GET", "/api/sessions/manage?agent=opencode", "")
// the fixtures' two: one with a conversation, one nothing was said in
if len(m.Sessions) != 2 || m.Sessions[0].Deletable || m.Sessions[0].Resume == "" {
t.Fatalf("installed: %+v", m.Sessions)
}
id := m.Sessions[0].ID
other := m.Sessions[1].ID
t.Cleanup(sessions.ForceCLIGone("opencode"))
m = call("GET", "/api/sessions/manage?agent=opencode", "")
if len(m.Sessions) != 2 || !m.Sessions[0].Deletable || !m.Sessions[0].Forget || m.Sessions[0].Resume != "" || !m.Agents[0].Deletable {
t.Fatalf("uninstalled: %+v %+v", m.Agents, m.Sessions)
}
call("POST", "/api/sessions/delete", `{"agent":"opencode","ids":["`+id+`"]}`)
m = call("GET", "/api/sessions/manage?agent=opencode", "")
if len(m.Sessions) != 1 || m.Sessions[0].ID != other || len(m.Trash) != 1 || !m.Trash[0].Forgot {
t.Fatalf("after delete: %+v trash %+v", m.Sessions, m.Trash)
}
call("POST", "/api/sessions/restore", `{"key":"`+m.Trash[0].Key+`"}`)
if m = call("GET", "/api/sessions/manage?agent=opencode", ""); len(m.Sessions) != 2 {
t.Fatalf("after restore: %+v", m.Sessions)
}
}
@@ -0,0 +1,91 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// _SekiBetu_ on X: OpenCode was uninstalled and its sessions stayed listed
// with Resume and no Delete. With the agent's command gone the page gives
// its rows no Resume and a Delete whose dialog says the session only leaves
// the list (its own files are not touched); the Trash marks it as taken off
// the list. In every language, Chromium and WebKit; 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 ID = "ses_1a2b3c4d5e6fAAAAAAAAAAAAAA";
const DIR = "~/Library/Application Support/magpie/trash/sessions";
const KEYS = {
confirm: "{agent} isn't installed here. These sessions leave this list; its own files are not touched, and Trash puts them back.",
off: "Taken off the list",
};
function serve(lang, calls) {
const store = { sessions: [{ agent: "opencode", id: ID, title: "Flaky test hunt", cwd: "/work/oc", start: at(900), last: at(800), size: 4, messages: 4, files: 1,
models: [], deletable: true, forget: true, transcript: false, resume: "" }], trash: [] };
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: "opencode", count: store.sessions.length, deletable: true, name: "OpenCode", icon: "generic" }],
agent: "opencode", sessions: store.sessions, terminal: false, trash: store.trash, trashDir: DIR, recording: false, recorded: false });
}
if (url.pathname === "/api/sessions/delete") {
const body = route.request().postDataJSON();
calls.push(body);
store.sessions = [];
store.trash.push({ key: "gateway/20261111-x", agent: "opencode", id: ID, title: "Flaky test hunt", last: at(800), deleted: at(0), size: 0, gateway: true, forgot: true, items: [], name: "OpenCode", icon: "generic" });
return json({ deleted: body.ids, refused: [] });
}
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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${lang}: an uninstalled agent's session has a Delete that only takes it off the list`, 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: 1000, height: 700 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const calls = [];
await page.route("**/*", serve(lang, calls));
await page.goto("http://magpie.test/?view=providers");
const tr = (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]);
if (lang !== "en") {
const missing = await page.evaluate(([lang, keys]) => keys.filter((k) => !I18N[lang]?.[k]), [lang, Object.values(KEYS)]);
assert.deepEqual(missing, [], `every new string has its ${lang}`);
}
await page.locator('#nav button[data-view="sessions"]').click();
const view = page.locator("#view-sessions");
const row = view.locator(".sm-sess").filter({ hasText: "Flaky test hunt" });
await row.waitFor();
assert.equal(await row.locator(".sess-resume").count(), 0, "no Resume for an agent that isn't there");
assert.equal(await view.locator(".sm-note:not(.sm-speed-note)").count(), 0, "no 'cannot delete' note");
await row.locator(".sm-del").click();
const ask = page.locator("#modal .sm-ask");
await ask.waitFor();
const said = (await ask.locator(".lib-confirm").allTextContents()).map((x) => x.trim());
assert.deepEqual(said, [await tr(KEYS.confirm, { agent: "OpenCode" })], "says it only leaves the list");
await ask.locator(".bar button.primary").click();
await ask.waitFor({ state: "detached" });
assert.deepEqual(calls, [{ agent: "opencode", ids: [ID] }]);
await view.locator(".sm-trash-btn").click();
const trow = view.locator(".sm-trash .row").filter({ hasText: "Flaky test hunt" });
await trow.waitFor();
assert((await trow.locator(".sub").textContent()).includes(await tr(KEYS.off)));
assert.deepEqual(errors, []);
});
}
}
+9 -2
View File
@@ -55,6 +55,8 @@ type Managed struct {
Messages int `json:"messages"`
Files int `json:"files"`
Deletable bool `json:"deletable"`
// Forget: Delete takes it off the list, its agent's files untouched
Forget bool `json:"forget,omitempty"`
// Undeletable: why a session of an agent whose sessions can be deleted
// can't be: "cursor-editor", a chat Cursor's editor keeps in its own
// database, or "read-only" (rowDeletable). The page says it on the
@@ -142,7 +144,7 @@ func agentCounts(all []file) []AgentCount {
}
out := []AgentCount{}
for a, keys := range n {
out = append(out, AgentCount{Agent: a, Count: len(keys), Deletable: Deletable(a)})
out = append(out, AgentCount{Agent: a, Count: len(keys), Deletable: Removable(a)})
}
sort.Slice(out, func(i, j int) bool {
if out[i].Count != out[j].Count {
@@ -319,6 +321,8 @@ func listAgentWith(agent string, all []file, quick bool) []Managed {
// a WSL distro's too (TJHHHH): moved out over \\wsl.localhost
m := Managed{Session: s, Files: len(fs)}
m.Deletable, m.Undeletable = rowDeletable(agent, s, fs)
m.Forget = !Deletable(agent) && Forgettable(agent)
m.Deletable = m.Deletable || m.Forget
for _, f := range fs {
m.Size += f.size
m.Pending = m.Pending || pending[f.path]
@@ -377,7 +381,7 @@ func keptSubagents(out []Managed) []Managed {
// whether its conversation can be read.
func listed(s *Session) {
if s.Resume == "" && !s.ReadOnly {
s.Resume = resumeCommand(s.WSL, s.Agent, s.ID, s.Cwd, s.Path)
s.Resume = resumeFor(s.WSL, s.Agent, s.ID, s.Cwd, s.Path)
}
if s.Carry == nil {
s.Carry = carries(*s)
@@ -402,6 +406,9 @@ type Trashed struct {
// Gateway: a session seen only through magpie's gateway, whose items
// are the conversation text magpie recorded of it (gateway_delete.go)
Gateway bool `json:"gateway,omitempty"`
// Forgot: a session of an agent that is gone, taken off the list
// (Forget); nothing of it was moved, Restore lists it again
Forgot bool `json:"forgot,omitempty"`
// CodexCatalog: a Codex thread's rows in the Codex app's catalog,
// taken out with it and put back on Restore (codex_catalog.go)
CodexCatalog []codexCatalogRow `json:"codex_catalog,omitempty"`
+11 -1
View File
@@ -2053,7 +2053,7 @@ func assemble(fs []file, price func(string) *catalog.Price, codexTitle func(stri
return s, false
}
if !s.ReadOnly {
s.Resume = resumeCommand(s.WSL, s.Agent, s.ID, s.Cwd, s.Path)
s.Resume = resumeFor(s.WSL, s.Agent, s.ID, s.Cwd, s.Path)
}
s.Carry, s.Transcript = carries(s), readable(s)
if s.Transcript {
@@ -2874,6 +2874,16 @@ func ResumeCommand(agent, id, cwd string) string { return resumeCommand("", agen
// resumeCommand is ResumeCommand for a session in a WSL distro too, when
// distro is set: see wslResume.
// resumeFor is resumeCommand for a listed row: none for an agent whose
// command is gone from this computer, which the line would fail to start.
// A WSL distro's agent is looked for there, not here.
func resumeFor(distro, agent, id, cwd, path string) string {
if distro == "" && cliGone(agent) {
return ""
}
return resumeCommand(distro, agent, id, cwd, path)
}
func resumeCommand(distro, agent, id, cwd, path string) string {
if !safeID.MatchString(id) {
return ""
+79
View File
@@ -0,0 +1,79 @@
package sessions
import (
"errors"
"slices"
"testing"
"time"
)
// An agent that was uninstalled leaves its sessions behind: OpenCode's are
// rows in a database magpie only reads (_SekiBetu_ on X: after removing
// OpenCode, its sessions stayed listed with a Resume and no Delete). Two
// things follow from the command being gone. Resume is no longer offered:
// the line would fail. And the list may be cleared: magpie can't delete
// rows of a database the agent keeps, but it can stop listing them, which
// is what Forget does. The agent's own files are never touched, and Restore
// in the trash lists the session again.
// cliOf is the command each agent's sessions are resumed with, for the
// agents magpie can't move to the trash (Deletable) as well.
var cliOf = map[string]string{
"claude": "claude", "codex": "codex", "opencode": "opencode", "pi": "pi",
"cline": "cline", "qoder": "qodercli", "qoder-cn": "qoderclicn",
"grok": "grok", "codebuddy": "codebuddy", "omp": "omp", "droid": "droid",
"kimi": "kimi", "agy": "agy", "cursor": "cursor-agent", "hermes": "hermes",
}
// cliGone says whether an agent's command is not installed on this
// computer. An agent with no command of its own (an app) is never gone.
// A var so tests can say; a test run answers false.
var cliGone = func(agent string) bool {
bin := cliOf[agent]
return bin != "" && !testing.Testing() && !lookOK(bin)
}
// Forgettable says whether magpie can stop listing an agent's sessions: its
// sessions can't be moved to the trash, and its command is gone.
func Forgettable(agent string) bool { return !Deletable(agent) && cliGone(agent) }
// Removable says whether Delete is on an agent's rows: they go to the
// trash, or, with the agent uninstalled, off the list (Forget).
func Removable(agent string) bool { return Deletable(agent) || Forgettable(agent) }
// Forget takes a listed session of an agent that is gone off the list, as
// DeleteGateway does for one seen only through the gateway: its note is in
// the trash, and Restore lists it again, as does a use of it after.
func Forget(agent, id string) (Trashed, error) {
if !Forgettable(agent) {
return Trashed{}, errors.New("magpie can't delete this agent's sessions")
}
for _, m := range ListAgent(agent) {
if m.ID == id {
return forgetSession(agent, id, m.Title, m.Last)
}
}
return Trashed{}, errors.New("no such session")
}
func forgetSession(agent, id, title string, last time.Time) (Trashed, error) {
t, err := DeleteGateway(agent, id, title, last)
if err != nil {
return t, err
}
// DeleteGateway wrote the note without it: say it is no gateway text
t.Forgot = true
dir := trashFolder(t.Key)
if dir == "" {
return t, errors.New("no such deleted session")
}
return t, writeManifest(dir, t)
}
// ForceCLIGone says, for a test in another package, which agents' commands
// are gone; the returned func puts it back.
func ForceCLIGone(agents ...string) (restore func()) {
old := cliGone
cliGone = func(a string) bool { return slices.Contains(agents, a) }
return func() { cliGone = old }
}
+59
View File
@@ -0,0 +1,59 @@
package sessions
import (
"path/filepath"
"testing"
)
// _SekiBetu_ on X: OpenCode uninstalled, its sessions stayed listed with a
// Resume and no Delete. With its command gone Resume is not offered, Delete
// takes the row off the list (its database is not touched), and Restore
// lists it again.
func TestUninstalledAgentSessionsAreForgotten(t *testing.T) {
inZone(t, 0)
data, _ := setupMore(t)
ocMakeDB(t, filepath.Join(data, "opencode", "opencode.db"))
t.Cleanup(ForceCLIGone())
row := func() Managed {
t.Helper()
for _, m := range ListAgent("opencode") {
if m.ID == ocMain {
return m
}
}
t.Fatal("no OpenCode session")
return Managed{}
}
if m := row(); m.Resume == "" || m.Deletable {
t.Fatalf("installed: %+v", m)
}
if _, err := Forget("opencode", ocMain); err == nil {
t.Fatal("forgot a session of an installed agent")
}
defer ForceCLIGone("opencode")()
if oc := find(t, List(0), "opencode", ocMain); oc.Resume != "" {
t.Fatalf("resume offered with opencode gone: %q", oc.Resume)
}
if m := row(); m.Resume != "" || !m.Deletable || !m.Forget {
t.Fatalf("uninstalled: resume %q deletable %v forget %v", m.Resume, m.Deletable, m.Forget)
}
m := row()
tr, err := Forget("opencode", ocMain)
if err != nil {
t.Fatal(err)
}
if !tr.Forgot || !GatewayHidden()("opencode", ocMain, m.Last) {
t.Fatalf("not hidden after Forget: %+v", tr)
}
if got := Trash(); len(got) != 1 || !got[0].Forgot {
t.Fatalf("trash %+v", got)
}
if _, err := Restore(tr.Key); err != nil {
t.Fatal(err)
}
if GatewayHidden()("opencode", ocMain, m.Last) {
t.Fatal("still hidden after Restore")
}
}