sessions: search what was said in every agent's sessions, from the page and an MCP server

cryingLiu on X asked to search the chat history of every agent magpie
reads sessions from: prompts and replies, from one place.

What the user gets:
- The Sessions page's search also lists, under the agent's own list,
  the other agents' sessions whose conversation says the words, each
  with a snippet. A hit opens the conversation in the sheet at the
  message that said it (transcript?find=), with "N earlier messages
  not shown"; the page itself never scrolls. While the index is still
  being built the head says "Indexing sessions…" or "Indexing N of M
  sessions…", and the page asks again every 3s until it is done.
- Magpie Sessions, a built-in MCP server in Library → MCP (Discover),
  opt in per agent like the other magpie servers. Its tools are
  search_sessions(query, agent?, limit) and read_session(id, around?),
  both returning text. It runs as `magpie mcp sessions` over stdio and
  reaches the gateway's /mcp/magpie/sessions, which serves only local
  callers that are not browsers.

How it works:
- internal/sessions/said_index.go keeps said-v1.db beside sessions.json:
  a contentless SQLite FTS5 index (detail=none) of the words each
  session says. It is built from the sessions list sessions already
  caches and refreshed at most every 10s: a new or rewritten file is
  read once, a grown Claude Code or Codex file only from where it ended,
  and a gone one is forgotten. A query asks the index which sessions
  have every word, then reads only those files for the snippet, for at
  most 6s. A search waits up to 2s for a refresh. While the first
  listing is still running the answer says `listing`, so an empty first
  answer is not read as "no session says it".
- Privacy: only agents sessions.Reads allows are indexed or searched;
  nothing is read until the user has answered the sessions question,
  and in gateway mode no agent's own files are read (the page doesn't
  ask). Reset forgets the index.
- /api/sessions/said for the page; the CLI parity list names it.

Run, at this tree (rebased on origin/main 256910f17):
- gofmt -l clean; go vet on mote for darwin, GOOS=linux -tags nogui
  and GOOS=windows: ok.
- go test -tags nogui ./... -timeout 45m on the WSL Linux box:
  every package ok at c8e445c4b (the tree before the one-hit wording,
  whose gateway tests ran again on mote: ok).
- GUI: the whole suite on mica at this head was still running when
  this was pushed (owner: never hold a verified change behind a full
  suite). Under mica's load, beside another session's full suite, 90
  tests had failed so far, all in files this change doesn't touch
  (accounts, Details, keys, plugins, providers); none in sessions,
  library or i18n. The files this change reaches passed on their own
  (below).
- Focused, green: internal/sessions (Said*, TranscriptAt),
  internal/gateway (SessionsMCP*, own MCP, read-only, key slots),
  internal/library (market, opt in), internal/gui (Said, Sessions,
  gateway mode); GUI sessions-said, sessions-search, library-sessions-mcp,
  vision-mcp-library, library-browser-setup and i18n-keys in chromium
  and webkit, every language, wide and narrow.
- Broken by hand, one at a time, each red and green restored: the
  index's Listing left out (TestSearchSaidWhileTheSessionsAreFound red
  in 2.5s); the page ignoring `listing` (sessions-said 6 of 7 red); the
  MCP's local/browser guard (TestSessionsMCPOnlyForAgentsHere red); the
  server's opt in (TestSessionsServerInDiscover red); every Reads check
  on the search path, the index's and SearchSession's together
  (TestSearchSaidLeavesOutAgentsNotRead red). With those gone the
  gateway-mode GUI test stays green, because the sessions listing
  leaves an unread agent out before the index sees it.
- Real use, in a sandbox HOME with GOPATH, GOMODCACHE and GOCACHE
  pinned, over the real history through symlinks (29 GB Claude Code,
  60 GB Codex, 14,102 sessions), sessions reads set to all in the
  sandbox: first listing ~60s cold (answers say still being found),
  whole index built in 9m50s while queries answered in ~6s each, index
  38 MB, a common word 4.9s and a rare word 1.0s warm, read_session at
  the words of a huge session 1.8s, peak footprint 442 MB for the whole
  process with the sessions cache. Nothing was written under the real
  ~/.claude or ~/.codex.
- The real binary end to end on mote, in a sandbox HOME: `magpie serve`
  on a free port and `magpie mcp sessions` over stdio with
  MAGPIE_GATEWAY, against a Claude Code session written there:
  initialize, tools/list, search_sessions found it with its snippet,
  read_session at the words started 3 messages before them, a word
  nowhere said "No session says", and a POST with a web page's Origin
  was refused 403. That run is how "1 sessions say" was found and
  made "1 session says" (TestSessionsMCPSearch red before, green after).

Not tried: a real agent (Claude Code, Codex) calling the server it was
given from the Library, and the page against a real backend (the GUI
tests fake the API). The index on Windows and Linux ran only through
the Go suite.
This commit is contained in:
yetone
2026-11-16 07:19:18 +08:00
parent 103eff4d44
commit 64c4261582
30 changed files with 2284 additions and 23 deletions
+58
View File
@@ -635,6 +635,64 @@ for the line filter), `TestContainsFold`, `TestMayHoldSkipsAFileWithoutTheWords`
`TestGatewayTitleAndSearch`, `TestSessionsSearch*`; browser
`sessions-search.test.cjs`.
### What was said in every agent's sessions
The same search over every agent at once (cryingLiu on X) can't read the
files each query: this computer's Claude Code history alone is 29 GB in
7,390 files. `sessions.SearchSaid` asks an index of the words said in them,
`said-v1.db` beside `sessions.json`: an SQLite FTS5 table with no text kept,
only which words are in which session (`content=''`, `detail='none'`; the
user's and the model's text, about 1% of the bytes). It is made the first
time a search asks, in the background, the newest sessions first, from the
sessions `sessions.json` already lists (`saidSessions`), and brought up to
date by the next search more than 10 s on (`saidStale`): a Claude Code or
Codex file that grew is read from where the last read ended (`upto`, at a
line's end), any other session again whole when its files changed, and a
session gone or rewritten is dropped. A search waits for that at most 2 s
(`saidWait`) and is otherwise answered from what is indexed, saying
`indexed` of `total`; while the first listing of the sessions is still
running (about 50 s over a 29 GB Claude Code and 60 GB Codex history with
a cold `sessions.json`) it says `listing` instead, so neither the page nor
the MCP server reads an empty first answer as "no session says it". Words are letter-or-digit runs matched by their start
(`auth` finds `authentication`); Chinese, Japanese and Korean go as each
two characters side by side (`saidWords`, `saidTerms`). The index only says
which sessions are worth reading: those are read newest first with
`SearchSession` for the hit and the words round it, to `limit` hits.
An agent magpie may not read (`Reads`, Settings › Sessions and gateway
mode) is left out of every answer at once and out of the index on its next
update; turning gateway mode on or off closes the index (`Reset` →
`ForgetSaid`, which stops a refresh running at the next session).
- `GET /api/sessions/said?q=&agent=&limit=` is the Sessions page's: under
the agent's own list, the sessions of other agents that said the words
(Other agents), asked again every 3 s while the index is still reading.
The page asks nothing in gateway mode.
- `GET /api/sessions/transcript?…&find=` reads the conversation from a few
messages before the first part that says the words (`TranscriptAt`,
`transcriptLead`), with `from` the parts left out. A hit, in the agent's
list or another's, opens the conversation sheet there: the part is ringed
(`sess-found`), its words marked with the CSS Custom Highlight API where
the browser has it, and the sheet, never the page, scrolled to it once.
- The `magpie-sessions` MCP server (`SessionsMCPPath`,
`/mcp/magpie/sessions`, [`sessions_mcp.go`](../../internal/gateway/sessions_mcp.go))
gives an agent `search_sessions(query, agent?, limit)` and
`read_session(session, find?, from?, max_chars?)`, as text: each hit's
`agent:id`, title, folder, time and the words round it; a read numbers
each message, shortens tool calls and answers, leaves thinking out, and
says how to go on (`from=`). Like Magpie Memory it answers the agents on
this computer alone, never another computer's key or a web page. The
Library offers it as opt-in, run as `magpie mcp sessions`
(`browsermcp.RunSessions`).
Implementation: [`internal/sessions/said_index.go`](../../internal/sessions/said_index.go),
`TranscriptAt` in [`transcript.go`](../../internal/sessions/transcript.go),
the `said` route in [`sessions_manage.go`](../../internal/gui/sessions_manage.go).
Verification: `TestSearchSaid*` (`TestSearchSaidReadsAGrownFileFromWhereItEnded`,
`TestSearchSaidLeavesOutAgentsNotRead`), `TestSaidWords`, `TestSaidTerms`,
`TestTranscriptAtStartsBeforeTheHit`, `TestSessionsMCP*`,
`TestSessionsServerInDiscover`, `TestGatewayModeListsNoOwnSessions`;
browser `sessions-said.test.cjs`, `library-sessions-mcp.test.cjs`.
Verification: `TestGatewayConversation*` (`TestGatewayConversationNeedsTheClientsSession`
and `TestGatewayConversationClientRequestPrefixedSession` for the two rules above), `TestGatewaySessionHistoryAndCalendar`,
`TestGatewaySessionsNativeWinsBeforeLimits`,
+1
View File
@@ -84,6 +84,7 @@ Pi's extensions and packages.
- Magpie Web Search (`magpie-web-search`, `searchServer` in [`market.go`](../../internal/library/market.go)) is the featured, opt-in server for magpie's web search: `magpie mcp search` (`RunSearch` in [`browsermcp.go`](../../internal/browsermcp/browsermcp.go)) passes each stdio message to the gateway's `/mcp/magpie/web-search`, as `magpie mcp browser` does to its own path, with no browser session. Its sheet says each search goes where Settings › Models › Web search sends it. That page's MCP server row (`#searchMcpRow`) keeps the address to copy, and under its words Give agents Magpie Web Search… opens the sheet in the Library (`magpie.call("library", "server", "magpie-web-search")`), Turn on the Library when the Library is off, and nothing in gateway mode, as Settings › Models › Images does for Magpie Image (lutra_fs on Discord: the search was in Settings and not in the Library; `search-mcp-library.test.cjs`). Each agent is given a 120-second tool timeout for it (`selfTimeout`). An agent in WSL is not given it directly, as with Magpie Browser; the MCP router serves it there.
- Magpie Browser (`magpie-browser`) is opt-in, added with no agents, so the router offers it to none until one is ticked (an agent asked to use the browser reached for AppleScript instead). While its extension is connected (`GET /api/library/browser`, read again every 3 seconds while the row is shown) and no agent has it, its row in the MCP list asks which agents may use it, on a line of its own under the row's name, command and chips (from the name's left edge to the row's right one, the row's `lib-asking`), a button per agent whose chip can be clicked; a button clicks that chip, so the choice goes through `servers/agents` as a chip's does, and the row asks nothing more (`browserAsk` in [`client.js`](../../internal/gui/assets/plugins/library/client.js); `library-browser-ask.test.cjs`).
- A page whose browser can't reach magpie's folders (magpie in a container, `gateway.InContainer`, or a page from another computer) is told so (`browserJSON.Away`), and the sheet's button is Download the extension: `POST /api/library/browser/extension` with the page's origin answers a zip of the extension (`browserext.Zip`) pointed at that origin, with the secret of the On gateway key named Magpie Browser, made by the first download (`browserKey`). It is a POST so a cross-site link can't mint a key. The zip lands in Downloads, so the key is a browser key (`access.Key.Browser`): it opens the extension's socket and nothing else, no model, MCP server or stat (`readOnlyGuard`, see [gateway routing](gateway-routing.md); Gateway → Gateway keys tags it Browser only and offers no access to change). One a magpie from before made with full access is held so with the same secret as the gateway starts and on the next download (`ScopeOwnBrowserKey`, `access.ScopeBrowser`), so the extension keeps connecting. A browser connecting from elsewhere with a key belongs to it: the gateway's relay gives it only to sessions tagged `key:<id>/` (`browserOwner`, `keyedSession` in [`browser.go`](../../internal/gateway/browser.go)), which is what a remote caller's session is forced to. The key the page makes is recorded as this magpie's own browser's (`SetOwnBrowserKey`, a file in the settings folder), and a browser connecting with it serves this computer's sessions too when it connects from this computer (`browserConn.own`: the key and `local`, so not through a proxy or the page port; `serves`). From another computer, the Docker bridge's 172.17.0.1 included, the key proves nothing: a copy of the zip could connect a browser there, and this computer's agents' calls would go to it, so it serves only its key's sessions (#5529). A record that can't be read names no key. A keyed connection lasts while its key does: `watchKey` looks every 5 seconds and closes the socket once the key is turned off, removed, expired or rotated (`access.Current`), and a call looks first too (`TestBrowserIsItsKeys`; `TestOwnBrowserKeyIsThisComputers`; `TestBrowserKeyOffClosesItsBrowser`; `TestBrowserExtensionDownload`; `library-browser-away.test.cjs`; `gateway-key-readonly.test.cjs`).
- Magpie Sessions (`magpie-sessions`, `sessionsServer` in [`market.go`](../../internal/library/market.go)) is the opt-in server that searches and reads what was said in every agent's sessions on this computer (cryingLiu on X): `magpie mcp sessions` (`RunSessions`) passes each stdio message to the gateway's `/mcp/magpie/sessions`, which answers this computer's agents alone, as Magpie Memory's does (`hereOnly`). No agent is ticked until picked (`library-sessions-mcp.test.cjs`, `TestSessionsServerInDiscover`). See [gateway-sessions.md](gateway-sessions.md#what-was-said-in-every-agents-sessions).
- Magpie Image Recognition (`magpie-vision`, `visionServer` in [`market.go`](../../internal/library/market.go)) is the featured, opt-in server for image recognition, beside Magpie Image and Magpie Web Search (matrix0487 on Discord: Discover had two of magpie's three): `magpie mcp vision` (`RunVision` in [`browsermcp.go`](../../internal/browsermcp/browsermcp.go)) passes each stdio message to the gateway's `/mcp/magpie/vision`, and makes `analyze_image`'s relative `image` path one in the agent's own folder on the way (`imageFrom`), since the gateway can't know where the agent runs; an absolute path, `~`, a URL or a drive goes as written. Its sheet says each image goes to Settings › Models › Images › Image recognition's model. That row has Give agents Magpie Image Recognition… (`libWay` in app.js, shared with Images' and Web search's links), Turn on the Library with the Library off, and nothing with recognition off or in gateway mode (`vision-mcp-library.test.cjs`). It gets the same 120-second tool timeout and the same WSL rule as Magpie Web Search.
- Discover's featured list is the same with nothing set up: one of magpie's own whose model or search isn't there yet, or which Settings turned off, carries `unready` (`gateway.OwnUnready`, set by the GUI's `/api/library/market/servers`), shown as a Not set up yet badge on its card and the full reason in its sheet. It can still be added, since it answers once that is set up, and until then its tools answer with the same reason, so no agent is given a tool that fails without a word.
- A carried library (`Collect`) has every file of each skill, its templates and other binaries included, up to `maxCarried` (16 MiB) a file and `maxCarriedAll` (32 MiB) in all, chosen smallest first across the skills (`readSkills`), so every skill's text goes before any big file. The total keeps a sealed backup under the 64 MiB a sync reads: the files are base64 twice in it. What is left out is named in `Left`, and `Put` keeps this computer's copy of such a file in the skill it puts (`keepLeft`). [`carry.go`](../../internal/library/carry.go)
+17
View File
@@ -14,6 +14,8 @@
// folder the agent started it in, for the project its memories are kept
// for, and the client name the agent gave at initialize, for which agent
// it is.
// `magpie mcp sessions` is the sessions' (gateway.SessionsMCPPath): what
// was said in every agent's sessions on this computer.
package browsermcp
import (
@@ -70,6 +72,21 @@ func RunMemory(args []string) error {
return serveMemory(os.Stdin, os.Stdout, gatewayBase(), wd)
}
// RunSessions serves the sessions MCP server on stdin and stdout until
// stdin ends.
func RunSessions(args []string) error {
if len(args) > 0 {
return fmt.Errorf("magpie mcp sessions takes no arguments")
}
return serveSessions(os.Stdin, os.Stdout, gatewayBase())
}
// serveSessions passes each line to the gateway's sessions server. A
// search while the index is first made reads for a few seconds.
func serveSessions(in io.Reader, out io.Writer, base string) error {
return relay(in, &bridge{base: base, path: gateway.SessionsMCPPath, title: "Magpie Sessions", client: &http.Client{Timeout: time.Minute}, out: out})
}
func gatewayBase() string {
base := strings.TrimRight(os.Getenv("MAGPIE_GATEWAY"), "/")
if base == "" {
+3
View File
@@ -420,6 +420,9 @@ func run(args []string) error {
if len(args) > 1 && args[1] == "memory" {
return browsermcp.RunMemory(args[2:])
}
if len(args) > 1 && args[1] == "sessions" {
return browsermcp.RunSessions(args[2:])
}
return imagemcp.Run(args[1:])
case "claude-mcp-helper": // internal: stdio MCP subprocess spawned by Claude Code
return claudebridge.RunMCP(args[1:])
+1
View File
@@ -499,6 +499,7 @@ var notYet = map[string]string{
"GET /api/speeds": U, // sessions_manage.go: the Sessions row's speed curve
"GET /api/sessions/manage": U, // sessions_manage.go
"GET /api/sessions/search": U, // sessions_manage.go
"GET /api/sessions/said": U, // sessions_manage.go: every agent's sessions; agents have the sessions MCP server
"POST /api/sessions/codex-provider": U, // sessions_manage.go
"POST /api/sessions/delete": U, // sessions_manage.go
"POST /api/sessions/purge": U, // sessions_manage.go
+2 -1
View File
@@ -1168,6 +1168,7 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc(SearchMCPPath, s.searchMCP)
mux.HandleFunc(VisionMCPPath, s.visionMCP)
mux.HandleFunc(MemoryMCPPath, s.memoryMCP)
mux.HandleFunc(SessionsMCPPath, s.sessionsMCP)
mux.HandleFunc(ImageMCPPath, s.imageMCP)
mux.HandleFunc(BrowserMCPPath, s.browserMCP)
mux.HandleFunc("GET "+BrowserExtensionPath, s.browserExtension)
@@ -1211,7 +1212,7 @@ var catalogSize stamped[struct{}, int]
func (s *Server) info(w http.ResponseWriter, r *http.Request) {
out := map[string]any{"name": "magpie", "version": Version, "models": catalogSize.get(struct{}{}, func() int { return len(provider.Catalog()) }), "window": Window,
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/decisions", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, MemoryMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/decisions", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, MemoryMCPPath, SessionsMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
// which process serves, for another magpie on this computer to name it
// on its Routing page (#2606); not told to another machine
if local(r) {
+1 -1
View File
@@ -28,7 +28,7 @@ var keySlotFree = []string{
"DELETE " + KeysPath + "/{id}", "POST " + OIDCKeysPath, "POST " + provider.RemoteProvePath,
"POST " + RestartPath, "POST " + provider.RemoteUpdatePath, "POST /v1/messages/count_tokens",
"POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}", SearchMCPPath, VisionMCPPath,
ImageMCPPath, BrowserMCPPath, MemoryMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath, ToolsMCPOne + "{plugin}",
ImageMCPPath, BrowserMCPPath, MemoryMCPPath, SessionsMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath, ToolsMCPOne + "{plugin}",
HubMCPPath + "{agent}", HubMCPAll, "/", "POST " + joinData, AdminPath,
// the chat page's files are kept in magpie, never sent to a model
"POST " + ChatPagePath + "/anthropic/v1/files", "DELETE " + ChatPagePath + "/anthropic/v1/files/{id}",
+4
View File
@@ -51,6 +51,8 @@ func ownMCP() []OwnMCP {
}
// memory is always there: it needs no model
out = append(out, OwnMCP{memoryServerName, "Magpie Memory", MemoryMCPPath})
// and so are the sessions: it reads what Settings › Sessions allows
out = append(out, OwnMCP{sessionsServerName, "Magpie Sessions", SessionsMCPPath})
if gwtool.Served(gwtool.PluginTools) {
// a note that can't be read says nothing: the server is listed,
// and its tools/list tells
@@ -86,6 +88,8 @@ func OwnMCPTools(ctx context.Context) []OwnMCPServer {
s.Tools = []string{GenerateImageTool, GenerateVideoTool, GenerationResultTool}
case memoryServerName:
s.Tools = []string{memorySearchTool, memorySaveTool, memoryForgetTool, memoryContextTool}
case sessionsServerName:
s.Tools = []string{sessionsSearchTool, sessionsReadTool}
case "magpie-tools":
ts, _ := servedTools(ctx)
for _, t := range ts {
+3 -2
View File
@@ -42,11 +42,12 @@ func toolsAre(t *testing.T, n int) {
t.Cleanup(func() { toolsOn = was })
}
// With nothing set up, only memory, which needs no model, is listed.
// With nothing set up, only memory and sessions, which need no model,
// are listed.
func TestOwnMCPNoneWhenNothingIsOn(t *testing.T) {
fresh(t)
toolsAre(t, 0)
if got := ownMCPNames(t, New()); len(got) != 1 || got[memoryServerName] != MemoryMCPPath {
if got := ownMCPNames(t, New()); len(got) != 2 || got[memoryServerName] != MemoryMCPPath || got[sessionsServerName] != SessionsMCPPath {
t.Fatalf("listed %v", got)
}
}
+1 -1
View File
@@ -61,7 +61,7 @@ var readOnlyRefused = []string{
// MCP servers, plugins' and Codex's backends, Gemini, everything else
"POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}",
SearchMCPPath, VisionMCPPath, ImageMCPPath, ImageMCPFiles + "{name}",
BrowserMCPPath, MemoryMCPPath, "GET " + BrowserExtensionPath, "GET " + BrowserStatusPath, ToolsMCPPath, ToolsMCPOne + "{plugin}",
BrowserMCPPath, MemoryMCPPath, SessionsMCPPath, "GET " + BrowserExtensionPath, "GET " + BrowserStatusPath, ToolsMCPPath, ToolsMCPOne + "{plugin}",
HubMCPPath + "{agent}", HubMCPAll, CodexPath + "/", "GET " + CodexCatalogPath,
"GET /v1beta/models", "POST /v1beta/models/{call...}", "/",
}
+1
View File
@@ -41,6 +41,7 @@ var OwnMCPServers = []struct{ Name, Path string }{
{"vision", VisionMCPPath},
{"web-search", SearchMCPPath},
{"memory", MemoryMCPPath},
{"sessions", SessionsMCPPath},
{"tools", ToolsMCPPath},
}
+347
View File
@@ -0,0 +1,347 @@
package gateway
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"unicode"
"github.com/yetone/magpie/internal/sessions"
)
// magpie's sessions (cryingLiu on X) are an MCP server an agent the user
// picks in Library → MCP can mount, so it can find what was said in any
// agent's session on this computer and read it: search_sessions and
// read_session, Streamable HTTP at SessionsMCPPath, served as
// SearchMCPPath is (serveMCP), to the agents on this computer alone, and
// given as `magpie mcp sessions`. It reads only the agents Settings ›
// Sessions lets magpie read (sessions.Reads), as the Sessions page does.
// SessionsMCPPath is where the sessions MCP server is served.
const SessionsMCPPath = "/mcp/magpie/sessions"
const (
sessionsServerName = "magpie-sessions"
sessionsSearchTool = "search_sessions"
sessionsReadTool = "read_session"
)
const (
// sessionsReadChars is how much of a session read_session gives when
// not told, and sessionsReadMost the most it gives
sessionsReadChars = 20_000
sessionsReadMost = 100_000
// sessionsToolChars is what is shown of a tool's call or answer
sessionsToolChars = 400
)
func (s *Server) sessionsMCP(w http.ResponseWriter, r *http.Request) {
// what was said in this computer's agents' sessions: only an agent on
// this computer reads it. Another computer's gateway key and a web
// page, even one Settings lists, are turned away.
if !local(r) || fromBrowser(r) {
http.Error(w, "magpie's sessions MCP server answers the agents on this computer alone", http.StatusForbidden)
return
}
serveMCP(w, r, "magpie's sessions", sessionsServerName, 1<<20, s.sessionsMCPCall)
}
func sessionsMCPTools() []any {
return []any{
map[string]any{
"name": sessionsSearchTool,
"title": "Search sessions",
"description": "Searches what was said (the user's prompts and the agents' replies) in the sessions of every coding agent on this computer: Claude Code, Codex and the others magpie reads. " +
"Use it to find an earlier conversation, a decision or a fix from another session or another agent. Words match by their start; the newest sessions come first. Read one with " + sessionsReadTool + ".",
"inputSchema": map[string]any{
"type": "object",
"properties": map[string]any{
"query": map[string]any{"type": "string", "description": "The words to find, as they were said"},
"agent": map[string]any{"type": "string", "description": "Only this agent's sessions, by magpie's id for it (claude, codex, gemini, opencode, …)"},
"limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 50, "default": 10},
},
"required": []string{"query"},
},
"annotations": map[string]any{"readOnlyHint": true, "openWorldHint": false},
},
map[string]any{
"name": sessionsReadTool,
"title": "Read session",
"description": "Reads a session's conversation as text: the prompts, the replies, and the tools called, shortened. " +
"With find, it starts a few messages before where those words were said; from goes on where the last read ended.",
"inputSchema": map[string]any{
"type": "object",
"properties": map[string]any{
"session": map[string]any{"type": "string", "description": "The session, as " + sessionsSearchTool + " names it (agent:id)"},
"find": map[string]any{"type": "string", "description": "Start a few messages before where these words were said"},
"from": map[string]any{"type": "integer", "minimum": 0, "description": "Start at this message, as a read before says"},
"max_chars": map[string]any{"type": "integer", "minimum": 1000, "maximum": sessionsReadMost, "default": sessionsReadChars},
},
"required": []string{"session"},
},
"annotations": map[string]any{"readOnlyHint": true, "openWorldHint": false},
},
}
}
type sessionsArgs struct {
Query string `json:"query"`
Agent string `json:"agent"`
Limit flexCount `json:"limit"`
Session string `json:"session"`
Find string `json:"find"`
From flexCount `json:"from"`
MaxChars flexCount `json:"max_chars"`
}
func (s *Server) sessionsMCPCall(r *http.Request, m mcpMessage) (any, map[string]any) {
switch m.Method {
case "initialize":
return map[string]any{
"protocolVersion": mcpVersion(m),
"capabilities": map[string]any{"tools": map[string]any{}},
"serverInfo": map[string]any{"name": sessionsServerName, "title": "Magpie Sessions", "version": Version},
"instructions": "What was said in every coding agent's sessions on this computer. Search it for an earlier conversation, decision or fix, in this agent or another, and read the session it is in.",
}, nil
case "ping":
return map[string]any{}, nil
case "tools/list":
return map[string]any{"tools": sessionsMCPTools()}, nil
case "tools/call":
var p struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
if err := json.Unmarshal(m.Params, &p); err != nil {
return nil, map[string]any{"code": -32602, "message": "invalid params: " + err.Error()}
}
var a sessionsArgs
if len(p.Arguments) > 0 {
if err := json.Unmarshal(p.Arguments, &a); err != nil {
return toolResult("the arguments don't read: "+err.Error(), true), nil
}
}
var said string
var err error
switch p.Name {
case sessionsSearchTool:
said, err = sessionsSearch(r, a)
case sessionsReadTool:
said, err = sessionsRead(a)
default:
return nil, map[string]any{"code": -32602, "message": "unknown tool " + p.Name + ": this server has " + sessionsSearchTool + " and " + sessionsReadTool}
}
if err != nil {
return toolResult(err.Error(), true), nil
}
return toolResult(said, false), nil
}
return nil, map[string]any{"code": -32601, "message": "method not found: " + m.Method}
}
// searchSaid is sessions.SearchSaid; a variable for tests.
var searchSaid = sessions.SearchSaid
func sessionsSearch(r *http.Request, a sessionsArgs) (string, error) {
needle := sessions.NeedleOf(a.Query)
if needle == "" {
return "", errors.New("query is empty: say the words to find")
}
limit := min(max(int(a.Limit), 0), 50)
if limit == 0 {
limit = 10
}
found, err := searchSaid(r.Context(), needle, strings.TrimSpace(a.Agent), limit)
if errors.Is(err, sessions.ErrNoWords) {
return "", errors.New("the query has no words to find (letters or digits)")
}
if err != nil {
return "", err
}
var b strings.Builder
still := found.Listing || found.Indexed < found.Total
if len(found.Hits) == 0 && still {
fmt.Fprintf(&b, "No session searched so far says %q.", needle)
} else if len(found.Hits) == 0 {
fmt.Fprintf(&b, "No session says %q.", needle)
} else if len(found.Hits) == 1 {
fmt.Fprintf(&b, "1 session says %q:\n", needle)
} else {
fmt.Fprintf(&b, "%d sessions say %q, the newest first:\n", len(found.Hits), needle)
}
for i, h := range found.Hits {
ss := h.Session
fmt.Fprintf(&b, "\n%d. %s:%s", i+1, ss.Agent, ss.ID)
if t := cutLine(ss.Title, 120); t != "" {
fmt.Fprintf(&b, " · %s", t)
}
b.WriteString("\n ")
if ss.Cwd != "" {
b.WriteString(ss.Cwd + " · ")
}
b.WriteString(ss.Last.Local().Format("2006-01-02 15:04"))
fmt.Fprintf(&b, "\n %s: %s[%s]%s\n", h.Hit.Role, strings.TrimLeft(snipTail(flat(h.Hit.Before), 200), " "), flat(h.Hit.Match), strings.TrimRight(snipHead(flat(h.Hit.After), 300), " "))
}
if found.Cut {
b.WriteString("\nThere may be more: ask for a higher limit, or more words.")
}
if found.Listing {
b.WriteString("\nStill indexing: the sessions to search are still being found; ask again in a minute.")
} else if found.Total > 0 && found.Indexed < found.Total {
fmt.Fprintf(&b, "\nStill indexing: %d of %d sessions searched so far; ask again in a minute for the rest.", found.Indexed, found.Total)
}
if len(found.Hits) > 0 {
b.WriteString("\nRead one with " + sessionsReadTool + "(session, find).")
}
return b.String(), nil
}
func sessionsRead(a sessionsArgs) (string, error) {
agent, id, ok := strings.Cut(strings.TrimSpace(a.Session), ":")
if !ok || agent == "" || id == "" {
return "", errors.New("session is agent:id, as " + sessionsSearchTool + " names it")
}
if !sessions.Reads(agent) {
return "", sessions.ErrNotRead
}
s, found := sessions.Find(agent, id)
if !found {
return "", fmt.Errorf("no session %s", a.Session)
}
var tr sessions.Transcript
var err error
from := max(int(a.From), 0)
if needle := sessions.NeedleOf(a.Find); needle != "" && from == 0 {
tr, err = sessions.TranscriptAt(s, needle)
if err == nil {
from = max(tr.From, sessionsNear(tr, needle)-sessionsLead)
}
} else {
tr, err = sessions.TranscriptOf(s)
}
if err != nil {
return "", err
}
most := int(a.MaxChars)
if most <= 0 {
most = sessionsReadChars
}
most = min(max(most, 1000), sessionsReadMost)
var b strings.Builder
fmt.Fprintf(&b, "%s:%s", s.Agent, s.ID)
if t := cutLine(s.Title, 200); t != "" {
b.WriteString(" · " + t)
}
b.WriteString("\n")
if s.Cwd != "" {
b.WriteString(s.Cwd + " · ")
}
fmt.Fprintf(&b, "%s to %s\n", s.Start.Local().Format("2006-01-02 15:04"), s.Last.Local().Format("2006-01-02 15:04"))
if from > tr.From {
fmt.Fprintf(&b, "(messages before %d left out)\n", from)
} else if tr.From > 0 {
fmt.Fprintf(&b, "(messages before %d left out)\n", tr.From)
}
end := tr.From
for i, p := range tr.Parts {
n := tr.From + i
if n < from {
continue
}
line := sessionsPart(n, p)
if line == "" {
end = n + 1
continue
}
if b.Len()+len(line) > most && end > from {
fmt.Fprintf(&b, "\n(more: %s with from=%d)", sessionsReadTool, n)
return b.String(), nil
}
b.WriteString(line)
end = n + 1
}
if tr.Cut {
fmt.Fprintf(&b, "\n(the rest is longer than is read at once: %s with from=%d)", sessionsReadTool, end)
}
return b.String(), nil
}
// sessionsLead is how many messages before the found one a read with
// find starts.
const sessionsLead = 3
// sessionsNear is the number of the first part that says needle, or 0.
func sessionsNear(tr sessions.Transcript, needle string) int {
for i, p := range tr.Parts {
if (p.Kind == "text" || p.Kind == "context") && strings.Contains(sessions.NeedleOf(p.Text), needle) {
return tr.From + i
}
}
return 0
}
// sessionsPart is one part as read_session shows it.
func sessionsPart(n int, p sessions.Part) string {
text := strings.TrimSpace(p.Text)
switch p.Kind {
case "text", "context":
if text == "" {
return ""
}
return fmt.Sprintf("\n[%d] %s:\n%s\n", n, p.Role, text)
case "thinking":
return ""
case "tool_use":
return fmt.Sprintf("\n[%d] %s called %s: %s\n", n, p.Role, p.Name, cutLine(text, sessionsToolChars))
case "tool_result":
return fmt.Sprintf("[%d] tool answered: %s\n", n, cutLine(text, sessionsToolChars))
case "image":
return fmt.Sprintf("\n[%d] %s: (an image)\n", n, p.Role)
}
return ""
}
// cutLine is text on one line, cut to most runes.
func cutLine(text string, most int) string {
return snipHead(strings.Join(strings.Fields(text), " "), most)
}
// flat is text on one line, each run of white space one space, its ends
// kept: the words round a match stay apart from it.
func flat(text string) string {
var b strings.Builder
space := false
for _, r := range text {
if unicode.IsSpace(r) {
space = true
continue
}
if space {
b.WriteByte(' ')
space = false
}
b.WriteRune(r)
}
if space {
b.WriteByte(' ')
}
return b.String()
}
// snipHead is text's first most runes; snipTail its last.
func snipHead(text string, most int) string {
if r := []rune(text); len(r) > most {
return string(r[:most]) + "…"
}
return text
}
func snipTail(text string, most int) string {
if r := []rune(text); len(r) > most {
return "…" + string(r[len(r)-most:])
}
return text
}
+147
View File
@@ -0,0 +1,147 @@
package gateway
import (
"context"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/sessions"
)
// sessionsCall is one tools/call of the sessions server from this
// computer, and the tool's text and whether it is an error.
func sessionsCall(t *testing.T, h http.Handler, tool, args string) (string, bool) {
t.Helper()
body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"` + tool + `","arguments":` + args + `}}`
m := readMCP(t, mcpPostTo(h, SessionsMCPPath, "127.0.0.1:50000", body))
if m.Error != nil || len(m.Result.Content) != 1 {
t.Fatalf("%s: %+v", tool, m)
}
return m.Result.Content[0].Text, m.Result.IsError
}
// What was said in this computer's sessions is for its own agents alone:
// another computer, even with a key, and a web page are turned away.
func TestSessionsMCPOnlyForAgentsHere(t *testing.T) {
fresh(t)
h := lanGuard(New().Handler())
list := `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`
m := readMCP(t, mcpPostTo(h, SessionsMCPPath, "127.0.0.1:50000", list))
if len(m.Result.Tools) != 2 || m.Result.Tools[0].Name != sessionsSearchTool || m.Result.Tools[1].Name != sessionsReadTool {
t.Fatalf("tools: %+v", m.Result.Tools)
}
for _, c := range []struct {
name, addr string
hdr []string
}{
{"a page", "127.0.0.1:50000", []string{"Origin", "http://127.0.0.1:3425"}},
{"a browser", "127.0.0.1:50000", []string{"User-Agent", "Mozilla/5.0", "Sec-Fetch-Mode", "cors"}},
{"another computer", "192.0.2.7:4000", nil},
} {
w := mcpPostTo(h, SessionsMCPPath, c.addr, list, c.hdr...)
if w.Code == 200 {
t.Errorf("%s was answered: %s", c.name, w.Body)
}
}
}
// search_sessions gives each session found as read_session takes it, the
// words round the match, and passes the agent and limit on.
func TestSessionsMCPSearch(t *testing.T) {
fresh(t)
h := lanGuard(New().Handler())
var asked [3]any
was := searchSaid
searchSaid = func(_ context.Context, needle, agent string, limit int) (sessions.SaidFound, error) {
asked = [3]any{needle, agent, limit}
return sessions.SaidFound{
Hits: []sessions.SaidHit{{
Session: sessions.Session{Agent: "codex", ID: "0190aaaa", Title: "Auth fix", Cwd: "/work/app", Last: time.Now()},
Hit: sessions.Hit{Role: "user", Before: "the ", Match: "Rainbow table", After: " skips the salt"},
}},
Indexed: 3, Total: 5, Cut: true,
}, nil
}
t.Cleanup(func() { searchSaid = was })
text, isErr := sessionsCall(t, h, sessionsSearchTool, `{"query":" Rainbow TABLE ","agent":"codex","limit":"4"}`)
if isErr {
t.Fatal(text)
}
if asked != [3]any{"rainbow table", "codex", 4} {
t.Fatalf("searched %v", asked)
}
for _, want := range []string{"1 session says \"rainbow table\":", "1. codex:0190aaaa · Auth fix", "/work/app · ", "user: the [Rainbow table] skips the salt", "higher limit", "3 of 5 sessions", sessionsReadTool} {
if !strings.Contains(text, want) {
t.Errorf("no %q in\n%s", want, text)
}
}
// the first listing of a long history still running: nothing is
// said to be missing yet
searchSaid = func(context.Context, string, string, int) (sessions.SaidFound, error) {
return sessions.SaidFound{Hits: []sessions.SaidHit{}, Listing: true}, nil
}
if text, _ := sessionsCall(t, h, sessionsSearchTool, `{"query":"rainbow"}`); !strings.Contains(text, "No session searched so far says") || !strings.Contains(text, "still being found") {
t.Fatalf("while listing:\n%s", text)
}
if text, isErr := sessionsCall(t, h, sessionsSearchTool, `{"query":" "}`); !isErr {
t.Fatalf("an empty query: %s", text)
}
}
// read_session with find starts a few messages before the words, says
// what it left out, and goes on with from; an agent Settings doesn't let
// magpie read is not read.
func TestSessionsMCPReadAtTheWords(t *testing.T) {
fresh(t)
home := os.Getenv("HOME")
claude := filepath.Join(home, ".claude")
t.Setenv("CLAUDE_CONFIG_DIR", claude)
sessions.Reset()
t.Cleanup(sessions.Reset)
at := time.Now().Add(-time.Hour).UTC()
stamp := func(i int) string { return at.Add(time.Duration(i) * time.Second).Format(time.RFC3339Nano) }
var lines []string
for i := range 40 {
lines = append(lines, fmt.Sprintf(`{"type":"user","timestamp":%q,"message":{"role":"user","content":"question %d"},"cwd":"/work/app","sessionId":"s1","uuid":"u%d"}`, stamp(2*i), i, i),
fmt.Sprintf(`{"type":"assistant","timestamp":%q,"message":{"role":"assistant","content":[{"type":"text","text":"answer %d %s"}]},"cwd":"/work/app","sessionId":"s1","uuid":"a%d"}`, stamp(2*i+1), i, strings.Repeat("words ", 10), i))
}
lines[50] = fmt.Sprintf(`{"type":"user","timestamp":%q,"message":{"role":"user","content":"where is the Zanzibar key"},"cwd":"/work/app","sessionId":"s1","uuid":"u25"}`, stamp(50))
path := filepath.Join(claude, "projects", "-work-app", "s1.jsonl")
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
t.Fatal(err)
}
h := lanGuard(New().Handler())
text, isErr := sessionsCall(t, h, sessionsReadTool, `{"session":"claude:s1","find":"zanzibar KEY","max_chars":1000}`)
if isErr {
t.Fatal(text)
}
if !strings.Contains(text, "(messages before 47 left out)") || !strings.Contains(text, "[47] assistant:\nanswer 23") || !strings.Contains(text, "[50] user:\nwhere is the Zanzibar key") || strings.Contains(text, "answer 22 ") {
t.Fatalf("read at the words:\n%s", text)
}
if !strings.Contains(text, "(more: "+sessionsReadTool+" with from=") {
t.Fatalf("no way on in\n%s", text)
}
whole, _ := sessionsCall(t, h, sessionsReadTool, `{"session":"claude:s1","from":"78"}`)
if !strings.Contains(whole, "[79] assistant:\nanswer 39") || strings.Contains(whole, "[77]") {
t.Fatalf("from 78:\n%s", whole)
}
if text, isErr := sessionsCall(t, h, sessionsReadTool, `{"session":"s1"}`); !isErr {
t.Fatalf("no agent: %s", text)
}
off := func() bool { return true }
sessions.OwnOff.Store(&off)
t.Cleanup(func() { sessions.OwnOff.Store(nil) })
if text, isErr := sessionsCall(t, h, sessionsReadTool, `{"session":"claude:s1"}`); !isErr || strings.Contains(text, "answer") {
t.Fatalf("read with no agent's files read: %s", text)
}
}
@@ -8731,6 +8731,8 @@ magpie.plugin("library", (ctx) => {
go.onclick = async (e) => { if (await closeLibModal()) openSettingsAt(e, "models", "#searchList .row"); };
hint.append(" ", go);
ed.append(hint);
} else if (x.name === "magpie-sessions") {
ed.append(el("p", "mk-hint", t("Pick the agents that may search and read what was said in your other sessions.")));
} else if (x.name === "magpie-vision") {
ed.append(el("p", "mk-hint", t("Pick the agents that may read images with it: each image goes to the Image recognition model set in Settings → Models → Images, and costs what that model charges.")));
} else if (x.optIn) ed.append(el("p", "mk-hint", t("Pick the agents that may generate images: each image costs what the model set in Settings → Models → Images charges.")));
@@ -2,6 +2,7 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"Pick the agents that may search and read what was said in your other sessions.": "选择可以搜索、阅读你其他会话内容的 Agent。",
"Update by themselves": "自动更新",
"Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "GitHub 和 git 上的技能有改动时自动重新获取。你在这里改过的技能保持不变。",
"Skills update by themselves now": "技能现在会自动更新",
@@ -1077,6 +1078,7 @@ magpie.strings({
"{name} read again from its source": "已重新从来源读取 {name}",
},
"zh-TW": {
"Pick the agents that may search and read what was said in your other sessions.": "選擇可以搜尋、閱讀你其他會話內容的 Agent。",
"Update by themselves": "自動更新",
"Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "GitHub 和 git 上的技能有變動時自動重新取得。你在這裡改過的技能保持不變。",
"Skills update by themselves now": "技能現在會自動更新",
@@ -2152,6 +2154,7 @@ magpie.strings({
"{name} read again from its source": "已重新從來源讀取 {name}",
},
ja: {
"Pick the agents that may search and read what was said in your other sessions.": "ほかのセッションで話した内容を検索して読める Agent を選びます。",
"Update by themselves": "自動で更新",
"Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "GitHub や git でスキルが変わったら自動で取得し直します。ここで変更したスキルはそのままです。",
"Skills update by themselves now": "スキルは自動で更新されるようになりました",
@@ -3227,6 +3230,7 @@ magpie.strings({
"{name} read again from its source": "{name} をソースから読み直しました",
},
de: {
"Pick the agents that may search and read what was said in your other sessions.": "Wähle die Agents, die durchsuchen und lesen dürfen, was in deinen anderen Sitzungen gesagt wurde.",
"Update by themselves": "Selbst aktualisieren",
"Fetch skills from GitHub and git again when they change there. One you changed here stays as it is.": "Skills von GitHub und git neu laden, wenn sie sich dort ändern. Ein hier geänderter Skill bleibt, wie er ist.",
"Skills update by themselves now": "Skills aktualisieren sich jetzt selbst",
+139 -12
View File
@@ -29,6 +29,13 @@ magpie.plugin("sessions", (ctx) => {
let found = null; // { agent, needle, hits: Map(id -> hit), busy, cut, unread, searched, total, error }
let searchCtl = null;
let searchT = 0;
// elsewhere is the same words in every other agent's sessions, from
// magpie's index of what was said (cryingLiu on X): { needle, hits,
// indexed, total, busy }, read again while the index is still being made
let elsewhere = null;
let elseCtl = null;
let elseT = 0;
const ELSE_MORE = 20;
const SEARCH_WAIT = 300;
const needleOf = (q) => q.trim().split(/\s+/).filter(Boolean).join(" ").toLowerCase();
let trashOn = false;
@@ -250,8 +257,10 @@ magpie.plugin("sessions", (ctx) => {
searchCtl?.abort();
searchCtl = null;
found = null;
elseSoon("");
return;
}
elseSoon(needle);
if (found && found.agent === data.agent && found.needle === needle && !found.busy && !found.error) return;
searchCtl?.abort();
searchCtl = null;
@@ -271,6 +280,77 @@ magpie.plugin("sessions", (ctx) => {
}, SEARCH_WAIT);
}
// elseSoon searches every agent's sessions for needle (none in gateway
// mode, where no agent's files here are read), once typing pauses, and
// again a few seconds on while magpie's index has sessions to read yet
function elseSoon(needle, again = 0) {
clearTimeout(elseT);
if (!needle || data?.reads?.gateway) {
elseCtl?.abort();
elseCtl = null;
elsewhere = null;
return;
}
if (!again && elsewhere?.needle === needle && !elsewhere.error) return;
elseCtl?.abort();
elseCtl = null;
const mine = elsewhere = again ? elsewhere : { needle, hits: [], busy: true };
elseT = setTimeout(async () => {
const ctl = elseCtl = new AbortController();
try {
const r = await api(`sessions/said?q=${encodeURIComponent(needle)}&limit=${ELSE_MORE + 10}`, undefined, undefined, ctl.signal);
if (elsewhere !== mine) return;
elsewhere = { needle, busy: false, hits: r?.hits || [], indexed: r?.indexed || 0, total: r?.total || 0, listing: !!r?.listing };
if ((elsewhere.listing || elsewhere.indexed < elsewhere.total) && again < 40) {
const now = elsewhere;
elseT = setTimeout(() => { if (elsewhere === now) { elsewhere = { ...now }; elseSoon(needle, again + 1); } }, 3000);
}
} catch (e) {
if (ctl.signal.aborted || elsewhere !== mine) return;
elsewhere = { needle, busy: false, hits: [], error: e.message };
}
if (elseCtl === ctl) elseCtl = null;
if (view === "sessions" && !trashOn) redrawList();
}, again ? 0 : SEARCH_WAIT);
}
// the hits elsewhere shown with the agent shown: those of other agents
const elseHits = () => elsewhere && elsewhere.needle === needleOf(query) && data ? elsewhere.hits.filter((h) => h.agent !== data.agent).slice(0, ELSE_MORE) : [];
// elseBox is the sessions of other agents that said what was searched
// for; a click shows the conversation at the words
function elseBox() {
const f = elsewhere && elsewhere.needle === needleOf(query) ? elsewhere : null;
const hits = elseHits();
const still = f && !f.busy && (f.listing || f.indexed < f.total);
if (!f || (!hits.length && !still)) return null;
const box = el("div", "list sm-else");
const h = el("div", "row sm-else-head");
h.append(el("span", "name", t("Other agents")));
if (still) h.append(el("span", "note", f.listing ? t("Indexing sessions…") : t("Indexing {n} of {total} sessions…", { n: f.indexed, total: f.total })));
box.append(h);
for (const x of hits) {
const r = el("button", "row sess sm-else-row");
r.type = "button";
r.dataset.agent = x.agent;
r.dataset.id = x.id;
r.setAttribute("aria-haspopup", "dialog");
const a = agentOf(x.agent);
const who = el("span", "who");
const s = { agent: x.agent, id: x.id, title: x.title || x.id };
who.append(el("span", "name", x.title || t("(no prompt)")),
el("span", "sub", [a.name, x.last ? ago(x.last) : "", x.wsl ? "WSL " + x.wsl : "", x.cwd || ""].filter(Boolean).join(" · ")),
hitLine(x.hit));
r.append(icon(a.icon), who);
r.onclick = (e) => {
e.stopPropagation();
if (window.getSelection()?.toString()) return;
talkSheet(s, null, f.needle);
};
box.append(r);
}
return box;
}
// what the search is doing, above the list, when it says more than the
// rows do
function searchNote() {
@@ -287,11 +367,21 @@ magpie.plugin("sessions", (ctx) => {
return p;
}
// the words round where a session said what was searched for
function hitLine(h) {
const d = el("div", "sub sm-hit");
// the words round where a session said what was searched for; given
// its session, a click shows the conversation there
function hitLine(h, s) {
const d = el(s ? "button" : "div", "sub sm-hit");
d.append(h.before || "", el("mark", "", h.match), h.after || "");
d.title = (h.before || "") + h.match + (h.after || "");
if (s) {
d.type = "button";
d.setAttribute("aria-haspopup", "dialog");
d.onclick = (e) => {
e.stopPropagation();
if (window.getSelection()?.toString()) return;
talkSheet(s, null, needleOf(query));
};
}
return d;
}
@@ -815,8 +905,10 @@ magpie.plugin("sessions", (ctx) => {
folderBoxes.clear();
const note = searchNote();
if (note) tree.append(note);
const others = elseBox();
if (!list.length) {
if (!search()?.busy) tree.append(el("div", "empty-state", query ? t("No session matches.") : t("No sessions yet")));
if (others) tree.append(others);
return;
}
const q = query.trim();
@@ -834,6 +926,7 @@ magpie.plugin("sessions", (ctx) => {
tree.append(box);
}
if (rest.length) tree.append(othersBox(rest, q));
if (others) tree.append(others);
toFocus();
}
@@ -1090,7 +1183,7 @@ magpie.plugin("sessions", (ctx) => {
// nothing of it otherwise (the group of them is one)
if (zcodeDraft(s)) r.title = s.cwd;
const hit = hitOf(s);
if (hit) who.append(hitLine(hit));
if (hit) who.append(hitLine(hit, s.transcript ? s : null));
// what it spent, as the Usage page's list shows it
r.append(who, ...sessSpent(s));
r.append(speedCell(s));
@@ -1381,8 +1474,8 @@ magpie.plugin("sessions", (ctx) => {
// drawTalk fills box with what was said in a session, read from the
// agent's own file when it is first shown (only read, never written)
function drawTalk(box, s, sub = "") {
const k = s.agent + "/" + s.id + (sub ? "/" + sub : "");
function drawTalk(box, s, sub = "", find = "") {
const k = s.agent + "/" + s.id + (sub ? "/" + sub : "") + (find ? "?" + find : "");
const got = talks.get(k);
if (!got) {
box.replaceChildren(el("p", "cx-none", t("Reading…")));
@@ -1394,10 +1487,10 @@ magpie.plugin("sessions", (ctx) => {
talks.set(k, value);
if (!talkOpen.has(k)) return;
for (const currentBox of document.querySelectorAll(".sess-talk")) {
if (currentBox.dataset.talk === k) drawTalk(currentBox, s, sub);
if (currentBox.dataset.talk === k) drawTalk(currentBox, s, sub, find);
}
};
api("sessions/transcript?agent=" + encodeURIComponent(s.agent) + "&id=" + encodeURIComponent(s.id) + (sub ? "&sub=" + encodeURIComponent(sub) : ""))
api("sessions/transcript?agent=" + encodeURIComponent(s.agent) + "&id=" + encodeURIComponent(s.id) + (sub ? "&sub=" + encodeURIComponent(sub) : "") + (find ? "&find=" + encodeURIComponent(find) : ""))
.then((tr) => finish({ tr }), (err) => finish({ err: err.message }));
return;
}
@@ -1405,11 +1498,13 @@ magpie.plugin("sessions", (ctx) => {
if (got.err) { box.replaceChildren(el("p", "cx-none", got.err)); talks.delete(k); return; }
const parts = got.tr?.parts || [];
const out = [];
// read from where the words were said, the start left out
if (got.tr?.from > 0) out.push(el("p", "cx-none sess-from", t(got.tr.from === 1 ? "{n} earlier message not shown" : "{n} earlier messages not shown", { n: got.tr.from })));
if (!parts.length) out.push(el("p", "cx-none", t(got.tr?.source === "gateway" ? "No saved gateway content for this session" : "Nothing was said here")));
// each reply names its model once, at its first part, and again
// only where the model changes inside it (#2253): the model its own
// line in the agent's file names, so none where the file names none
let said = "", fresh = true;
let said = "", fresh = true, foundOne = false;
for (const p of parts) {
let model = "";
if (p.role === "assistant") {
@@ -1419,6 +1514,7 @@ magpie.plugin("sessions", (ctx) => {
} else if (p.role === "user") fresh = true;
const said1 = ledSaid(p, model);
if (p.role === "user" && (!p.kind || p.kind === "text")) said1.dataset.turn = "1";
if (find && !foundOne && (!p.kind || p.kind === "text" || p.kind === "context") && needleOf(p.text || "").includes(find)) { said1.classList.add("sess-found"); foundOne = true; }
out.push(said1);
}
if (got.tr?.cut) out.push(el("p", "cx-none", t("There was more than is shown here")));
@@ -1433,9 +1529,10 @@ magpie.plugin("sessions", (ctx) => {
// long to get around). A turn is what the user said; the sheet scrolls
// to it, with no animation, as a key pressed many times would.
const NAV = { top: "M4 3.5h8M8 13V6.5M5 9 8 6l3 3", prev: "M4.5 10 8 6.5l3.5 3.5", next: "M4.5 6 8 9.5 11.5 6", bottom: "M4 12.5h8M8 3v6.5M5 7 8 10l3-3" };
function talkSheet(s, sa) {
const k = s.agent + "/" + s.id + (sa ? "/" + sa.id : "");
function talkSheet(s, sa, find = "") {
const k = s.agent + "/" + s.id + (sa ? "/" + sa.id : "") + (find ? "?" + find : "");
talkOpen.add(k);
if (globalThis.CSS?.highlights) CSS.highlights.delete("sess-found");
const ed = el("div", "editor sess-sheet wide");
const head = el("div", "ehead");
const nav = (name, label) => {
@@ -1485,12 +1582,42 @@ magpie.plugin("sessions", (ctx) => {
let queued = 0;
body.addEventListener("scroll", () => { if (!queued) queued = requestAnimationFrame(() => { queued = 0; sync(); }); });
box.addEventListener("talkdrawn", sync);
box.again = () => drawTalk(box, s, sa ? sa.id : "");
// opened at a search's words: the sheet starts at the message that
// said them, once, as it is first drawn
let toFound = !!find;
box.addEventListener("talkdrawn", () => {
const at1 = toFound && box.querySelector(".sess-found");
if (!at1) return;
toFound = false;
markFound(at1, find);
go(Math.max(0, at(at1) - SLACK));
});
box.again = () => drawTalk(box, s, sa ? sa.id : "", find);
box.again();
sync();
body.focus({ preventScroll: true });
}
// markFound marks the words searched for in the message n where the
// browser can (CSS Custom Highlight API), never changing what is drawn
function markFound(n, find) {
if (typeof Highlight === "undefined" || !CSS.highlights) return;
const words = find.split(" ").filter(Boolean);
const ranges = [];
const walk = document.createTreeWalker(n, NodeFilter.SHOW_TEXT);
for (let tn = walk.nextNode(); tn && ranges.length < 50; tn = walk.nextNode()) {
const low = tn.data.toLowerCase();
for (const w of words) {
for (let i = low.indexOf(w); i >= 0 && ranges.length < 50; i = low.indexOf(w, i + w.length)) {
const r = new Range();
try { r.setStart(tn, i); r.setEnd(tn, i + w.length); } catch { continue; }
ranges.push(r);
}
}
}
if (ranges.length) CSS.highlights.set("sess-found", new Highlight(...ranges));
}
function askRelocate(from, wsl) {
const ed = el("div", "editor sm-ask");
const h = el("div", "ehead");
@@ -96,6 +96,11 @@ magpie.strings({
"Erased for good": "已彻底删除",
"{n} sessions erased for good": "已彻底删除 {n} 个会话",
"Searching what was said…": "正在搜索对话内容…",
"Other agents": "其他智能体",
"Indexing {n} of {total} sessions…": "已索引 {n}/{total} 个会话…",
"Indexing sessions…": "正在索引会话…",
"{n} earlier message not shown": "前面 {n} 条消息未显示",
"{n} earlier messages not shown": "前面 {n} 条消息未显示",
"Couldn't search what was said: {error}": "无法搜索对话内容:{error}",
"{agent}'s own files of its sessions can't be read here, so only what magpie recorded through the gateway is searched.": "这里读不到 {agent} 自己的会话文件,只搜索 magpie 通过网关记录的内容。",
"Searched what was said in the latest {n} of {total} sessions.": "已搜索最近 {n} 个会话的对话内容(共 {total} 个)。",
@@ -195,6 +200,11 @@ magpie.strings({
"Erased for good": "已徹底刪除",
"{n} sessions erased for good": "已徹底刪除 {n} 個會話",
"Searching what was said…": "正在搜尋對話內容…",
"Other agents": "其他智慧體",
"Indexing {n} of {total} sessions…": "已索引 {n}/{total} 個會話…",
"Indexing sessions…": "正在索引會話…",
"{n} earlier message not shown": "前面 {n} 則訊息未顯示",
"{n} earlier messages not shown": "前面 {n} 則訊息未顯示",
"Couldn't search what was said: {error}": "無法搜尋對話內容:{error}",
"{agent}'s own files of its sessions can't be read here, so only what magpie recorded through the gateway is searched.": "這裡讀不到 {agent} 自己的會話檔案,只搜尋 magpie 透過閘道記錄的內容。",
"Searched what was said in the latest {n} of {total} sessions.": "已搜尋最近 {n} 個會話的對話內容(共 {total} 個)。",
@@ -294,6 +304,11 @@ magpie.strings({
"Erased for good": "完全に削除しました",
"{n} sessions erased for good": "{n} 件のセッションを完全に削除しました",
"Searching what was said…": "会話の内容を検索中…",
"Other agents": "ほかのエージェント",
"Indexing {n} of {total} sessions…": "{total} 件中 {n} 件のセッションを索引済み…",
"Indexing sessions…": "セッションを索引中…",
"{n} earlier message not shown": "それ以前の {n} 件のメッセージは表示していません",
"{n} earlier messages not shown": "それ以前の {n} 件のメッセージは表示していません",
"Couldn't search what was said: {error}": "会話の内容を検索できませんでした:{error}",
"{agent}'s own files of its sessions can't be read here, so only what magpie recorded through the gateway is searched.": "{agent} 自身のセッションファイルはここでは読めないため、magpie がゲートウェイ経由で記録した内容だけを検索します。",
"Searched what was said in the latest {n} of {total} sessions.": "最新 {n} 件の会話の内容を検索しました(全 {total} 件)。",
@@ -393,6 +408,11 @@ magpie.strings({
"Erased for good": "Endgültig gelöscht",
"{n} sessions erased for good": "{n} Sitzungen endgültig gelöscht",
"Searching what was said…": "Gesprächsinhalte werden durchsucht …",
"Other agents": "Andere Agents",
"Indexing {n} of {total} sessions…": "{n} von {total} Sitzungen indexiert …",
"Indexing sessions…": "Sitzungen werden indexiert …",
"{n} earlier message not shown": "{n} frühere Nachricht nicht angezeigt",
"{n} earlier messages not shown": "{n} frühere Nachrichten nicht angezeigt",
"Couldn't search what was said: {error}": "Gesprächsinhalte konnten nicht durchsucht werden: {error}",
"{agent}'s own files of its sessions can't be read here, so only what magpie recorded through the gateway is searched.": "Die eigenen Sitzungsdateien von {agent} sind hier nicht lesbar, daher wird nur durchsucht, was magpie über das Gateway aufgezeichnet hat.",
"Searched what was said in the latest {n} of {total} sessions.": "Gesprächsinhalte der neuesten {n} von {total} Sitzungen durchsucht.",
@@ -25,6 +25,22 @@
/* where a session said what was searched for, the words themselves marked */
.row .sub.sm-hit { color: var(--fg-2); }
.sm-hit mark { background: var(--accent-soft); color: var(--fg); border-radius: 3px; padding: 0 1px; font-weight: 500; }
/* a hit's words open the conversation at them */
button.sub.sm-hit { display: block; width: 100%; height: auto; margin: 1px 0 0; padding: 0; border: 0; background: none; font: inherit; font-size: 11.5px; line-height: inherit; text-align: left; cursor: pointer; border-radius: 0; }
@media (hover: hover) and (pointer: fine) { button.sub.sm-hit:hover { color: var(--fg); background: none; } }
/* the same words in other agents' sessions, after the agent's own */
.sm-else-head { min-height: 32px; gap: 8px; }
.sm-else-head .name { flex: 1; font-size: 12px; font-weight: 500; color: var(--faint); }
.sm-else-head .note { flex: none; font-size: 11px; color: var(--faint); font-variant-numeric: tabular-nums; }
.sm-else > .row + .row { border-top: 1px solid var(--line-2); }
button.row.sm-else-row { width: 100%; gap: 10px; text-align: left; cursor: pointer; font: inherit; color: inherit; }
.sm-else-row > svg, .sm-else-row > img { flex: none; width: 16px; height: 16px; }
.sm-else-row .who { display: flex; flex-direction: column; min-width: 0; }
.sm-else-row .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* the message a search opened the conversation at, and its words */
.sess-talk .sess-found { border-radius: 8px; box-shadow: 0 0 0 1px var(--accent-soft); }
::highlight(sess-found) { background: var(--accent-soft); color: var(--fg); }
.sess-from { margin-bottom: 8px; }
.sm-bar { gap: 8px; padding: 0 11px; }
.sm-bar .grow { flex: 1; }
.sm-bar .sm-delete, .sm-bar .sm-empty { display: inline-flex; align-items: center; gap: 5px; }
+5
View File
@@ -336,7 +336,12 @@ func sessionRoutes(mux *http.ServeMux, w Windows) {
}
// sub: one of its subagents, found among those the session lists
// (#2261)
// find: the words a search found in it, so that the part they
// are in is among those read (a long session's is cut)
read := sessions.TranscriptOf
if find := sessions.NeedleOf(q.Get("find")); find != "" {
read = func(s sessions.Session) (sessions.Transcript, error) { return sessions.TranscriptAt(s, find) }
}
if sub := q.Get("sub"); sub != "" {
read = func(s sessions.Session) (sessions.Transcript, error) { return sessions.SubagentTranscript(s, sub) }
}
@@ -111,6 +111,14 @@ func TestGatewayModeListsNoOwnSessions(t *testing.T) {
if b := ok("GET", "/api/sessions/transcript?agent=claude&id="+local, ""); !strings.Contains(b, "secret plan") {
t.Fatalf("gateway mode off: the local transcript: %s", b)
}
// every agent's sessions searched at once, and one read where the
// words were said
if b := ok("GET", "/api/sessions/said?q=secret+plan", ""); !strings.Contains(b, `"id":"`+local+`"`) || !strings.Contains(b, `"agent":"claude"`) {
t.Fatalf("gateway mode off: every agent's search: %s", b)
}
if b := ok("GET", "/api/sessions/transcript?agent=claude&id="+local+"&find=secret+plan", ""); !strings.Contains(b, "secret plan") {
t.Fatalf("gateway mode off: the transcript at the words: %s", b)
}
if b := ok("GET", "/api/sessions/stats?days=0", ""); !strings.Contains(b, `"claude"`) {
t.Fatalf("gateway mode off: stats leave out Claude Code: %s", b)
}
@@ -185,6 +193,7 @@ func TestGatewayModeListsNoOwnSessions(t *testing.T) {
t.Fatalf("gateway mode: the gateway's Markdown: %s", b)
}
ownLeft("search", ok("GET", "/api/sessions/search?agent=claude&q=secret", ""))
ownLeft("every agent's search", ok("GET", "/api/sessions/said?q=secret", ""))
if b := ok("GET", "/api/sessions/search?agent=pi&q=remotely", ""); !strings.Contains(b, remote) {
t.Fatalf("gateway mode: search leaves out the gateway's session: %s", b)
}
+44
View File
@@ -10,6 +10,7 @@ import (
"runtime"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
@@ -286,6 +287,19 @@ func sessionManageRoutes(mux *http.ServeMux, w Windows) {
q := r.URL.Query()
writeJSON(rw, searchSessions(r.Context(), q.Get("agent"), q.Get("q"), searchBudget))
})
// said is the sessions of every agent (or ?agent='s) whose
// conversation says ?q=, from the index of what was said in them
// (sessions.SearchSaid): the Sessions page's hits in other agents.
mux.HandleFunc("GET /api/sessions/said", func(rw http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
limit, _ := strconv.Atoi(q.Get("limit"))
found, err := sessions.SearchSaid(r.Context(), sessions.NeedleOf(q.Get("q")), q.Get("agent"), min(max(limit, 1), 100))
if err != nil && !errors.Is(err, sessions.ErrNoWords) {
fail(rw, err)
return
}
writeJSON(rw, saidJSONOf(found))
})
// delete moves the sessions named to magpie's trash, one by one; one
// still being written is left, and said so. One seen only through the
// gateway, of any agent, has what magpie keeps of it moved there.
@@ -575,3 +589,33 @@ func searchSessions(ctx context.Context, agentID, query string, budget time.Dura
}
return out
}
// saidJSON is what the page shows of a search over every agent
// (sessions.SearchSaid): of each session, what its row says.
type saidJSON struct {
Hits []saidHitJSON `json:"hits"`
Indexed int `json:"indexed"`
Total int `json:"total"`
Cut bool `json:"cut,omitempty"`
Listing bool `json:"listing,omitempty"`
}
type saidHitJSON struct {
Agent string `json:"agent"`
ID string `json:"id"`
Title string `json:"title,omitempty"`
Cwd string `json:"cwd,omitempty"`
Last time.Time `json:"last"`
WSL string `json:"wsl,omitempty"`
Transcript bool `json:"transcript"`
Hit sessions.Hit `json:"hit"`
}
func saidJSONOf(f sessions.SaidFound) saidJSON {
out := saidJSON{Hits: make([]saidHitJSON, 0, len(f.Hits)), Indexed: f.Indexed, Total: f.Total, Cut: f.Cut, Listing: f.Listing}
for _, h := range f.Hits {
s := h.Session
out.Hits = append(out.Hits, saidHitJSON{Agent: s.Agent, ID: s.ID, Title: s.Title, Cwd: s.Cwd, Last: s.Last, WSL: s.WSL, Transcript: true, Hit: h.Hit})
}
return out
}
@@ -0,0 +1,96 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Magpie Sessions in the Library's Discover (cryingLiu on X): an MCP server
// that searches and reads what was said in every agent's sessions on this
// computer. What was said is the user's own, so it is opt in: its sheet
// says what the agents picked may do and ticks none until they are picked,
// and the image servers' cost hint is not shown for it. Every language,
// Chromium and WebKit, at 1100 and 420 wide, nothing running off to the
// side; no backend, the API is faked here.
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 { strings } = require("./strings.cjs");
const assets = path.resolve(__dirname, "../assets");
const { I18N } = strings();
const LANGS = ["en", "zh", "zh-TW", "ja", "de"];
const tr = (lang, s) => (lang === "en" ? s : I18N[lang]?.[s] ?? s);
const HOME = "/Users/tester";
const ABOUT = "Search and read what was said in every agent's sessions on this computer: an earlier conversation, decision or fix, from Claude Code, Codex or any agent Magpie reads.";
const HINT = "Pick the agents that may search and read what was said in your other sessions.";
const IMAGES = "Pick the agents that may generate images: each image costs what the model set in Settings → Models → Images charges.";
function route(lang) {
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:${JSON.stringify(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/library") {
return json({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [
{ id: "claude", name: "Claude Code", icon: "claudecode-color", mcp: `${HOME}/.claude.json`, skills: `${HOME}/.claude/skills` },
{ id: "codex", name: "Codex", icon: "codex", mcp: `${HOME}/.codex/config.toml`, skills: `${HOME}/.codex/skills` },
],
instructions: { agents: [], sets: [] }, servers: [], foundServers: [], projects: [], foundSkills: [], skills: [], problems: [],
});
}
if (url.pathname === "/api/library/market/servers") {
return json({ items: [
{ id: "magpie-sessions", name: "magpie-sessions", title: "Magpie Sessions", publisher: "Magpie", description: ABOUT, transport: "stdio", runs: "magpie", featured: true, optIn: true, have: "" },
{ id: "fetch", name: "fetch", title: "Fetch", description: "Read the web.", transport: "stdio", runs: "uvx", featured: true, have: "" },
] });
}
if (url.pathname === "/api/library/market/skills") return json({ items: [] });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } });
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)];
const body = await fs.readFile(file).catch(() => null);
await (body ? route.fulfill({ body, contentType }) : route.fulfill({ status: 404, body: "" }));
};
}
const wide = (page) => page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": Magpie Sessions' sheet is opt in and says what it gives", async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const lang of LANGS) {
for (const width of [1100, 420]) {
await t.test(`${lang} at ${width}px`, async () => {
const context = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", route(lang));
await page.addInitScript(() => { localStorage.setItem("magpie.libTab", "mcp"); });
await page.goto("http://magpie.test/?view=library");
await page.locator('#view-library .mk[data-market="mcp"] .mk-card[data-id="magpie-sessions"]').click();
const sheet = page.locator("#modal .mk-sheet");
await sheet.waitFor();
assert.equal((await sheet.locator(".mk-name.big").textContent()).trim(), "Magpie Sessions");
const hints = await sheet.locator(".mk-hint").allTextContents();
assert(hints.map((h) => h.trim()).includes(tr(lang, HINT)), hints.join(" | "));
assert(!hints.some((h) => h.includes(tr(lang, IMAGES))), "not the image servers' hint");
// opt in: no agent is ticked until it is picked
assert.equal(await sheet.locator(".lib-ag").count() >= 2, true, "the agents to pick from");
assert.equal(await sheet.locator(".lib-ag.on").count(), 0, "no agent ticked");
assert.equal(await wide(page), 0);
if (lang !== "en") assert.ok(I18N[lang]?.[HINT], `${lang} has the hint`);
assert.deepEqual(errors, []);
await context.close();
});
}
}
});
}
+187
View File
@@ -0,0 +1,187 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The Sessions page's search also finds what was said in other agents'
// sessions (cryingLiu on X): under the list, the sessions of other agents
// whose conversation says the words, from magpie's index of them
// (/api/sessions/said), asked again while the sessions are still being
// listed and while the index is still reading. A hit,
// there or in the agent's own list, opens the conversation in the sheet at
// the message that said it (transcript&find=), its start left out and said
// so; the page itself never scrolls. In gateway mode, where no agent's own
// files are read, nothing is asked. Chromium and WebKit, every language,
// wide and narrow.
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();
// a long conversation whose 31st message says the words
const PARTS = [];
for (let i = 0; i < 40; i++) {
PARTS.push(i === 30
? { role: "user", kind: "text", text: "where is the Zanzibar key kept" }
: { role: i % 2 ? "assistant" : "user", kind: "text", text: Array.from({ length: 4 }, (_, j) => `message ${i} line ${j}`).join("\n") });
}
function serve(lang, log, gateway) {
const sessions = [
{ agent: "pi", id: "p-1", cwd: "/work/pi", title: "Rename foo", start: at(10), last: at(5), models: [], size: 4096, messages: 6, deletable: true, transcript: true },
{ agent: "pi", id: "p-2", cwd: "/work/pi", title: "Write tests", start: at(30), last: at(20), models: [], size: 4096, messages: 6, deletable: true, transcript: true },
];
const agents = [
{ agent: "pi", count: 2, deletable: true, name: "Pi", icon: "pi" },
{ agent: "claude", count: 1, deletable: true, name: "Claude Code", icon: "claude" },
];
const reads = { asked: true, all: true, found: [], gateway };
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:${JSON.stringify(lang)},theme:"light",web:false};` });
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/reads") return json(reads);
if (url.pathname === "/api/sessions/manage") return json({ agents, agent: "pi", sessions, terminal: false, trash: [], trashDir: "~/trash", reads });
if (url.pathname === "/api/sessions/search") {
const q = url.searchParams.get("q");
const hits = q === "zanzibar" ? [{ id: "p-1", role: "user", kind: "text", before: "where is the ", match: "Zanzibar", after: " key kept" }] : [];
return json({ hits, searched: 2, total: 2 });
}
if (url.pathname === "/api/sessions/said") {
const q = url.searchParams.get("q");
log.said.push(q);
const hit = { role: "user", kind: "text", before: "where is the ", match: "Zanzibar", after: " key kept" };
const hits = q === "zanzibar" ? [
{ agent: "pi", id: "p-1", title: "Rename foo", last: at(5), transcript: true, hit },
{ agent: "claude", id: "c-1", title: "Keys in the vault", cwd: "/work/vault", last: at(60), transcript: true, hit },
] : [];
// the first answer while the sessions are still being listed, the
// next while the index reads them, then all read
if (log.said.length === 1) return json({ hits: [], indexed: 0, total: 0, listing: true });
return json({ hits, indexed: log.said.length === 2 ? 3 : 5, total: 5 });
}
if (url.pathname === "/api/sessions/transcript") {
log.read.push(Object.fromEntries(url.searchParams));
const find = url.searchParams.get("find");
return json(find ? { parts: PARTS.slice(24), from: 24 } : { parts: PARTS });
}
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).catch(() => ""), contentType });
};
}
const KEYS = ["Other agents", "Indexing sessions…", "Indexing {n} of {total} sessions…", "{n} earlier message not shown", "{n} earlier messages not shown"];
const nav = { en: "Sessions", zh: "会话", "zh-TW": "會話", ja: "セッション", de: "Sitzungen" };
async function open(browser, lang, width, gateway = false) {
const context = await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" });
const page = await context.newPage();
page.setDefaultTimeout(6000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const log = { said: [], read: [] };
await page.route("**/*", serve(lang, log, gateway));
await page.goto("http://magpie.test/?view=providers");
await page.locator("#nav").getByRole("button", { name: nav[lang], exact: true }).click();
const view = page.locator("#view-sessions");
await view.locator('.row.sm-sess[data-id="p-1"]').waitFor();
return { context, page, view, log, errors, tr: (k, v) => page.evaluate(([k, v]) => t(k, v), [k, v]) };
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: search finds other agents' sessions and opens at the words`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
for (const [lang, width] of [["en", 1100], ["zh", 1100], ["zh-TW", 560], ["ja", 560], ["de", 420]]) {
await t.test(`${lang} at ${width}`, async () => {
const { context, page, view, log, errors, tr } = await open(browser, lang, width);
const filter = view.locator(".sm-filter");
await filter.pressSequentially("zanzibar", { delay: 15 });
// under the list, the other agents' sessions that said it, the
// current agent's own left to its list; the index still reading
const box = view.locator(".list.sm-else");
await box.waitFor();
await box.locator(".sm-else-head .note").filter({ hasText: await tr("Indexing sessions…") }).waitFor();
assert.equal(await box.locator(".sm-else-head .name").textContent(), await tr("Other agents"));
await box.locator(".sm-else-head .note").filter({ hasText: await tr("Indexing {n} of {total} sessions…", { n: 3, total: 5 }) }).waitFor();
const rows = box.locator(".sm-else-row");
assert.deepEqual(await rows.evaluateAll((l) => l.map((r) => r.dataset.agent + ":" + r.dataset.id)), ["claude:c-1"]);
assert.equal(await rows.first().locator(".sm-hit mark").textContent(), "Zanzibar");
assert.match(await rows.first().locator(".sub").first().textContent(), /Claude Code · .*\/work\/vault/);
// asked again while it reads; then nothing more to say
await box.locator(".sm-else-head .note").waitFor({ state: "detached", timeout: 8000 });
assert.deepEqual(log.said, ["zanzibar", "zanzibar", "zanzibar"]);
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "no page overflow");
const fit = await rows.first().evaluate((r) => ({ right: r.getBoundingClientRect().right, page: document.querySelector("#view-sessions").getBoundingClientRect().right }));
assert(fit.right <= fit.page + 1, `the row overflows: ${JSON.stringify(fit)}`);
// a hit opens the conversation at the message that said it
const y0 = await page.evaluate(() => scrollY);
await rows.first().click();
const sheet = page.locator(".sess-sheet");
await sheet.locator(".sess-found").waitFor();
assert.deepEqual([log.read.at(-1).agent, log.read.at(-1).id, log.read.at(-1).find], ["claude", "c-1", "zanzibar"]);
assert.equal((await sheet.locator(".sess-from").textContent()).trim(), await tr("{n} earlier messages not shown", { n: 24 }));
assert.match(await sheet.locator(".sess-found").textContent(), /Zanzibar key kept/);
assert.equal(await sheet.locator(".sess-found").count(), 1);
const where = await sheet.locator(".sess-found").evaluate((n) => {
const body = n.closest(".ebody");
return { top: n.getBoundingClientRect().top - body.getBoundingClientRect().top, scrolled: body.scrollTop, h: body.clientHeight };
});
assert(where.scrolled > 0 && where.top >= 0 && where.top < 40, `the sheet starts at the words: ${JSON.stringify(where)}`);
assert.equal(await page.evaluate(() => scrollY), y0, "the page never scrolled");
await page.keyboard.press("Escape");
await sheet.waitFor({ state: "detached" });
// the agent's own hit opens there too
await view.locator('.row.sm-sess[data-id="p-1"] .sm-hit').click();
await sheet.locator(".sess-found").waitFor();
assert.deepEqual([log.read.at(-1).agent, log.read.at(-1).id, log.read.at(-1).find], ["pi", "p-1", "zanzibar"]);
await page.keyboard.press("Escape");
await sheet.waitFor({ state: "detached" });
// cleared, the other agents go with it
await filter.press("Escape");
await box.waitFor({ state: "detached" });
if (lang !== "en") {
const missing = await page.evaluate(([lang, keys]) => keys.filter((k) => !I18N[lang]?.[k]), [lang, KEYS]);
assert.deepEqual(missing, [], `${lang} has every string`);
}
if (process.env.SCREENSHOT_DIR) {
await filter.fill("zanzibar");
await box.waitFor();
await fs.mkdir(process.env.SCREENSHOT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.SCREENSHOT_DIR, `${engine}-${lang}-${width}-sessions-said.png`) });
}
assert.deepEqual(errors, []);
await context.close();
});
}
});
test(`${engine}: in gateway mode no other agent is searched`, async () => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
try {
const { context, view, log, errors } = await open(browser, "en", 1000, true);
await view.locator(".sm-filter").pressSequentially("zanzibar", { delay: 15 });
await view.locator('.row.sm-sess[data-id="p-1"] .sm-hit mark').waitFor();
await view.page().waitForTimeout(800);
assert.deepEqual(log.said, []);
assert.equal(await view.locator(".sm-else").count(), 0);
assert.deepEqual(errors, []);
await context.close();
} finally {
await browser.close();
}
});
}
+18 -1
View File
@@ -100,6 +100,7 @@ var featured = []MarketServer{
searchServer(),
visionServer(),
memoryServer(),
sessionsServer(),
evermeServer(),
nowledgeServer(),
remoteServer("context7", "Context7", "Upstash", gh("upstash"), "https://mcp.context7.com/mcp",
@@ -253,6 +254,22 @@ func memoryServer() MarketServer {
"Memory shared by every agent: your preferences, rules and what each project needs, kept in Magpie. Agents search it before asking again, and save what you ask them to remember.", magpieCommand, []string{"mcp", "memory"})
}
// sessionsServerName is the name Magpie Sessions' server is written
// under, the name the gateway's own sessions server goes by (ownMCP).
const sessionsServerName = "magpie-sessions"
// sessionsServer is Magpie Sessions: what was said in every agent's
// sessions on this computer, as search_sessions and read_session, through
// `magpie mcp sessions`, which passes each call to the gateway's
// SessionsMCPPath (cryingLiu on X). An agent given it reads the user's
// other conversations, so it is given only to the agents picked for it.
func sessionsServer() MarketServer {
m := localServer(sessionsServerName, "Magpie Sessions", "Magpie", "https://usemagpie.ai/favicon.png", "https://usemagpie.ai",
"Search and read what was said in every agent's sessions on this computer: an earlier conversation, decision or fix, from Claude Code, Codex or any agent Magpie reads.", magpieCommand, []string{"mcp", "sessions"})
m.OptIn = true
return m
}
// evermeServer is EverMe's memory (EverMind-AI/EverMe, @everme/memory-mcp,
// the generic stdio server its README gives for any MCP host): mem_search,
// mem_context, mem_save_fact and mem_save_turn against the EverMe backend.
@@ -441,7 +458,7 @@ func serverKey(s *Server) string {
if s.Remote() {
return strings.TrimSuffix(strings.ToLower(s.URL), "/")
}
if len(s.Args) == 2 && s.Args[0] == "mcp" && (s.Args[1] == "image" || s.Args[1] == "browser" || s.Args[1] == "search" || s.Args[1] == "vision" || s.Args[1] == "memory") {
if len(s.Args) == 2 && s.Args[0] == "mcp" && (s.Args[1] == "image" || s.Args[1] == "browser" || s.Args[1] == "search" || s.Args[1] == "vision" || s.Args[1] == "memory" || s.Args[1] == "sessions") {
return "magpie mcp " + s.Args[1] // magpie's own, wherever its binary is
}
uv := progName(s.Command) == "uvx"
+34
View File
@@ -501,6 +501,40 @@ func TestMemoryServerInDiscover(t *testing.T) {
}
}
// Magpie Sessions is offered beside magpie's other servers but, since an
// agent given it reads the user's other conversations, only to the agents
// picked for it; it acts as this computer's user, and a copy at another
// path is the same server.
func TestSessionsServerInDiscover(t *testing.T) {
sandbox(t)
list, err := MarketServers("")
if err != nil {
t.Fatal(err)
}
if !slices.ContainsFunc(list, func(m MarketServer) bool { return m.ID == sessionsServerName && m.OptIn }) {
t.Fatalf("%s not in Discover as opt-in: %+v", sessionsServerName, list)
}
ok(t)(InstallServer(sessionsServerName, nil, []string{"claude"}))
l, err := load()
if err != nil {
t.Fatal(err)
}
s := l.server(sessionsServerName)
if s == nil || strings.Join(s.Agents, ",") != "claude" || !filepath.IsAbs(s.Command) || strings.Join(s.Args, " ") != "mcp sessions" {
t.Fatalf("added as %+v", s)
}
if !hereOnly(s) {
t.Fatal("the sessions server is offered to other computers")
}
other := Server{Name: "said", Transport: "stdio", Command: "/opt/other/magpie", Args: []string{"mcp", "sessions"}}
if serverKey(&other) != serverKey(s) {
t.Fatalf("keys %q and %q", serverKey(&other), serverKey(s))
}
if mem := (Server{Name: "m", Transport: "stdio", Command: s.Command, Args: []string{"mcp", "memory"}}); serverKey(&mem) == serverKey(s) {
t.Fatal("memory and sessions share a key")
}
}
// EverMe and Nowledge Mem are offered as memory sources, each added in one
// step with what its own docs give (OipsAnthony on X).
func TestThirdPartyMemoryServers(t *testing.T) {
+9 -2
View File
@@ -241,8 +241,15 @@ func hubAbouts(ss []*Server) []gateway.HubServer {
// hereOnly is whether s acts as this computer's user beyond what its
// tools' arguments say (gateway.HubServer's HereOnly): Magpie Browser and
// another magpie's router (keepsSession), and magpie's image server.
func hereOnly(s *Server) bool { return keepsSession(s) || isSelf(s) || isMemory(s) }
// another magpie's router (keepsSession), and magpie's image, memory and
// sessions servers.
func hereOnly(s *Server) bool { return keepsSession(s) || isSelf(s) || isMemory(s) || isSessions(s) }
// isSessions is whether s is magpie's own sessions server (`magpie mcp
// sessions`), which reads this computer's user's conversations.
func isSessions(s *Server) bool {
return !s.Remote() && len(s.Args) >= 2 && s.Args[0] == "mcp" && s.Args[1] == "sessions"
}
// isMemory is whether s is magpie's own memory server (`magpie mcp
// memory`), which holds what is known about this computer's user.
+640
View File
@@ -0,0 +1,640 @@
package sessions
// What was said in every agent's sessions, searched at once (cryingLiu on
// X): the Sessions page's search across agents, and the magpie-sessions
// MCP server's search_sessions, which lets an agent find what was said in
// another agent's session.
//
// Reading every session file for each query is what the one-agent search
// does (SearchSession over the agent's sessions, 8 s at most), and over
// every agent it would be tens of gigabytes a query: this computer's
// Claude Code history is 29 GB in 7,390 files, Codex's 8 GB. So the words
// said in them (the user's and the model's text, about 1% of the bytes)
// are kept in an index, said-v1.db beside sessions.json: an SQLite FTS5
// table that keeps no text, only which words are in which session
// (content='', detail='none'). It is made the first time a search asks,
// in the background, the newest sessions first, and kept up to date from
// then on as sessions.json is: a Claude Code or Codex file that grew is
// read from where the last read ended, any other session again whole
// when its files changed. A search asks the index which sessions hold
// every word, then reads only those, the newest first, with
// SearchSession, for the hit and the words round it; the index is never
// the answer, only which files are worth reading.
//
// Words are a letter-or-digit run, matched by their start ("auth" finds
// "authentication", not "oauth"); Chinese, Japanese and Korean have no
// spaces, so each two characters side by side are a word there. An agent
// magpie may not read (Reads) is left out of the index the next time it
// is brought up to date, and out of every answer at once.
import (
"bytes"
"context"
"database/sql"
"errors"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"github.com/yetone/magpie/internal/catalog"
)
// SaidHit is one session a search found, and the words round where.
type SaidHit struct {
Session Session `json:"session"`
Hit Hit `json:"hit"`
}
// SaidFound is what a search over every agent's sessions found: hits,
// the newest session first. Indexed of Total sessions are in the index;
// fewer while it is first made, when only those were searched. Cut: there
// may be more hits than were looked for. Listing: the sessions to index
// are still being found, the first time on a long history, so Indexed and
// Total don't say yet how much was searched.
type SaidFound struct {
Hits []SaidHit `json:"hits"`
Indexed int `json:"indexed"`
Total int `json:"total"`
Cut bool `json:"cut,omitempty"`
Listing bool `json:"listing,omitempty"`
}
// ErrNoWords: a search with no letter or digit to look for.
var ErrNoWords = errors.New("nothing to search for")
const (
// saidStale: an index brought up to date this recently is searched
// as it is (the page searches as the reader types)
saidStale = 10 * time.Second
// saidWait is how long a search waits for the index to be brought up
// to date; one still being made first is searched as far as it got
saidWait = 2 * time.Second
// saidChunk is how many words of one read go in one row
saidChunk = 50_000
// saidWordMax is the runes of a word kept: a long run (a hash, base64)
// is found by its start
saidWordMax = 32
)
// saidSession is a session the index holds: its listing, and what says
// whether its file changed.
type saidSession struct {
s Session
size int64 // the main file's
sig string
// grow: its file is only ever added to (Claude Code's, Codex's), so
// a longer one is read from where the last read ended
grow bool
}
type saidIndex struct {
where func() string // the index's file
list func() []saidSession
mu sync.Mutex
db *sql.DB
file string
running chan struct{} // closed when the refresh running ends
at time.Time // when the last refresh began
sessions map[string]saidSession
indexed int
total int
listed bool // the sessions to index were found once
quit atomic.Bool // the refresh running stops at its next session
}
var saidIdx = &saidIndex{where: SaidPath, list: saidSessions}
// SaidPath is the index's file.
func SaidPath() string { return filepath.Join(filepath.Dir(CachePath()), "said-v1.db") }
// SearchSaid finds needle (NeedleOf) in what was said in every agent's
// sessions, or in agent's alone when it is given: at most limit hits.
func SearchSaid(ctx context.Context, needle, agent string, limit int) (SaidFound, error) {
return saidIdx.search(ctx, needle, agent, limit)
}
// ForgetSaid closes the index, so a test's HOME can go: a refresh
// running stops after the session it is reading.
func ForgetSaid() {
saidIdx.quit.Store(true)
defer saidIdx.quit.Store(false)
saidIdx.mu.Lock()
run := saidIdx.running
saidIdx.mu.Unlock()
if run != nil {
<-run
}
saidIdx.mu.Lock()
defer saidIdx.mu.Unlock()
if saidIdx.db != nil {
saidIdx.db.Close()
}
saidIdx.db, saidIdx.file, saidIdx.sessions, saidIdx.at, saidIdx.indexed, saidIdx.total = nil, "", nil, time.Time{}, 0, 0
saidIdx.listed = false
}
func (x *saidIndex) open() (*sql.DB, error) {
x.mu.Lock()
defer x.mu.Unlock()
file := x.where()
if x.db != nil && x.file == file {
return x.db, nil
}
if x.db != nil {
x.db.Close()
x.db, x.sessions, x.at = nil, nil, time.Time{}
}
if err := os.MkdirAll(filepath.Dir(file), 0o700); err != nil {
return nil, err
}
db, err := sql.Open("sqlite", sqliteURL(file, "_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)"))
if err != nil {
return nil, err
}
db.SetMaxOpenConns(4)
for _, q := range []string{
`CREATE TABLE IF NOT EXISTS files(key TEXT PRIMARY KEY, path TEXT NOT NULL, sig TEXT NOT NULL, upto INTEGER NOT NULL)`,
`CREATE TABLE IF NOT EXISTS chunks(rowid INTEGER PRIMARY KEY, key TEXT NOT NULL)`,
`CREATE INDEX IF NOT EXISTS chunks_key ON chunks(key)`,
`CREATE VIRTUAL TABLE IF NOT EXISTS said USING fts5(t, content='', contentless_delete=1, detail='none', tokenize='unicode61 remove_diacritics 2')`,
} {
if _, err := db.Exec(q); err != nil {
db.Close()
return nil, err
}
}
os.Chmod(file, 0o600)
x.db, x.file = db, file
return db, nil
}
// fresh starts bringing the index up to date, unless it was a moment
// ago, and waits for it at most wait.
func (x *saidIndex) fresh(ctx context.Context, db *sql.DB, wait time.Duration) {
x.mu.Lock()
run := x.running
if run == nil && time.Since(x.at) >= saidStale {
run = make(chan struct{})
x.running, x.at = run, time.Now()
go func() {
defer func() {
x.mu.Lock()
x.running = nil
x.mu.Unlock()
close(run)
}()
x.refresh(db)
}()
}
x.mu.Unlock()
if run == nil {
return
}
t := time.NewTimer(wait)
defer t.Stop()
select {
case <-run:
case <-t.C:
case <-ctx.Done():
}
}
// saidRow is what the index holds of a session.
type saidRow struct {
path, sig string
upto int64
}
// refresh brings the index up to date with the sessions listed now: the
// newest first, so a search while it is first made finds the latest.
func (x *saidIndex) refresh(db *sql.DB) {
list := x.list()
sort.SliceStable(list, func(i, j int) bool { return list[i].s.Last.After(list[j].s.Last) })
now := make(map[string]saidSession, len(list))
for _, ss := range list {
now[ss.s.Agent+":"+ss.s.ID] = ss
}
rows := map[string]saidRow{}
if rs, err := db.Query(`SELECT key, path, sig, upto FROM files`); err == nil {
for rs.Next() {
var k string
var r saidRow
if rs.Scan(&k, &r.path, &r.sig, &r.upto) == nil {
rows[k] = r
}
}
rs.Close()
}
done := 0
for _, ss := range list {
if r, ok := rows[ss.s.Agent+":"+ss.s.ID]; ok && saidSame(ss, r) {
done++
}
}
x.mu.Lock()
x.sessions, x.indexed, x.total, x.listed = now, done, len(list), true
x.mu.Unlock()
// gone, or of an agent magpie may no longer read
for k := range rows {
if _, ok := now[k]; !ok {
saidDrop(db, k)
}
}
for _, ss := range list {
if x.quit.Load() {
return
}
k := ss.s.Agent + ":" + ss.s.ID
r, had := rows[k]
if had && saidSame(ss, r) {
continue
}
if !Reads(ss.s.Agent) {
continue
}
var err error
if had && ss.grow && r.path == ss.s.Path && ss.size >= r.upto {
err = saidRead(db, k, ss, r.upto, false)
} else {
err = saidRead(db, k, ss, 0, true)
}
if err == nil {
x.mu.Lock()
x.indexed++
x.mu.Unlock()
}
}
}
// saidSame says whether the index holds a session as it is now.
func saidSame(ss saidSession, r saidRow) bool {
if r.path != ss.s.Path {
return false
}
if ss.grow {
return r.upto == ss.size || r.upto == lineEnd(ss.s.Path, ss.size)
}
return r.sig == ss.sig
}
func saidDrop(db *sql.DB, key string) {
tx, err := db.Begin()
if err != nil {
return
}
defer tx.Rollback()
if saidDropIn(tx, key) == nil {
tx.Commit()
}
}
func saidDropIn(tx *sql.Tx, key string) error {
if _, err := tx.Exec(`DELETE FROM said WHERE rowid IN (SELECT rowid FROM chunks WHERE key = ?)`, key); err != nil {
return err
}
if _, err := tx.Exec(`DELETE FROM chunks WHERE key = ?`, key); err != nil {
return err
}
_, err := tx.Exec(`DELETE FROM files WHERE key = ?`, key)
return err
}
// saidRead reads what was said in a session, from the byte from on when
// it grows (else whole, its rows dropped first), into the index.
func saidRead(db *sql.DB, key string, ss saidSession, from int64, whole bool) error {
var chunks []string
words := map[string]struct{}{}
flush := func() {
if len(words) == 0 {
return
}
var b strings.Builder
for w := range words {
b.WriteString(w)
b.WriteByte(' ')
}
chunks = append(chunks, b.String())
clear(words)
}
add := func(_ bool, p Part) bool {
if said(p) {
saidWords(p.Text, func(w string) {
words[w] = struct{}{}
})
if len(words) >= saidChunk {
flush()
}
}
return true
}
upto := ss.size
var err error
if ss.grow {
upto = lineEnd(ss.s.Path, ss.size)
if whole {
from = 0
}
c := Call{Agent: ss.s.Agent, File: ss.s.Path, From: from, To: upto}
if ss.s.Agent == "codex" {
err = codexContentOf(c, codexSaidLine, add)
} else {
err = claudeContentOf(c, claudeSaidLine, add)
}
} else {
err = readTranscriptOf(ss.s, nil, add)
}
if err != nil && !errors.Is(err, io.EOF) {
return err
}
flush()
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if whole {
if err := saidDropIn(tx, key); err != nil {
return err
}
}
for _, c := range chunks {
r, err := tx.Exec(`INSERT INTO chunks(key) VALUES(?)`, key)
if err != nil {
return err
}
id, err := r.LastInsertId()
if err != nil {
return err
}
if _, err := tx.Exec(`INSERT INTO said(rowid, t) VALUES(?, ?)`, id, c); err != nil {
return err
}
}
if _, err := tx.Exec(`INSERT INTO files(key, path, sig, upto) VALUES(?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET path = excluded.path, sig = excluded.sig, upto = excluded.upto`, key, ss.s.Path, ss.sig, upto); err != nil {
return err
}
return tx.Commit()
}
// claudeSaidLine: a line that may say something, not a tool's answer
// (most of a session's bytes)
func claudeSaidLine(b []byte) bool { return !bytes.Contains(b, ccToolAnswer) }
var (
ccToolAnswer = []byte(`"tool_use_id":`)
cxMessage = []byte(`"type":"message"`)
)
// codexSaidLine: a message, not a tool call, its output or reasoning
func codexSaidLine(b []byte) bool { return bytes.Contains(b, cxMessage) }
// lineEnd is where the last whole line of a file ends, at or before size:
// a line still being written is read when it is whole.
func lineEnd(path string, size int64) int64 {
f, err := os.Open(path)
if err != nil {
return size
}
defer f.Close()
buf := make([]byte, 64<<10)
for end := size; end > 0; {
start := max(0, end-int64(len(buf)))
n, err := f.ReadAt(buf[:end-start], start)
if err != nil && !errors.Is(err, io.EOF) {
return size
}
for i := n - 1; i >= 0; i-- {
if buf[i] == '\n' {
return start + int64(i) + 1
}
}
end = start
}
return 0
}
// cjk is a letter written without spaces between words.
func cjk(r rune) bool {
return unicode.Is(unicode.Han, r) || unicode.In(r, unicode.Hiragana, unicode.Katakana, unicode.Hangul)
}
// saidRuns tells each a run of text the index keeps words of: letters
// and digits lowered, a run of Chinese, Japanese or Korean (han) apart.
func saidRuns(text string, each func(run []rune, han bool)) {
var run []rune
han := false
end := func() {
if len(run) > 0 {
each(run, han)
run = run[:0]
}
}
for _, r := range text {
switch {
case cjk(r):
if !han {
end()
}
han = true
run = append(run, r)
case unicode.IsLetter(r) || unicode.IsDigit(r) || unicode.Is(unicode.Mn, r):
if han {
end()
}
han = false
run = append(run, unicode.ToLower(r))
default:
end()
}
}
end()
}
// saidWords tells emit each word of text, as the index keeps them: a run
// of letters and digits (its first saidWordMax runes), and in Chinese,
// Japanese and Korean each two characters side by side, and the last
// one of a run alone, so that one character is found by its start.
func saidWords(text string, emit func(string)) {
saidRuns(text, func(run []rune, han bool) {
if !han {
emit(string(run[:min(len(run), saidWordMax)]))
return
}
for i := 0; i+1 < len(run); i++ {
emit(string(run[i : i+2]))
}
emit(string(run[len(run)-1:]))
})
}
// saidTerms are the FTS5 queries a needle's words make, each to be held
// by a session: a word by its start, two CJK characters side by side as
// they are, and one standing alone by its start.
func saidTerms(needle string) []string {
var out []string
seen := map[string]bool{}
put := func(q string) {
if !seen[q] {
seen[q] = true
out = append(out, q)
}
}
saidRuns(needle, func(run []rune, han bool) {
switch {
case !han:
put(`"` + string(run[:min(len(run), saidWordMax)]) + `"*`)
case len(run) == 1:
put(`"` + string(run) + `"*`)
default:
for i := 0; i+1 < len(run); i++ {
put(`"` + string(run[i:i+2]) + `"`)
}
}
})
return out
}
// saidKeys are the sessions whose index holds every term.
func saidKeys(ctx context.Context, db *sql.DB, terms []string) (map[string]bool, error) {
var keys map[string]bool
for _, t := range terms {
rs, err := db.QueryContext(ctx, `SELECT DISTINCT c.key FROM said JOIN chunks c ON c.rowid = said.rowid WHERE said MATCH ?`, t)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
// a term FTS5 won't take narrows nothing: the files
// are read for the words in any case
continue
}
got := map[string]bool{}
for rs.Next() {
var k string
if rs.Scan(&k) == nil && (keys == nil || keys[k]) {
got[k] = true
}
}
err = rs.Err()
rs.Close()
if err != nil {
return nil, err
}
keys = got
if len(keys) == 0 {
break
}
}
return keys, nil
}
// saidReadMost is how long a search reads the files the index named.
const saidReadMost = 6 * time.Second
func (x *saidIndex) search(ctx context.Context, needle, agent string, limit int) (SaidFound, error) {
out := SaidFound{Hits: []SaidHit{}}
terms := saidTerms(needle)
if len(terms) == 0 {
return out, ErrNoWords
}
if limit <= 0 {
limit = 20
}
db, err := x.open()
if err != nil {
return out, err
}
x.fresh(ctx, db, saidWait)
keys, err := saidKeys(ctx, db, terms)
if err != nil {
return out, err
}
x.mu.Lock()
var found []saidSession
for k := range keys {
if ss, ok := x.sessions[k]; ok && (agent == "" || ss.s.Agent == agent) && Reads(ss.s.Agent) {
found = append(found, ss)
}
}
out.Indexed, out.Total, out.Listing = x.indexed, x.total, !x.listed
x.mu.Unlock()
sort.SliceStable(found, func(i, j int) bool {
if !found[i].s.Last.Equal(found[j].s.Last) {
return found[i].s.Last.After(found[j].s.Last)
}
return found[i].s.ID < found[j].s.ID
})
until := time.Now().Add(saidReadMost)
for _, ss := range found {
if len(out.Hits) == limit || time.Now().After(until) {
out.Cut = true
break
}
if ctx.Err() != nil {
return out, ctx.Err()
}
h, ok, err := SearchSession(ctx, ss.s, needle)
if err == nil && ok {
out.Hits = append(out.Hits, SaidHit{Session: ss.s, Hit: h})
}
}
return out, nil
}
// saidSessions are every session whose conversation can be read, of the
// agents magpie may read, as the Sessions page lists them.
func saidSessions() []saidSession {
storeMu.RLock()
defer storeMu.RUnlock()
mu.Lock()
defer mu.Unlock()
loadCache()
defer useDBs()()
files := allFiles()
refresh(files, files)
groups := byKey(files, nil)
copies, branches := ccFamily(files)
titles := codexTitleOf()
price := func(string) *catalog.Price { return nil }
out := make([]saidSession, 0, len(groups))
for k, fs := range groups {
if copies[k] != "" || len(fs) == 0 || !HasTranscript(fs[0].agent) || !Reads(fs[0].agent) {
continue
}
s, ok := assembleListed(fs, price, titles)
if !ok || !readable(s) || s.Path == "" {
continue
}
setBranch(&s, branches[k], groups)
ss := saidSession{s: s}
var mod modTime
var size int64
for _, f := range fs {
size += f.size
mod = max(mod, f.mod)
if f.path == s.Path {
ss.size = f.size
}
}
ss.sig = strconv.FormatInt(size, 10) + "/" + strconv.FormatInt(int64(mod), 10)
ss.grow = saidGrows(s)
out = append(out, ss)
}
return out
}
// saidGrows: a session whose file is only added to, line by line.
func saidGrows(s Session) bool {
switch s.Agent {
case "claude", "qoder", "qoder-cn", "codex":
return !packed(s.Path) && linesFile(s)
}
return false
}
+404
View File
@@ -0,0 +1,404 @@
package sessions
import (
"context"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
"testing"
"time"
)
func TestSaidWords(t *testing.T) {
var got []string
saidWords("Fix the OAuth-login, 修复登录问题 ok", func(w string) { got = append(got, w) })
want := []string{"fix", "the", "oauth", "login", "修复", "复登", "登录", "录问", "问题", "题", "ok"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("words %q, want %q", got, want)
}
got = nil
saidWords(strings.Repeat("a", 100), func(w string) { got = append(got, w) })
if len(got) != 1 || len(got[0]) != saidWordMax {
t.Fatalf("a long run: %q", got)
}
}
func TestSaidTerms(t *testing.T) {
for needle, want := range map[string][]string{
"auth bug": {`"auth"*`, `"bug"*`},
"登录问题": {`"登录"`, `"录问"`, `"问题"`},
"修": {`"修"*`},
"!!! ...": nil,
"bug bug": {`"bug"*`},
`say "hi"*`: {`"say"*`, `"hi"*`},
} {
if got := saidTerms(NeedleOf(needle)); !reflect.DeepEqual(got, want) {
t.Errorf("%q: terms %q, want %q", needle, got, want)
}
}
}
// saidTestIndex is an index in a test's folder over the sessions list
// gives.
func saidTestIndex(t *testing.T, list func() []saidSession) *saidIndex {
t.Helper()
file := filepath.Join(t.TempDir(), "said.db")
x := &saidIndex{where: func() string { return file }, list: list}
t.Cleanup(func() {
x.mu.Lock()
run := x.running
x.mu.Unlock()
if run != nil {
<-run
}
if x.db != nil {
x.db.Close()
}
})
return x
}
// stale has the next search bring the index up to date.
func (x *saidIndex) stale() {
x.mu.Lock()
x.at = time.Time{}
x.mu.Unlock()
}
// saidFile writes lines to a session file of agent and lists it as the
// index would.
func saidFile(t *testing.T, dir, agent, id string, last time.Time, lines ...string) saidSession {
t.Helper()
path := filepath.Join(dir, id+".jsonl")
writeLines(t, path, lines...)
return saidOf(t, Session{Agent: agent, ID: id, Path: path, Last: last})
}
func saidOf(t *testing.T, s Session) saidSession {
t.Helper()
fi, err := os.Stat(s.Path)
if err != nil {
t.Fatal(err)
}
return saidSession{s: s, size: fi.Size(), sig: fi.ModTime().String(), grow: s.Agent == "claude" || s.Agent == "codex"}
}
func cxSaid(role, text string) string {
kind := "input_text"
if role == "assistant" {
kind = "output_text"
}
return `{"type":"response_item","payload":{"type":"message","role":"` + role + `","content":[{"type":"` + kind + `","text":"` + text + `"}]}}`
}
func saidAgents(f SaidFound) []string {
var out []string
for _, h := range f.Hits {
out = append(out, h.Session.Agent+":"+h.Session.ID)
}
return out
}
// cryingLiu on X: what was said in any agent's session is found from one
// search, the newest session first, with the words round it.
func TestSearchSaidAcrossAgents(t *testing.T) {
dir := t.TempDir()
now := time.Now()
list := []saidSession{
saidFile(t, dir, "claude", "c1", now.Add(-time.Hour), claudeAsked, claudeTool, claudeSaid),
saidFile(t, dir, "codex", "x1", now,
`{"type":"session_meta","payload":{"id":"x1"}}`,
cxSaid("user", "Why does the rainbow build fail?"),
`{"type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{\"command\":[\"kubectl\"]}","call_id":"c1"}}`,
cxSaid("assistant", "修复登录问题之后就好了")),
}
x := saidTestIndex(t, func() []saidSession { return list })
ctx := context.Background()
f, err := x.search(ctx, NeedleOf("rainbow"), "", 10)
if err != nil {
t.Fatal(err)
}
if got := saidAgents(f); !reflect.DeepEqual(got, []string{"codex:x1", "claude:c1"}) {
t.Fatalf("rainbow found in %v", got)
}
if f.Indexed != 2 || f.Total != 2 {
t.Fatalf("indexed %d of %d", f.Indexed, f.Total)
}
if h := f.Hits[1].Hit; h.Match != "rainbow" || h.Role != "assistant" {
t.Fatalf("claude's hit: %+v", h)
}
// Chinese, by its characters side by side, and a word by its start
if f, _ := x.search(ctx, NeedleOf("登录问题"), "", 10); !reflect.DeepEqual(saidAgents(f), []string{"codex:x1"}) {
t.Fatalf("登录问题 found in %v", saidAgents(f))
}
if f, _ := x.search(ctx, NeedleOf("salt"), "", 10); !reflect.DeepEqual(saidAgents(f), []string{"claude:c1"}) {
t.Fatalf("salt found in %v", saidAgents(f))
}
// one agent's alone
if f, _ := x.search(ctx, NeedleOf("rainbow"), "claude", 10); !reflect.DeepEqual(saidAgents(f), []string{"claude:c1"}) {
t.Fatalf("claude's rainbow: %v", saidAgents(f))
}
// a word said in no session, and one only a tool call has
for _, w := range []string{"kubernetes", "kubectl"} {
if f, _ := x.search(ctx, NeedleOf(w), "", 10); len(f.Hits) != 0 {
t.Fatalf("%s found in %v", w, saidAgents(f))
}
}
// the limit
if f, _ := x.search(ctx, NeedleOf("rainbow"), "", 1); len(f.Hits) != 1 || !f.Cut {
t.Fatalf("limit 1: %v cut %v", saidAgents(f), f.Cut)
}
if _, err := x.search(ctx, NeedleOf("?!"), "", 10); err != ErrNoWords {
t.Fatalf("no words: %v", err)
}
}
// The index tells which files to read: a session it doesn't name is not
// read for a search.
func TestSearchSaidReadsOnlyTheSessionsWithTheWords(t *testing.T) {
dir := t.TempDir()
list := []saidSession{
saidFile(t, dir, "claude", "c1", time.Now(), claudeAsked, claudeSaid),
saidFile(t, dir, "claude", "c2", time.Now(), `{"type":"user","message":{"role":"user","content":"nothing here"},"uuid":"u1"}`),
}
x := saidTestIndex(t, func() []saidSession { return list })
if _, err := x.search(context.Background(), NeedleOf("salt"), "", 10); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
read := map[string]int{}
scanHook = func(p string, _ int64) {
mu.Lock()
read[filepath.Base(p)]++
mu.Unlock()
}
t.Cleanup(func() { scanHook = nil })
f, err := x.search(context.Background(), NeedleOf("salt"), "", 10)
if err != nil || len(f.Hits) != 1 {
t.Fatalf("salt: %v %v", saidAgents(f), err)
}
if read["c2.jsonl"] != 0 || read["c1.jsonl"] == 0 {
t.Fatalf("files read: %v", read)
}
}
// A Claude Code or Codex file that grew is read from where the last read
// ended, and a line still being written waits until it is whole.
func TestSearchSaidReadsAGrownFileFromWhereItEnded(t *testing.T) {
dir := t.TempDir()
ss := saidFile(t, dir, "claude", "c1", time.Now(), claudeAsked, claudeSaid)
var mu sync.Mutex
list := []saidSession{ss}
x := saidTestIndex(t, func() []saidSession { mu.Lock(); defer mu.Unlock(); return list })
ctx := context.Background()
if f, _ := x.search(ctx, NeedleOf("salt"), "", 10); len(f.Hits) != 1 {
t.Fatal("salt not found")
}
size := ss.size
grow := func(text string) {
fh, err := os.OpenFile(ss.s.Path, os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
fh.WriteString(text)
fh.Close()
mu.Lock()
list = []saidSession{saidOf(t, ss.s)}
mu.Unlock()
x.stale()
}
var from []int64
scanHook = func(p string, off int64) {
if p == ss.s.Path {
mu.Lock()
from = append(from, off)
mu.Unlock()
}
}
t.Cleanup(func() { scanHook = nil })
// half a line: not read yet
line := `{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Zanzibar holds the keys."}]},"uuid":"a3"}`
grow(line[:40])
if f, _ := x.search(ctx, NeedleOf("zanzibar"), "", 10); len(f.Hits) != 0 {
t.Fatalf("half a line indexed: %v", saidAgents(f))
}
grow(line[40:] + "\n")
f, _ := x.search(ctx, NeedleOf("zanzibar"), "", 10)
if len(f.Hits) != 1 {
t.Fatalf("zanzibar not found after the file grew")
}
mu.Lock()
first := append([]int64(nil), from...)
mu.Unlock()
if len(first) == 0 || first[0] != size {
t.Fatalf("the grown file was read from %v, want %d first", first, size)
}
// what was there before is still found
if f, _ := x.search(ctx, NeedleOf("salt"), "", 10); len(f.Hits) != 1 {
t.Fatal("salt lost after the file grew")
}
}
// A session gone from the list is gone from the index; one rewritten is
// read again whole, its old words gone.
func TestSearchSaidForgetsGoneAndRewrittenSessions(t *testing.T) {
dir := t.TempDir()
a := saidFile(t, dir, "gemini", "g1", time.Now(), claudeAsked)
b := saidFile(t, dir, "claude", "c1", time.Now(), claudeSaid)
a.grow = false
var mu sync.Mutex
list := []saidSession{a, b}
x := saidTestIndex(t, func() []saidSession { mu.Lock(); defer mu.Unlock(); return list })
ctx := context.Background()
if _, err := x.search(ctx, NeedleOf("salt"), "", 10); err != nil {
t.Fatal(err)
}
count := func(key string) (n int) {
x.db.QueryRow(`SELECT count(*) FROM chunks WHERE key = ?`, key).Scan(&n)
return
}
if count("claude:c1") == 0 {
t.Fatal("claude:c1 not indexed")
}
mu.Lock()
list = []saidSession{a}
mu.Unlock()
x.stale()
x.search(ctx, NeedleOf("salt"), "", 10)
if n := count("claude:c1"); n != 0 {
t.Fatalf("a gone session keeps %d rows", n)
}
// a session that isn't only added to, changed: read again whole
a.sig = "changed"
mu.Lock()
list = []saidSession{a}
mu.Unlock()
x.stale()
x.search(ctx, NeedleOf("login"), "", 10)
if n := count("gemini:g1"); n != 1 {
t.Fatalf("a rewritten session has %d rows, want 1", n)
}
}
// An agent magpie may not read is in no answer, even while the index
// still holds it.
func TestSearchSaidLeavesOutAgentsNotRead(t *testing.T) {
dir := t.TempDir()
list := []saidSession{saidFile(t, dir, "claude", "c1", time.Now(), claudeSaid)}
x := saidTestIndex(t, func() []saidSession { return list })
ctx := context.Background()
if f, _ := x.search(ctx, NeedleOf("salt"), "", 10); len(f.Hits) != 1 {
t.Fatal("salt not found")
}
off := func() bool { return true }
OwnOff.Store(&off)
t.Cleanup(func() { OwnOff.Store(nil) })
if f, _ := x.search(ctx, NeedleOf("salt"), "", 10); len(f.Hits) != 0 {
t.Fatalf("found in an agent not read: %v", saidAgents(f))
}
}
// The real list: every agent's sessions, of the agents magpie may read.
func TestSaidSessionsListsTheAgentsRead(t *testing.T) {
d := consentHome(t)
writeTwoAgents(t, d)
keys := func() map[string]bool {
out := map[string]bool{}
for _, ss := range saidSessions() {
out[ss.s.Agent] = true
if ss.size == 0 || ss.sig == "" || !ss.grow {
t.Errorf("%s: %+v", ss.s.Agent, ss)
}
}
return out
}
if got := keys(); len(got) != 0 {
t.Fatalf("nothing allowed lists %v", got)
}
if err := SetReads(new(bool), map[string]bool{"claude": true}); err != nil {
t.Fatal(err)
}
Reset()
if got := keys(); !got["claude"] || got["codex"] {
t.Fatalf("claude allowed lists %v", got)
}
on := true
if err := SetReads(&on, nil); err != nil {
t.Fatal(err)
}
Reset()
if got := keys(); !got["claude"] || !got["codex"] {
t.Fatalf("all allowed lists %v", got)
}
}
// A hit past what a transcript keeps is shown: the transcript starts a
// few parts before it.
func TestTranscriptAtStartsBeforeTheHit(t *testing.T) {
filler := strings.Repeat("lorem ipsum ", 600) // ~7,200 characters
var lines []string
for i := range 80 {
lines = append(lines, `{"type":"user","message":{"role":"user","content":"`+filler+`"},"uuid":"u`+strconv.Itoa(i)+`"}`)
}
lines = append(lines, `{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"the zanzibar answer"}]},"uuid":"z"}`)
s := claudeFile(t, lines...)
whole, err := TranscriptOf(s)
if err != nil || !whole.Cut {
t.Fatalf("the fixture should be cut: %v %v", whole.Cut, err)
}
at, err := TranscriptAt(s, NeedleOf("Zanzibar"))
if err != nil {
t.Fatal(err)
}
if at.From != 80-transcriptLead {
t.Fatalf("from %d, want %d", at.From, 80-transcriptLead)
}
if n := len(at.Parts); n == 0 || !strings.Contains(at.Parts[n-1].Text, "zanzibar") {
t.Fatalf("the hit isn't in the transcript (%d parts)", n)
}
// a hit TranscriptOf shows: it as it is
near, _ := TranscriptAt(s, NeedleOf("lorem"))
if near.From != 0 || len(near.Parts) != len(whole.Parts) {
t.Fatalf("a near hit moved the transcript: from %d", near.From)
}
}
// The first listing of a long history can outlast a search's wait: the
// answer then says the sessions are still being found, not that none says
// the words (the real 29G Claude and 60G Codex history took ~50s to list).
func TestSearchSaidWhileTheSessionsAreFound(t *testing.T) {
dir := t.TempDir()
at := time.Now().Add(-time.Hour)
ss := saidFile(t, dir, "claude", "c1", at, `{"type":"user","message":{"role":"user","content":"the Zanzibar key"}}`)
hold := make(chan struct{})
x := saidTestIndex(t, func() []saidSession { <-hold; return []saidSession{ss} })
var let sync.Once
letGo := func() { let.Do(func() { close(hold) }) }
t.Cleanup(letGo) // before the index's own, which waits for the listing
// the search waits saidWait for a listing held until it is let go
f, err := x.search(context.Background(), "zanzibar", "", 10)
if err != nil {
t.Fatal(err)
}
if !f.Listing || len(f.Hits) != 0 {
t.Fatalf("while listing: %+v", f)
}
letGo()
x.mu.Lock()
run := x.running
x.mu.Unlock()
<-run
f, err = x.search(context.Background(), "zanzibar", "", 10)
if err != nil || f.Listing || f.Indexed != 1 || f.Total != 1 || len(f.Hits) != 1 {
t.Fatalf("listed: %+v %v", f, err)
}
}
+3 -1
View File
@@ -1996,8 +1996,10 @@ func pricer() func(string) *catalog.Price {
}
}
// Reset forgets the kept parses, in memory only.
// Reset forgets the kept parses, in memory only, and closes the index of
// what was said, so a test's HOME can go.
func Reset() {
ForgetSaid()
desktopTitles.Lock()
desktopTitles.names, desktopTitles.last = nil, nil
desktopTitles.Unlock()
+68 -2
View File
@@ -15,8 +15,11 @@ import (
// Transcript is what was said in a session, in the order it was said.
type Transcript struct {
Parts []Part `json:"parts"`
Cut bool `json:"cut,omitempty"` // there was more than is kept here
Parts []Part `json:"parts"`
Cut bool `json:"cut,omitempty"` // there was more than is kept here
// From is the parts before the first one kept, left out so that the
// part a search found is shown (TranscriptAt)
From int `json:"from,omitempty"`
Source string `json:"source,omitempty"`
Captured int `json:"captured,omitempty"`
}
@@ -72,6 +75,69 @@ func TranscriptOf(s Session) (Transcript, error) {
return out, readTranscript(s, out.add)
}
// transcriptLead is the parts kept before the one TranscriptAt finds,
// when the ones before it are left out.
const transcriptLead = 6
// TranscriptAt is TranscriptOf for a reader brought to the part that
// holds needle (NeedleOf), the first said one, else the first anywhere,
// as SearchSession's hit: when TranscriptOf would be cut before that
// part, the parts before it are left out (but a few) and From says how
// many were.
func TranscriptAt(s Session, needle string) (Transcript, error) {
if needle == "" {
return TranscriptOf(s)
}
if !Reads(s.Agent) {
return Transcript{Parts: []Part{}}, ErrNotRead
}
if !HasTranscript(s.Agent) || s.Path == "" {
return Transcript{Parts: []Part{}}, ErrNoTranscript
}
// the parts TranscriptOf keeps are counted as it keeps them, and the
// found one's place among them noted, and the characters before it
at, saidAt, n, size, sizeAt, saidSize := -1, -1, 0, 0, 0, 0
if err := readTranscript(s, func(_ bool, p Part) bool {
p, ok := keep(p)
if !ok {
return true
}
if searched(p) {
if _, hit := hitIn(p, needle); hit {
if at < 0 {
at, sizeAt = n, size
}
if said(p) && saidAt < 0 {
saidAt, saidSize = n, size
}
}
}
n++
size += len(p.Text)
return saidAt < 0
}); err != nil {
return Transcript{Parts: []Part{}}, err
}
if saidAt >= 0 {
at, sizeAt = saidAt, saidSize
}
if at < 0 || sizeAt < transcriptMax {
return TranscriptOf(s)
}
out := Transcript{Parts: []Part{}, From: max(0, at-transcriptLead)}
i := 0
return out, readTranscript(s, func(in bool, p Part) bool {
if _, ok := keep(p); !ok {
return true
}
i++
if i <= out.From {
return true
}
return out.add(in, p)
})
}
// readTranscript tells add each part of a session's conversation, in order,
// as its agent's file has it.
func readTranscript(s Session, add func(bool, Part) bool) error {