Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(web): memory changes below the file summary, with a peer Memory side panel (#375)

Yaowei Zheng4cb360ad732a
diff --git a/changelog/unreleased/2026-08-20-memory-change-list.md b/changelog/unreleased/2026-08-20-memory-change-list.md
new file mode 100644
index 00000000..7c6a9e23
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-memory-change-list.md
@@ -0,0 +1,19 @@
+# Memory changes below the file summary, with a peer Memory side panel
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `web`
+- **PR:** [#375](https://github.com/Prism-Shadow/penguin-harness/pull/375)
+
+[中文版](2026-08-20-memory-change-list.zh.md)
+
+When a Task changed the Agent's Memory, the conversation now shows it in two places. A memory-changes card renders directly below the file-summary card at the end of the Task — one row per topic file, with the scope (User or Workspace memory) and the change kind (wrote / edited) as icon-and-tooltip markers. And the chat gained a Memory panel — a peer of the subagents, terminal and Workspace panels, with its own entry in the panel switcher and the same docked/Sheet shell and exclusivity — holding two levels: a list of both scopes' topics (the same data the agent-settings memory tab shows, topics changed by this conversation carrying a marker), and one memory's detail, its content rendered like the file viewer. Clicking a card row opens the panel directly on that memory's content; entering through the panel switcher always starts at the list. Tasks that touched no memory show no card.
+
+## Details
+
+- Rows come from the structured tool record: successfully completed `write_file` / `edit_file` calls whose path falls under the Session's Memory root (`<agent_state>/memory/`), merged to one row per file — a full write outweighs in-place edits. Denied or failed calls never appear.
+- A changed file the loaded listing no longer carries was deleted afterwards: it leaves the card and the panel list. While the listing hasn't loaded, nothing is treated as deleted.
+- Each scope's `MEMORY.md` index and the `.workspace` marker are filtered out: the index is rewritten alongside nearly every topic change and would double every row.
+- Changes made through an opaque `exec_command` shell carry no structured signal and are not listed, matching the file-summary card's existing limitation. Root-session Tasks only; a subagent's memory writes belong to that child's own Agent.
+- Streaming replies never flash the memory displays: re-derived but unchanged rows keep their identity, so the listing and an open detail only refresh when a settled Task actually changed memory.
+- Memory management (add / edit / delete) stays on the agent-settings memory tab; the panel's list header links there. On narrow viewports the panel rides the same bottom Sheet as its siblings; switching conversations resets it to the list.
diff --git a/changelog/unreleased/2026-08-20-memory-change-list.zh.md b/changelog/unreleased/2026-08-20-memory-change-list.zh.md
new file mode 100644
index 00000000..efef7107
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-memory-change-list.zh.md
@@ -0,0 +1,19 @@
+# 文件汇总下方列出记忆更改,并新增同级记忆侧栏
+
+- **Date:** 2026-08-20
+- **Type:** feature
+- **Scope:** `web`
+- **PR:** [#375](https://github.com/Prism-Shadow/penguin-harness/pull/375)
+
+[English](2026-08-20-memory-change-list.md)
+
+Task 更改过 Agent 记忆时,对话现在会在两处展示出来。Task 末尾的文件汇总卡正下方新增一张记忆更改卡——每个主题文件一行,以 icon+tooltip 标注作用域(用户记忆或工作区记忆)与更改类型(写入 / 编辑)。聊天新增记忆面板——与智能体、终端、工作区面板同级,在面板切换器中有自己的入口,共用同一套停靠/Sheet 外壳与互斥编排——面板内分两级:列表(两个作用域的主题列表,与 Agent 设置记忆标签页同一份数据,本次对话更改过的主题带标记)与单条记忆的详情,内容以与文件查看一致的方式渲染。点击卡片行直达该条记忆的内容;经面板切换器进入则始终落在列表。未触及记忆的 Task 不显示此卡。
+
+## 详情
+
+- 行来自结构化工具记录:成功完成、路径落在会话记忆根(`<agent_state>/memory/`)下的 `write_file` / `edit_file` 调用,按文件合并为一行——整文件写入的权重高于原地编辑。被拒绝或失败的调用不会出现。
+- 已加载列表不再收录的已更改文件即已被删除:它会从更改卡与面板列表中消失。列表尚未加载时,不把任何条目当作已删除。
+- 各作用域的 `MEMORY.md` 索引与 `.workspace` 标记文件被过滤:索引几乎随每次主题变更连带改写,单列会使每行都翻倍。
+- 经不透明 `exec_command` shell 所做的更改没有结构化信号,不会列出,与文件汇总卡既有的局限一致。仅统计根会话的 Task;subagent 的记忆写入属于其自身 Agent。
+- 流式回复不会引起记忆界面闪烁:重派生但内容未变的行保持引用不变,列表与已打开的详情只在真正改动记忆的 Task 落定时刷新。
+- 记忆管理(添加 / 编辑 / 删除)仍在 Agent 设置的记忆标签页;面板列表头部可跳转过去。窄视口下面板与其兄弟面板共用底部 Sheet;切换会话时重置为列表。
diff --git a/packages/web/src/features/agents/memory-tab.tsx b/packages/web/src/features/agents/memory-tab.tsx
index 5145d5fe..9d1260e0 100644
--- a/packages/web/src/features/agents/memory-tab.tsx
+++ b/packages/web/src/features/agents/memory-tab.tsx
@@ -66,10 +66,7 @@ import {
} from "./memory-transfer";
import type { MemoryImportPlan } from "./memory-transfer";
-/** The body without its frontmatter block: the drawer's metadata header already shows those fields, so rendering the raw YAML too would only repeat them. */
-function bodyWithoutFrontmatter(content: string): string {
- return content.replace(/^\ufeff?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "");
-}
+import { bodyWithoutFrontmatter } from "../../lib/frontmatter";
/** Same breakpoint as the chat page's panels: \u22651024px the view opens as a side Drawer, below it as a bottom Sheet. */
const DESKTOP_QUERY = "(min-width: 1024px)";
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 28522d99..64a6ad28 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -7,7 +7,8 @@
* panel on the right (use-files-panel.ts), and each message's trailing file summary card jumps to
* and locates the file in the tree via onOpenFile. The subagents panel docks the same way
* (use-subagents-panel.ts): subagent chips in the stream open it focused via onOpenSubagent,
- * and the two docked panels are mutually exclusive (coordinated here, not in the hooks).
+ * and the three docked panels — files, subagents and Memory (use-memory-panel.ts) — are
+ * mutually exclusive (coordinated here, not in the hooks).
* Approval mode and Model/context usage live in the input area's toolbar; context is compacted
* via the /compact slash command.
* Draft state (/chat/new) is carried by DraftView: Agent / Workspace / approval mode / Model are
@@ -61,6 +62,7 @@ import {
pushMessage,
} from "../../lib/omni/stream-model";
import type { StreamModel } from "../../lib/omni/stream-model";
+import { aggregateMemoryChanges, sameMemoryChanges } from "../../lib/omni/memory-changes";
import { bucketCostUsd, liveSessionElapsedMs } from "../../lib/omni/task-stats";
import type { TaskStatsTracker } from "../../lib/omni/task-stats";
import { useAuth } from "../../state/auth";
@@ -109,6 +111,11 @@ import { providerInfo } from "@prismshadow/penguin-core/model-catalog";
import { FilesPanel } from "./files-panel";
import { useFilesPanel } from "./use-files-panel";
import type { FilesPanelState } from "./use-files-panel";
+import { MemoryPanel } from "./memory-panel";
+import { useMemoryPanel } from "./use-memory-panel";
+import type { MemoryPanelState } from "./use-memory-panel";
+import { useMemoryListing } from "./use-memory-listing";
+import { deletedChangeKeys } from "./memory-nav";
import { SubagentsPanel } from "./subagents-panel";
import { TerminalDockSlot } from "../terminal/terminal-dock-slot";
import {
@@ -314,14 +321,16 @@ export function ChatPage() {
const routeSessionId = params.sessionId ?? null;
const filesPanelRaw = useFilesPanel(routeSessionId);
+ const memoryPanelRaw = useMemoryPanel(routeSessionId);
const subagentsPanelRaw = useSubagentsPanel(routeSessionId);
- // The two docked panels are MUTUALLY EXCLUSIVE — side by side they'd crush the chat column at
- // the 1024px breakpoint (and two stacked Sheets on mobile would be worse). Exclusivity is
+ // The three docked panels are MUTUALLY EXCLUSIVE — side by side they'd crush the chat column at
+ // the 1024px breakpoint (and stacked Sheets on mobile would be worse). Exclusivity is
// enforced here, on the panel objects every consumer receives, rather than at each call site:
// ANY path that opens one panel (toolbar toggles, message file cards via onOpenFile, subagent
- // chips via onOpenSubagent, or a future caller) closes the other as a side effect of
- // setOpen(true). Closing never cascades. The hooks stay uncoordinated on purpose — they don't
- // know about each other; only this page, which owns both, does.
+ // chips via onOpenSubagent, memory-changes card rows via onLocateMemoryChange, or a future
+ // caller) closes the other two as a side effect of setOpen(true). Closing never cascades. The
+ // hooks stay uncoordinated on purpose — they don't know about each other; only this page,
+ // which owns all three, does.
//
// Docked swaps are SEQUENCED, not simultaneous: with both width transitions running at
// once the total width is constant, so the closing panel's left-anchored content never
@@ -367,19 +376,37 @@ export function ChatPage() {
// they cost height, not width.
/** A visible left/right terminal pane — read BEFORE the flag below starts hiding it. */
const sidePaneShowing = () => visiblePanes().some((p) => p === "left" || p === "right");
+ /**
+ * Tri-panel exclusivity: at most one of the three docked panels is open, so opening one
+ * hard-closes the sibling that is already closed (a no-op) and hands the OPEN sibling to
+ * swapPanels for the sequenced close→open (the collapse-transition dance above). Closing
+ * asks the two siblings whether the side is still held — this panel's own `open` is the
+ * render-time value and still reads true here.
+ */
+ const exclusiveOpen = (
+ self: { setOpen: (v: boolean) => void },
+ siblings: [
+ { open: boolean; isDocked: boolean; setOpen: (v: boolean) => void },
+ { open: boolean; isDocked: boolean; setOpen: (v: boolean) => void },
+ ],
+ ) => {
+ const retracting = sidePaneShowing();
+ setChatSidePanelOpen(true);
+ const [a, b] = siblings;
+ const openSibling = a.open ? a : b;
+ const otherSibling = openSibling === a ? b : a;
+ otherSibling.setOpen(false);
+ swapPanels(openSibling, self.setOpen, retracting);
+ };
const filesPanel: FilesPanelState = {
...filesPanelRaw,
setOpen: (next: boolean) => {
cancelPanelSwap();
if (next) {
- const retracting = sidePaneShowing();
- setChatSidePanelOpen(true);
- swapPanels(subagentsPanelRaw, filesPanelRaw.setOpen, retracting);
+ exclusiveOpen(filesPanelRaw, [subagentsPanelRaw, memoryPanelRaw]);
} else {
filesPanelRaw.setOpen(false);
- // The OTHER panel decides whether the side is still held: this one's `open` is the
- // render-time value and still reads true here.
- setChatSidePanelOpen(subagentsPanelRaw.open);
+ setChatSidePanelOpen(subagentsPanelRaw.open || memoryPanelRaw.open);
}
},
};
@@ -388,17 +415,27 @@ export function ChatPage() {
setOpen: (next: boolean) => {
cancelPanelSwap();
if (next) {
- const retracting = sidePaneShowing();
- setChatSidePanelOpen(true);
- swapPanels(filesPanelRaw, subagentsPanelRaw.setOpen, retracting);
+ exclusiveOpen(subagentsPanelRaw, [filesPanelRaw, memoryPanelRaw]);
} else {
subagentsPanelRaw.setOpen(false);
- setChatSidePanelOpen(filesPanelRaw.open);
+ setChatSidePanelOpen(filesPanelRaw.open || memoryPanelRaw.open);
+ }
+ },
+ };
+ const memoryPanel: MemoryPanelState = {
+ ...memoryPanelRaw,
+ setOpen: (next: boolean) => {
+ cancelPanelSwap();
+ if (next) {
+ exclusiveOpen(memoryPanelRaw, [filesPanelRaw, subagentsPanelRaw]);
+ } else {
+ memoryPanelRaw.setOpen(false);
+ setChatSidePanelOpen(filesPanelRaw.open || subagentsPanelRaw.open);
}
},
};
// The other direction. The store flips this the moment anything puts a terminal on screen
- // (see terminalTakesTheSide), which is the only signal the page needs: retract both panels
+ // (see terminalTakesTheSide), which is the only signal the page needs: retract every panel
// and let the pane render. Edge-triggered, so a panel the user opens is not immediately
// closed again — it sets the flag back on its way up.
useSyncExternalStore(subscribeTerminalDock, dockStateVersion);
@@ -411,6 +448,7 @@ export function ChatPage() {
cancelPanelSwap();
filesPanelRaw.setOpen(false);
subagentsPanelRaw.setOpen(false);
+ memoryPanelRaw.setOpen(false);
// Panel objects are recreated every render; the raw hooks' setters are stable.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [terminalHasTheSide]);
@@ -488,6 +526,45 @@ export function ChatPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
[stream.version, routeSessionId],
);
+ // This conversation's memory changes, aggregated across every visible Task for the Memory
+ // panel and the card (version keys the memo like panelModel). Backfilled windows are read
+ // here too, but each builds its own model, and a model derives rows only once a session_meta
+ // has told it where the Memory root is — so a window that starts mid-shard contributes none
+ // (see collectTaskMemoryChanges).
+ const rawMemoryChanges = useMemo(
+ () =>
+ aggregateMemoryChanges(
+ allItems.flatMap((it) =>
+ it.kind === "task_stats" && it.memoryChanges !== undefined ? [it.memoryChanges] : [],
+ ),
+ ),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [stream.version, routeSessionId],
+ );
+ // Identity-stable view of the rows: the memo above re-derives on EVERY streamed message
+ // (version bumps per tick), but downstream effects — the listing fetch, the detail
+ // refetch — and memos key on the array's identity. Keeping the previous reference while
+ // the content is unchanged is what stops the Memory panel flashing during a streaming
+ // reply; only a settled Task that actually changed memory swaps it.
+ const memoryChangesRef = useRef(rawMemoryChanges);
+ if (!sameMemoryChanges(memoryChangesRef.current, rawMemoryChanges)) {
+ memoryChangesRef.current = rawMemoryChanges;
+ }
+ const sessionMemoryChanges = memoryChangesRef.current;
+ // The Agent's memory listing, fetched once memory is on screen or this conversation has
+ // changes to mark; shared by the Memory panel and the card's deleted-row marking.
+ const memoryListing = useMemoryListing(
+ projectId,
+ selected?.agentId ?? null,
+ memoryPanelRaw.open || sessionMemoryChanges.length > 0,
+ sessionMemoryChanges,
+ );
+ // Changed files the loaded listing no longer carries: the card drops those rows
+ // (undefined while the listing hasn't loaded — "unknown" must not read as "deleted").
+ const deletedMemoryKeys = useMemo(
+ () => deletedChangeKeys(memoryListing.scopes, sessionMemoryChanges) ?? undefined,
+ [memoryListing.scopes, sessionMemoryChanges],
+ );
// The message stream's scroll container, exposed by MessageStream for the outline's
// jump/scrollspy (anchors are queried inside it, never document-wide).
const streamScrollRef = useRef<HTMLDivElement | null>(null);
@@ -518,17 +595,18 @@ export function ChatPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedSessionId, selectedAgentId, setCurrentAgentId]);
- // A NEW chat starts with both panels closed: a panel opened for an earlier conversation must
+ // A NEW chat starts with every panel closed: a panel opened for an earlier conversation must
// not carry into a freshly created one. The draft is the reset point — it renders no panels
// itself, so the Session created from it (first send navigates to /chat/:id) begins closed,
// while a plain conversation switch keeps whatever the user had open. This effect owns the
- // ONLY automatic close of either panel.
+ // ONLY automatic close of any of them.
useEffect(() => {
if (!draft) return;
// A swap's pending delayed open must not fire into the fresh draft after this reset.
cancelPanelSwap();
filesPanelRaw.setOpen(false);
subagentsPanelRaw.setOpen(false);
+ memoryPanelRaw.setOpen(false);
setChatSidePanelOpen(false); // nothing holds the side any more: side panes come back
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [draft]);
@@ -560,7 +638,8 @@ export function ChatPage() {
action === "autoOpen" &&
subagentsPanelRaw.isDocked &&
!subagentsPanelRaw.open &&
- !filesPanelRaw.open
+ !filesPanelRaw.open &&
+ !memoryPanelRaw.open
) {
setChatSidePanelOpen(true);
subagentsPanelRaw.setOpen(true);
@@ -1441,17 +1520,31 @@ export function ChatPage() {
// The file card has already normalized the text path to a Workspace-relative path
// (toWorkspaceRelative, including stripping absolute-path prefixes and converting Windows
// separators), so this just opens the panel and navigates to it directly (the wrapped
- // setOpen already closes the subagents panel — see the exclusivity block above).
+ // setOpen already closes the sibling panels — see the exclusivity block above).
filesPanel.setOpen(true);
filesPanel.browsePath(path);
},
onOpenSubagent: (sessionId, origin) => {
// Chip click: open the panel focused on that child (the focus chain ends with the child's
- // own id; the wrapped setOpen closes the Files panel). focusSubagent after setOpen: the
+ // own id; the wrapped setOpen closes the sibling panels). focusSubagent after setOpen: the
// open resets the Task scope to "latest", and the focus then pins it to this chip's Task.
subagentsPanel.setOpen(true);
subagentsPanel.focusSubagent(sessionId, [...origin, sessionId]);
},
+ onOpenMemory: () => {
+ // The Memory panel on its list (the wrapped setOpen closes the sibling panels).
+ memoryPanel.setOpen(true);
+ memoryPanelRaw.openMemory(null);
+ },
+ onLocateMemoryChange: (row) => {
+ memoryPanel.setOpen(true);
+ memoryPanelRaw.openMemory({
+ scope: row.scope,
+ ...(row.scopeKey !== undefined ? { scopeKey: row.scopeKey } : {}),
+ file: row.file,
+ });
+ },
+ ...(deletedMemoryKeys !== undefined ? { deletedMemoryKeys } : {}),
workspace: selected?.workspace ?? null,
statFiles,
onFork,
@@ -1619,8 +1712,9 @@ export function ChatPage() {
{/* Panel switcher (icon-only): pinned panel triggers + the "all panels" dropdown
with per-panel pin toggles. Subagents panel docks the latest-Task call graph
- (use-subagents-panel.ts), Workspace docks the files panel (use-files-panel.ts) —
- opening either closes the other (wrapped setOpen) — and the terminal toggles the
+ (use-subagents-panel.ts), Workspace docks the files panel (use-files-panel.ts),
+ Memory docks the two-level memory view (use-memory-panel.ts) — opening any of the
+ three closes the other two (wrapped setOpen) — and the terminal toggles the
app-wide dock (terminal-dock.tsx). */}
<PanelsToolbar
agentsOpen={subagentsPanel.open}
@@ -1628,6 +1722,16 @@ export function ChatPage() {
agentsPending={anySubagentPending}
workspaceOpen={filesPanel.open}
onToggleWorkspace={() => filesPanel.setOpen(!filesPanel.open)}
+ memoryOpen={memoryPanel.open}
+ onToggleMemory={() => {
+ if (memoryPanel.open) {
+ memoryPanel.setOpen(false);
+ } else {
+ // Toolbar entry lands on the list level (memory-nav entry routing).
+ memoryPanel.setOpen(true);
+ memoryPanelRaw.openMemory(null);
+ }
+ }}
/>
{/* Conversation index fallback: exactly when the gutter tick rail can't show
@@ -2002,6 +2106,17 @@ export function ChatPage() {
/>
)}
{selected && <FilesPanel session={selected} panel={filesPanel} />}
+ {selected && (
+ <MemoryPanel
+ session={selected}
+ panel={memoryPanel}
+ memoryChanges={sessionMemoryChanges}
+ scopes={memoryListing.scopes}
+ listingError={memoryListing.error}
+ // Management (add / edit / delete) lives on the agent-settings memory tab.
+ onOpenMemorySettings={() => navigate(`/agents/${selected.agentId}?tab=memory`)}
+ />
+ )}
<TerminalDockSlot position="right" />
</div>
diff --git a/packages/web/src/features/chat/memory-changes-card.tsx b/packages/web/src/features/chat/memory-changes-card.tsx
new file mode 100644
index 00000000..b77a0de4
--- /dev/null
+++ b/packages/web/src/features/chat/memory-changes-card.tsx
@@ -0,0 +1,131 @@
+/**
+ * Memory-change summary card, rendered right below the file-summary card at the end of a
+ * root Task (same visual family): one row per memory topic file the Task changed through
+ * the structured file tools, derived by the stream model (TaskStatsItem.memoryChanges —
+ * see lib/omni/memory-changes.ts for what qualifies and what is filtered).
+ *
+ * Clicking a row opens the Memory side panel directly on that memory's content; the
+ * header's book button opens the panel on its list. A changed file that was deleted in a
+ * later turn is filtered out (deletedKeys) — the row disappears here just as it does from
+ * the panel's list; the whole card hides when nothing survives.
+ */
+import { useState } from "react";
+import { S } from "../../lib/strings";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { Chevron } from "../../components/ui/chevron";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import type { MemoryChangeRow } from "../../lib/omni/memory-changes";
+import { memoryRowKey } from "../../lib/omni/memory-changes";
+import { PathLabel } from "./message-files-card";
+import { scopeGlyph } from "./memory-view";
+
+const MAX_VISIBLE = 3;
+
+/** Open book (the card's mark, same as the Memory panel's), page-with-plus (full write), pencil (in-place edit). */
+const MEMORY_ICON =
+ "M4 19.5A2.5 2.5 0 0 1 6.5 17H20M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z";
+const WRITE_ICON = "M6 3h8l4 4v14H6zM12 11v6M9 14h6";
+const EDIT_ICON = "M12 20h9M16.5 3.5a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z";
+
+export function MemoryChangesCard({
+ rows,
+ deletedKeys,
+ onLocateChange,
+ onOpenPanel,
+}: {
+ rows: MemoryChangeRow[];
+ /** Keys (memoryRowKey) of changed files that no longer exist: those rows are filtered out. Absent = the listing hasn't loaded, which must not read as deleted — everything shows. */
+ deletedKeys?: ReadonlySet<string>;
+ /** Row click: open the Memory panel on this row's content; rows render as plain rows if this isn't wired up. */
+ onLocateChange?: (row: MemoryChangeRow) => void;
+ /** Header button: open the Memory panel on its list; the button doesn't render if this isn't wired up. */
+ onOpenPanel?: () => void;
+}) {
+ const [expanded, setExpanded] = useState(false);
+ const alive = deletedKeys ? rows.filter((row) => !deletedKeys.has(memoryRowKey(row))) : rows;
+ if (alive.length === 0) return null;
+
+ const visible = expanded ? alive : alive.slice(0, MAX_VISIBLE);
+ const hidden = alive.length - visible.length;
+
+ const rowInner = (row: MemoryChangeRow) => {
+ const glyph = scopeGlyph(row.scope, row.scopeKey);
+ return (
+ <>
+ <span title={glyph.title} className="shrink-0 text-gray-400">
+ <GlyphIcon d={glyph.d} size={ICON_SIZE.rowLead} />
+ <span className="sr-only">{glyph.title}</span>
+ </span>
+ <PathLabel path={row.file} />
+ <span className="min-w-0 flex-1" />
+ <span
+ title={row.op === "write" ? S.chat.memoryOpWrite : S.chat.memoryOpEdit}
+ className="shrink-0 text-gray-400"
+ >
+ <GlyphIcon d={row.op === "write" ? WRITE_ICON : EDIT_ICON} size={ICON_SIZE.inlineGlyph} />
+ </span>
+ </>
+ );
+ };
+
+ return (
+ <div className="anim-msg my-3 overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
+ {/* Header bar, mirroring the file-summary card: "icon + N memory updates", plus the one
+ card-level action (rows navigate to their own content, so this doesn't duplicate them). */}
+ <div className="flex items-center gap-2 border-b border-gray-100 bg-gray-50 px-3 py-2 dark:border-gray-800/60 dark:bg-gray-800/40">
+ <GlyphIcon d={MEMORY_ICON} size={ICON_SIZE.rowLead} className="shrink-0 text-gray-400" />
+ <span className="min-w-0 flex-1 truncate text-sm font-medium">
+ {S.chat.memoryChangesTitle(alive.length)}
+ </span>
+ {onOpenPanel && (
+ <button
+ type="button"
+ title={S.chat.memoryViewTitle}
+ onClick={onOpenPanel}
+ className="flex h-6 w-6 shrink-0 cursor-pointer items-center justify-center text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:hover:text-gray-300"
+ >
+ <GlyphIcon d={MEMORY_ICON} size={ICON_SIZE.inlineGlyph} />
+ <span className="sr-only">{S.chat.memoryViewTitle}</span>
+ </button>
+ )}
+ </div>
+ <div className="divide-y divide-gray-100 dark:divide-gray-800/60">
+ {visible.map((row) => {
+ const key = memoryRowKey(row);
+ return onLocateChange ? (
+ <button
+ key={key}
+ type="button"
+ title={S.chat.memoryRowOpen}
+ onClick={() => onLocateChange(row)}
+ className="group flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50"
+ >
+ {rowInner(row)}
+ {/* Right-aligned action hint, the file card's affordance (span, not a nested button: the row itself is the button). */}
+ <span
+ aria-hidden
+ className="shrink-0 text-xs text-gray-400 transition-colors duration-150 group-hover:text-gray-600 dark:text-gray-500 dark:group-hover:text-gray-300"
+ >
+ {S.chat.memoryRowOpen}
+ </span>
+ </button>
+ ) : (
+ <div key={key} className="flex w-full items-center gap-2 px-3 py-2">
+ {rowInner(row)}
+ </div>
+ );
+ })}
+ {(hidden > 0 || expanded) && alive.length > MAX_VISIBLE && (
+ <button
+ type="button"
+ onClick={() => setExpanded((v) => !v)}
+ className="flex w-full items-center gap-1.5 px-3 py-2 text-left text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-50 dark:text-gray-400 dark:hover:bg-gray-800/50"
+ >
+ {expanded ? S.chat.showLess : S.chat.memoryShowMore(hidden)}
+ <Chevron open={expanded} className="text-gray-400" size={ICON_SIZE.chevronDense} />
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/chat/memory-nav.ts b/packages/web/src/features/chat/memory-nav.ts
new file mode 100644
index 00000000..55916d94
--- /dev/null
+++ b/packages/web/src/features/chat/memory-nav.ts
@@ -0,0 +1,144 @@
+/**
+ * Navigation model and list view-model for the Memory side panel (pure; the component in
+ * memory-view.tsx just renders these).
+ *
+ * Two levels: the list (both scopes' topic lists, changed topics marked) and one memory's
+ * detail (its content, rendered like the file viewer). Entry routes by where the user came
+ * from: a memory-changes card row carries a locate target and lands directly on that
+ * memory's detail; entering through the panel toggle (or any entry without a target) lands
+ * on the list. Back always returns to the list.
+ */
+import type { MemoryFileInfo, MemoryScopeInfo } from "@prismshadow/penguin-server/api";
+import type {
+ MemoryChangeOp,
+ MemoryChangeRow,
+ MemoryLocateTarget,
+} from "../../lib/omni/memory-changes";
+import { memoryRowKey } from "../../lib/omni/memory-changes";
+
+export type MemoryNavMode = { kind: "list" } | { kind: "detail"; target: MemoryLocateTarget };
+
+/** Entry routing: a request with a target goes straight to that memory's detail; no target (panel toggle, card header) shows the list. */
+export function memoryNavForRequest(
+ request: { target: MemoryLocateTarget | null } | null,
+): MemoryNavMode {
+ return request?.target != null ? { kind: "detail", target: request.target } : { kind: "list" };
+}
+
+/** The detail view's back button: always the list. */
+export function memoryNavBack(): MemoryNavMode {
+ return { kind: "list" };
+}
+
+/** One scope's server listing, as chat-page loads it (use-memory-listing). */
+export interface ScopeFiles {
+ info: MemoryScopeInfo;
+ files: MemoryFileInfo[];
+}
+
+/** One list-view row: a topic file. */
+export interface MemoryListRow {
+ target: MemoryLocateTarget;
+ /** Listing title (frontmatter `name`), or the file path while the listing hasn't loaded. */
+ title: string;
+ description?: string;
+ /** Frontmatter `updated_at` verbatim / file mtime (ISO); both absent on change-derived rows. */
+ updatedAt?: string;
+ modifiedAt?: string;
+ /** Set when this conversation changed the topic (the marker + its tooltip). */
+ changed?: MemoryChangeOp;
+}
+
+export interface MemoryListGroup {
+ scope: "user" | "workspace";
+ scopeKey: string;
+ workspacePath?: string;
+ rows: MemoryListRow[];
+}
+
+/** The row's target within its group's scope. */
+function targetOf(
+ group: { scope: "user" | "workspace"; scopeKey: string },
+ file: string,
+): MemoryLocateTarget {
+ return group.scope === "user"
+ ? { scope: "user", file }
+ : { scope: "workspace", scopeKey: group.scopeKey, file };
+}
+
+/**
+ * The list view's groups. With the listing loaded, its rows are the list — a changed topic
+ * gets its marker, and a changed file the listing no longer carries was deleted afterwards,
+ * so it simply doesn't appear. While the listing hasn't loaded (null), the groups come from
+ * the changes alone: "not loaded yet" must not be mistaken for "deleted".
+ */
+export function buildMemoryList(
+ scopes: readonly ScopeFiles[] | null,
+ changes: readonly MemoryChangeRow[],
+): MemoryListGroup[] {
+ if (scopes === null) {
+ const groups: MemoryListGroup[] = [];
+ for (const change of changes) {
+ const scopeKey = change.scope === "user" ? "user" : (change.scopeKey ?? "");
+ let group = groups.find((g) => g.scope === change.scope && g.scopeKey === scopeKey);
+ if (group === undefined) {
+ group = { scope: change.scope, scopeKey, rows: [] };
+ if (change.scope === "user") groups.unshift(group);
+ else groups.push(group);
+ }
+ group.rows.push({
+ target: targetOf(group, change.file),
+ title: change.file,
+ changed: change.op,
+ });
+ }
+ return groups;
+ }
+
+ const changedByKey = new Map(changes.map((c) => [memoryRowKey(c), c.op] as const));
+ return scopes.map(({ info, files }) => {
+ const group: MemoryListGroup = {
+ scope: info.kind,
+ scopeKey: info.scopeKey,
+ ...(info.workspacePath !== undefined ? { workspacePath: info.workspacePath } : {}),
+ rows: [],
+ };
+ for (const f of files) {
+ const target = targetOf(group, f.name);
+ const changed = changedByKey.get(memoryRowKey(target));
+ group.rows.push({
+ target,
+ title: f.title,
+ ...(f.description !== "" ? { description: f.description } : {}),
+ ...(f.updatedAt !== undefined ? { updatedAt: f.updatedAt } : {}),
+ modifiedAt: f.modifiedAt,
+ ...(changed !== undefined ? { changed } : {}),
+ });
+ }
+ return group;
+ });
+}
+
+/**
+ * Keys (memoryRowKey) of changed files the loaded listing no longer carries — they were
+ * deleted after the change, so their entries are filtered out of the memory-changes card
+ * (the panel list drops them by construction, see buildMemoryList). Null while the listing
+ * hasn't loaded: "not loaded yet" must not be mistaken for "deleted".
+ */
+export function deletedChangeKeys(
+ scopes: readonly ScopeFiles[] | null,
+ changes: readonly MemoryChangeRow[],
+): ReadonlySet<string> | null {
+ if (scopes === null) return null;
+ const listed = new Set<string>();
+ for (const { info, files } of scopes) {
+ const group = { scope: info.kind, scopeKey: info.scopeKey };
+ for (const f of files) listed.add(memoryRowKey(targetOf(group, f.name)));
+ }
+ const deleted = new Set<string>();
+ for (const change of changes) {
+ const key = memoryRowKey(change);
+ if (!listed.has(key)) deleted.add(key);
+ }
+ return deleted;
+}
diff --git a/packages/web/src/features/chat/memory-panel.tsx b/packages/web/src/features/chat/memory-panel.tsx
new file mode 100644
index 00000000..7263386c
--- /dev/null
+++ b/packages/web/src/features/chat/memory-panel.tsx
@@ -0,0 +1,109 @@
+/**
+ * Memory panel — a peer of the subagents and files panels, same shell behavior: docked to
+ * the right with a drag-to-resize edge on desktop (≥1024px, see isDocked in
+ * use-memory-panel.ts), a bottom Sheet on narrower viewports. Content is the two-level
+ * Memory view (memory-view.tsx); the panel itself only provides the frame, mirroring
+ * files-panel.tsx — including the inert width-collapse (see that file's notes on why the
+ * node stays mounted and why the divider belongs to the open state only).
+ */
+import type { SessionInfo } from "@prismshadow/penguin-server/api";
+import { S } from "../../lib/strings";
+import { Sheet } from "../../components/ui/sheet";
+import { CloseIcon } from "../../components/ui/icons";
+import type { MemoryChangeRow } from "../../lib/omni/memory-changes";
+import { ChatMemoryView } from "./memory-view";
+import type { ScopeFiles } from "./memory-nav";
+import type { MemoryPanelState } from "./use-memory-panel";
+
+interface MemoryPanelProps {
+ session: SessionInfo;
+ panel: MemoryPanelState;
+ /** This conversation's aggregated memory changes (identity-stable across streaming ticks — see chat-page's stabilization). */
+ memoryChanges: MemoryChangeRow[];
+ /** The server listing (loaded by chat-page's use-memory-listing) and its error, shared with the card's deleted-row marking. */
+ scopes: ScopeFiles[] | null;
+ listingError: string | null;
+ /** Opens the agent-settings memory tab (the view's management link). */
+ onOpenMemorySettings?: (() => void) | undefined;
+}
+
+export function MemoryPanel({
+ session,
+ panel,
+ memoryChanges,
+ scopes,
+ listingError,
+ onOpenMemorySettings,
+}: MemoryPanelProps) {
+ const view = (
+ // Keyed by session: a new conversation starts back at the list level.
+ <ChatMemoryView
+ key={session.sessionId}
+ session={session}
+ changes={memoryChanges}
+ scopes={scopes}
+ listingError={listingError}
+ request={panel.memoryRequest}
+ active={panel.open}
+ {...(onOpenMemorySettings ? { onOpenSettings: onOpenMemorySettings } : {})}
+ />
+ );
+
+ if (!panel.isDocked) {
+ return (
+ <Sheet
+ open={panel.open}
+ snap={panel.sheetSnap}
+ onSnapChange={panel.setSheetSnap}
+ onClose={() => panel.setOpen(false)}
+ title={S.chat.memoryViewTitle}
+ >
+ <div className="flex h-full min-h-0 flex-col">
+ <div className="min-h-0 flex-1">{view}</div>
+ </div>
+ </Sheet>
+ );
+ }
+
+ return (
+ <>
+ {panel.open && (
+ <div
+ data-testid="memory-panel-resizer"
+ onMouseDown={panel.startResize}
+ onDoubleClick={panel.resetWidth}
+ title={S.files.resizeHandle}
+ className={`w-1.5 shrink-0 cursor-col-resize transition-colors duration-150 hover:bg-brand-300/50 dark:hover:bg-brand-700/40 ${
+ panel.resizing ? "bg-brand-400/60" : "bg-transparent"
+ }`}
+ />
+ )}
+ <div
+ data-testid="memory-panel"
+ ref={panel.panelRef}
+ style={{ width: panel.open ? panel.width : 0 }}
+ inert={!panel.open}
+ className={`relative flex min-h-0 shrink-0 flex-col overflow-hidden ${
+ panel.open ? "border-l border-gray-200 dark:border-gray-800" : ""
+ } ${panel.resizing ? "pointer-events-none" : "transition-[width] duration-200"}`}
+ >
+ <div style={{ width: panel.width }} className="flex h-full min-h-0 flex-col">
+ <div className="flex shrink-0 items-center gap-1 px-3 pt-2">
+ <h4 className="min-w-0 flex-1 truncate text-sm font-semibold">
+ {S.chat.memoryViewTitle}
+ </h4>
+ <button
+ type="button"
+ onClick={() => panel.setOpen(false)}
+ title={S.common.close}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <CloseIcon />
+ </button>
+ </div>
+ <div className="min-h-0 flex-1">{view}</div>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/packages/web/src/features/chat/memory-view.tsx b/packages/web/src/features/chat/memory-view.tsx
new file mode 100644
index 00000000..f5e2e7e3
--- /dev/null
+++ b/packages/web/src/features/chat/memory-view.tsx
@@ -0,0 +1,280 @@
+/**
+ * The Memory side panel's content (see memory-panel.tsx for the shell): two levels, modeled
+ * by memory-nav.ts. The list shows both scopes' topic lists — the same server routes the
+ * agent-settings memory tab reads — with a marker on topics this conversation changed; a
+ * topic's detail is the memory's content rendered like the file viewer (Markdown,
+ * frontmatter stripped — the header already shows those fields). A file deleted after being
+ * changed simply leaves the list (buildMemoryList); the unavailable note below only covers
+ * the race where the file disappears between the listing load and the click.
+ *
+ * Entry routes by origin: a memory-changes card row lands directly on that memory's detail;
+ * entering through the panel toggle lands on the list. Management (add / edit / delete)
+ * stays on the agent-settings tab — the list header links there — so this view never
+ * duplicates the bridge-modal flows.
+ */
+import { useEffect, useState } from "react";
+import type { SessionInfo } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { formatRelativeDate } from "../../lib/format";
+import { bodyWithoutFrontmatter } from "../../lib/frontmatter";
+import type { MemoryChangeRow, MemoryLocateTarget } from "../../lib/omni/memory-changes";
+import { memoryRowKey } from "../../lib/omni/memory-changes";
+import { useLocale } from "../../state/locale";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { SkeletonList } from "../../components/ui/skeleton";
+import { Md } from "./md";
+import { buildMemoryList, memoryNavBack, memoryNavForRequest } from "./memory-nav";
+import type { MemoryNavMode, ScopeFiles } from "./memory-nav";
+
+/** Person (User scope), folder (Workspace scope), boxed arrow (open the settings tab), left arrow (back to the list). */
+const USER_ICON = "M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M12 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8z";
+const FOLDER_ICON = "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z";
+const OPEN_SETTINGS_ICON =
+ "M14 4h6v6M20 4 10 14M9 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-3";
+const BACK_ICON = "M19 12H5m6-6-6 6 6 6";
+
+/** The scope glyph + tooltip pair, shared with the memory-changes card's rows. */
+export function scopeGlyph(scope: "user" | "workspace", scopeKey?: string) {
+ return {
+ d: scope === "user" ? USER_ICON : FOLDER_ICON,
+ title: scope === "user" ? S.memory.userScope : S.chat.memoryScopeWorkspace(scopeKey ?? ""),
+ };
+}
+
+/** List-group title: the User scope's fixed label, or the Workspace directory's basename. */
+function groupTitle(group: {
+ scope: "user" | "workspace";
+ scopeKey: string;
+ workspacePath?: string;
+}): string {
+ return group.scope === "user"
+ ? S.memory.userScope
+ : (group.workspacePath?.split(/[\\/]/).filter(Boolean).at(-1) ?? group.scopeKey);
+}
+
+export function ChatMemoryView({
+ session,
+ changes,
+ scopes,
+ listingError,
+ request,
+ active,
+ onOpenSettings,
+}: {
+ session: SessionInfo;
+ /** This conversation's aggregated memory changes (identity-stable — chat-page only swaps the array when the content moved). */
+ changes: MemoryChangeRow[];
+ /** The server listing, loaded by chat-page's use-memory-listing; null = not loaded. */
+ scopes: ScopeFiles[] | null;
+ listingError: string | null;
+ /** Navigation command from openMemory (object identity re-triggers): with a target it lands on that memory's detail, without one on the list. */
+ request: { target: MemoryLocateTarget | null } | null;
+ /** Whether the panel is showing (detail loading waits for it). */
+ active: boolean;
+ /** Opens the agent-settings memory tab, where management (add / edit / delete) lives. */
+ onOpenSettings?: () => void;
+}) {
+ const { locale } = useLocale();
+
+ // ---- navigation (memory-nav.ts): entry routing + back ----
+ const [mode, setMode] = useState<MemoryNavMode>({ kind: "list" });
+ // Landing on a located memory just shows its content — no highlight, no transient tint —
+ // the same arrival the file-summary card's rows give (they only preview the file).
+ useEffect(() => {
+ if (request === null) return;
+ setMode(memoryNavForRequest(request));
+ }, [request]);
+
+ // ---- detail content (loaded per target; keyed so a stale response can't cross targets) ----
+ const detailKey = mode.kind === "detail" ? memoryRowKey(mode.target) : null;
+ const [detail, setDetail] = useState<{
+ key: string;
+ content: string | null;
+ failed: boolean;
+ } | null>(null);
+ useEffect(() => {
+ if (!active || mode.kind !== "detail") return;
+ const target = mode.target;
+ const key = memoryRowKey(target);
+ let cancelled = false;
+ setDetail({ key, content: null, failed: false });
+ void api
+ .getMemoryFile(
+ session.projectId,
+ session.agentId,
+ target.scope === "user" ? "user" : (target.scopeKey ?? ""),
+ target.file,
+ )
+ .then((res) => {
+ if (!cancelled) setDetail({ key, content: res.content, failed: false });
+ })
+ .catch(() => {
+ if (!cancelled) setDetail({ key, content: null, failed: true });
+ });
+ return () => {
+ cancelled = true;
+ };
+ // detailKey stands in for mode.target's identity; changes refresh a just-rewritten file
+ // (identity-stable, so streaming ticks never re-fire this).
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [active, detailKey, session.projectId, session.agentId, changes]);
+
+ const groups = buildMemoryList(scopes, changes);
+
+ // ---- detail level ----
+ if (mode.kind === "detail") {
+ const target = mode.target;
+ const listedRow = groups
+ .flatMap((g) => g.rows)
+ .find((r) => memoryRowKey(r.target) === detailKey);
+ const loaded = detail !== null && detail.key === detailKey;
+ const glyph = scopeGlyph(target.scope, target.scopeKey);
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ <div className="flex shrink-0 items-center gap-2 border-b border-gray-100 px-3 py-2 dark:border-gray-800/60">
+ <button
+ type="button"
+ onClick={() => setMode(memoryNavBack())}
+ title={S.chat.memoryBack}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <GlyphIcon d={BACK_ICON} size={ICON_SIZE.iconButton} />
+ <span className="sr-only">{S.chat.memoryBack}</span>
+ </button>
+ <span title={glyph.title} className="shrink-0 text-gray-400">
+ <GlyphIcon d={glyph.d} size={ICON_SIZE.rowLead} />
+ <span className="sr-only">{glyph.title}</span>
+ </span>
+ <p className="min-w-0 flex-1 truncate font-mono text-[13px] font-semibold">
+ {listedRow?.title ?? target.file}
+ </p>
+ {listedRow &&
+ (listedRow.updatedAt !== undefined || listedRow.modifiedAt !== undefined) && (
+ <span className="shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500">
+ {listedRow.updatedAt ??
+ (listedRow.modifiedAt !== undefined
+ ? formatRelativeDate(listedRow.modifiedAt, locale)
+ : "")}
+ </span>
+ )}
+ </div>
+ <div className="min-h-0 flex-1 space-y-3 overflow-y-auto px-3.5 py-3">
+ {listedRow?.description !== undefined && (
+ <p className="text-xs text-gray-500 dark:text-gray-400">{listedRow.description}</p>
+ )}
+ {!loaded || (!detail.failed && detail.content === null) ? (
+ <SkeletonList rows={3} />
+ ) : detail.failed ? (
+ <p className="text-xs text-gray-400 dark:text-gray-500">
+ {S.chat.memoryContentUnavailable}
+ </p>
+ ) : (
+ <div className="md-body text-sm">
+ <Md text={bodyWithoutFrontmatter(detail.content ?? "")} />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ // ---- list level ----
+ return (
+ <div className="h-full min-h-0 overflow-y-auto">
+ <div className="flex items-center gap-1 px-3.5 pb-1 pt-2">
+ <span className="min-w-0 flex-1" />
+ {onOpenSettings && (
+ // Labelled, not a bare glyph: the arrow says the click leaves this panel, the text
+ // says where it lands, and nobody has to hover to find that out. `title` repeats the
+ // label verbatim rather than expanding on it, so the accessible name matches the
+ // visible one. The label fits the shared width's 320px minimum; past that (a larger
+ // text size) it truncates instead of pushing the row wider.
+ <button
+ type="button"
+ onClick={onOpenSettings}
+ title={S.chat.openAgentMemory}
+ className="flex min-w-0 cursor-pointer items-center gap-1 rounded-md px-1.5 py-1 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <GlyphIcon d={OPEN_SETTINGS_ICON} size={ICON_SIZE.inlineGlyph} />
+ <span className="truncate">{S.chat.openAgentMemory}</span>
+ </button>
+ )}
+ </div>
+ {listingError !== null && groups.length === 0 ? (
+ <p className="px-3.5 py-2 text-xs text-gray-500 dark:text-gray-400">{listingError}</p>
+ ) : scopes === null && groups.length === 0 ? (
+ <div className="px-3.5 py-2">
+ <SkeletonList rows={3} />
+ </div>
+ ) : groups.every((g) => g.rows.length === 0) ? (
+ <p className="px-3.5 py-2 text-xs text-gray-400 dark:text-gray-500">
+ {S.chat.memoryEmptyAll}
+ </p>
+ ) : (
+ groups.map((group) =>
+ group.rows.length === 0 ? null : (
+ <div key={`${group.scope} ${group.scopeKey}`} className="pb-2">
+ <div className="flex items-center gap-2 px-3.5 py-1.5">
+ <span className="shrink-0 text-gray-400">
+ <GlyphIcon
+ d={group.scope === "user" ? USER_ICON : FOLDER_ICON}
+ size={ICON_SIZE.inlineGlyph}
+ />
+ </span>
+ <p
+ className="min-w-0 flex-1 truncate text-xs text-gray-500 dark:text-gray-400"
+ title={group.workspacePath}
+ >
+ {groupTitle(group)}
+ </p>
+ <span className="shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500">
+ {S.memory.itemCount(group.rows.length)}
+ </span>
+ </div>
+ <ul>
+ {group.rows.map((row) => (
+ <li key={memoryRowKey(row.target)}>
+ <button
+ type="button"
+ onClick={() => setMode({ kind: "detail", target: row.target })}
+ className="flex w-full cursor-pointer items-center gap-3 px-3.5 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50"
+ >
+ <div className="min-w-0 flex-1">
+ <p className="flex items-center gap-1.5 truncate font-mono text-[13px] font-medium text-gray-800 dark:text-gray-200">
+ {row.changed !== undefined && (
+ <span
+ title={S.chat.memoryChangedMark}
+ className="h-1.5 w-1.5 shrink-0 rounded-full bg-brand-500"
+ >
+ <span className="sr-only">{S.chat.memoryChangedMark}</span>
+ </span>
+ )}
+ <span className="min-w-0 truncate">{row.title}</span>
+ </p>
+ {row.description !== undefined && (
+ <p className="truncate text-xs text-gray-500 dark:text-gray-400">
+ {row.description}
+ </p>
+ )}
+ </div>
+ {(row.updatedAt !== undefined || row.modifiedAt !== undefined) && (
+ <span className="shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500">
+ {row.updatedAt ??
+ (row.modifiedAt !== undefined
+ ? formatRelativeDate(row.modifiedAt, locale)
+ : "")}
+ </span>
+ )}
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ),
+ )
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/features/chat/message-files-card.tsx b/packages/web/src/features/chat/message-files-card.tsx
index d384f619..6bc6ff56 100644
--- a/packages/web/src/features/chat/message-files-card.tsx
+++ b/packages/web/src/features/chat/message-files-card.tsx
@@ -39,8 +39,9 @@ export function extractFilePaths(markdown: string): string[] {
/** Path split into segments: directory prefix faded, filename bold (Codex-style). The directory
* segment has shrink-[9999] and collapses first, the filename segment truncates only after —
- * both segments are truncatable, so the row never overflows its container on a narrow panel. */
-function PathLabel({ path }: { path: string }) {
+ * both segments are truncatable, so the row never overflows its container on a narrow panel.
+ * Shared with the memory-changes card, which renders the same row family. */
+export function PathLabel({ path }: { path: string }) {
const slash = path.lastIndexOf("/");
const dir = slash >= 0 ? path.slice(0, slash + 1) : "";
const name = slash >= 0 ? path.slice(slash + 1) : path;
diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsx
index fd16858a..ae77983e 100644
--- a/packages/web/src/features/chat/message-item.tsx
+++ b/packages/web/src/features/chat/message-item.tsx
@@ -16,6 +16,7 @@ import { GlyphIcon } from "../../components/ui/glyph-icon";
import { CopyButton } from "../../components/ui/copy-button";
import { ZoomableImage } from "../../components/ui/image-zoom";
import { MessageFilesCard } from "./message-files-card";
+import { MemoryChangesCard } from "./memory-changes-card";
import { ThinkingBlock } from "./thinking-block";
import { ToolCallCard } from "./tool-call-card";
import { SubagentChip } from "./subagent-chip";
@@ -385,6 +386,17 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo
onOpenFile={ctx.onOpenFile}
/>
)}
+ {/* Memory changes sit below the file list: same Task-level summary, but sourced from
+ the structured tool record (stream model) rather than the reply text, so it also
+ renders when the reply never named the files. */}
+ {ctx.origin.length === 0 && item.memoryChanges !== undefined && (
+ <MemoryChangesCard
+ rows={item.memoryChanges}
+ {...(ctx.deletedMemoryKeys ? { deletedKeys: ctx.deletedMemoryKeys } : {})}
+ {...(ctx.onLocateMemoryChange ? { onLocateChange: ctx.onLocateMemoryChange } : {})}
+ {...(ctx.onOpenMemory ? { onOpenPanel: ctx.onOpenMemory } : {})}
+ />
+ )}
<TaskStatsLine
stats={item.stats}
assistantText={item.assistantText}
diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsx
index 7e3e4d8a..ad3b4a7f 100644
--- a/packages/web/src/features/chat/message-stream.tsx
+++ b/packages/web/src/features/chat/message-stream.tsx
@@ -9,6 +9,7 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react";
import type { ReactNode, RefObject } from "react";
import { S } from "../../lib/strings";
import type { ChatItem } from "../../lib/omni/stream-model";
+import type { MemoryChangeRow } from "../../lib/omni/memory-changes";
import type { TaskStats } from "../../lib/omni/task-stats";
import type { PendingApproval } from "./use-session-stream";
import { EmptyState } from "../../components/ui/empty-state";
@@ -46,6 +47,12 @@ export interface StreamRenderContext {
onOpenFile?: (path: string) => void;
/** Opens the subagents panel focused on this child session (subagent chip click); `origin` is the ctx.origin at the chip's render level — the child's ancestor chain, excluding its own id. */
onOpenSubagent?: (sessionId: string, origin: string[]) => void;
+ /** Opens the Memory panel on its list (memory-changes card header); the button doesn't render if this isn't wired up. */
+ onOpenMemory?: () => void;
+ /** Opens the Memory panel on this row's memory content (memory-changes card row click); rows render inert if this isn't wired up. */
+ onLocateMemoryChange?: (row: MemoryChangeRow) => void;
+ /** Keys of changed memory files that no longer exist (deleted after the change): the card drops those rows. Absent while the listing hasn't loaded. */
+ deletedMemoryKeys?: ReadonlySet<string>;
/** Absolute Workspace path of the current Session (used by the file-summary card to normalize body paths). */
workspace?: string | null;
/** Batch file-existence check (with session-level caching); the card doesn't render if this isn't wired up. */
diff --git a/packages/web/src/features/chat/panels-toolbar.tsx b/packages/web/src/features/chat/panels-toolbar.tsx
index 7c1b697f..60300b6f 100644
--- a/packages/web/src/features/chat/panels-toolbar.tsx
+++ b/packages/web/src/features/chat/panels-toolbar.tsx
@@ -2,11 +2,11 @@
* Top-right panel switcher of the chat toolbar (Codex-style): icon-only buttons for the
* pinned panels, then an "all panels" dropdown listing every panel with icon + name.
*
- * Three panels exist: the subagents panel ("智能体面板"), the terminal dock and the
- * Workspace files panel. Which of them get their own toolbar icon is user-configurable via
- * the pin toggles inside the dropdown (persisted per browser); the default pins the
- * subagents panel and the Workspace, leaving the terminal reachable through the dropdown
- * (or Ctrl+`) until pinned.
+ * Four panels exist: the subagents panel, the terminal dock, the Workspace files panel and
+ * the Memory panel. Which of them get their own toolbar icon is user-configurable via the
+ * pin toggles inside the dropdown (persisted per browser); the default pins the subagents
+ * panel and the Workspace, leaving the terminal and Memory reachable through the dropdown
+ * (the terminal also via Ctrl+`) until pinned.
*
* The open/close state itself lives with each panel's own hook/store — this component only
* renders triggers, so pinning/unpinning never touches panel state.
@@ -30,12 +30,16 @@ import { displayTitle, useTerminalDockOpen } from "../terminal/terminal-dock";
import { liveTerminals, subscribeTerminals, terminalApiSupported } from "../terminal/terminal-list";
import { toneDot } from "../../lib/tone";
-export type PanelKey = "agents" | "terminal" | "workspace";
+export type PanelKey = "agents" | "terminal" | "workspace" | "memory";
const PIN_STORAGE_KEY = "penguin.chat.pinnedPanels";
const DEFAULT_PINS: readonly PanelKey[] = ["agents", "workspace"];
/** Display order of pinned icons and dropdown rows (the product-specified order). */
-const PANEL_ORDER: readonly PanelKey[] = ["agents", "terminal", "workspace"];
+const PANEL_ORDER: readonly PanelKey[] = ["agents", "terminal", "workspace", "memory"];
+
+/** Open book: the Memory panel's mark (same glyph as the memory-changes card header). */
+const MEMORY_ICON =
+ "M4 19.5A2.5 2.5 0 0 1 6.5 17H20M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z";
/** Plus: the "create" trigger opening the panels menu. */
const CREATE_ICON = "M12 5v14M5 12h14";
@@ -83,6 +87,8 @@ export interface PanelsToolbarProps {
agentsPending: boolean;
workspaceOpen: boolean;
onToggleWorkspace: () => void;
+ memoryOpen: boolean;
+ onToggleMemory: () => void;
}
interface PanelEntry {
@@ -275,6 +281,14 @@ export function PanelsToolbar(props: PanelsToolbarProps) {
open: props.workspaceOpen,
toggle: props.onToggleWorkspace,
},
+ {
+ key: "memory",
+ label: S.chat.memoryViewTitle,
+ buttonLabel: S.chat.openMemoryPanel,
+ glyph: () => <GlyphIcon d={MEMORY_ICON} size={ICON_SIZE.iconButton} />,
+ open: props.memoryOpen,
+ toggle: props.onToggleMemory,
+ },
];
const panels = entries.filter((entry) => entry.key !== "terminal" || terminalSupported);
diff --git a/packages/web/src/features/chat/use-files-panel.ts b/packages/web/src/features/chat/use-files-panel.ts
index 79279caa..dbcfda2f 100644
--- a/packages/web/src/features/chat/use-files-panel.ts
+++ b/packages/web/src/features/chat/use-files-panel.ts
@@ -2,7 +2,8 @@
* Files panel state machine: panel open/close, the responsive breakpoint for desktop docking
* vs. falling back to a mobile drawer, and the "locate a file in the directory tree" navigation
* command (driven by clicking a file chip inside a message). Drag-to-resize and the width live
- * in use-panel-width.ts, shared with the Agents panel so the two open at the same width.
+ * in use-panel-width.ts, shared with the Agents and Memory panels so they all open at the
+ * same width.
*
* The panel's content is just WorkspaceBrowser's single directory-tree view — the protocol has no
* structured file-write signal at all (file writes can happen inside the opaque exec_command shell),
@@ -12,8 +13,8 @@
* Only the navigation command resets when sessionId changes; the open/closed state persists
* across Sessions (once opened, it stays open — a panel the user opened is part of their
* browsing environment, and switching conversations shouldn't collapse it). Starting a NEW chat
- * is the one reset point, and it belongs to the chat page, which owns both panels: see the
- * draft effect in chat-page.tsx.
+ * is the one reset point, and it belongs to the chat page, which owns every docked panel: see
+ * the draft effect in chat-page.tsx.
*/
import { useCallback, useEffect, useState } from "react";
import type { SheetSnap } from "../../components/ui/sheet";
diff --git a/packages/web/src/features/chat/use-memory-listing.ts b/packages/web/src/features/chat/use-memory-listing.ts
new file mode 100644
index 00000000..a7fa0747
--- /dev/null
+++ b/packages/web/src/features/chat/use-memory-listing.ts
@@ -0,0 +1,55 @@
+/**
+ * The Agent's memory listing (overview + every scope's files), owned by chat-page and
+ * shared by two consumers: the Memory panel's list/detail views, and the memory-changes
+ * card's deleted-row filtering (a changed file the loaded listing doesn't carry no longer
+ * exists, so the card drops its rows — see memory-nav.ts deletedChangeKeys).
+ *
+ * Fetches only when wanted (the panel is open, or this conversation has memory changes to
+ * mark), and refetches when `changes` moves — the caller passes an identity-stable array
+ * (see chat-page's stabilization), so streaming ticks never re-fire this.
+ */
+import { useEffect, useState } from "react";
+import * as api from "../../api/endpoints";
+import { apiErrorText } from "../../lib/api-error";
+import type { MemoryChangeRow } from "../../lib/omni/memory-changes";
+import type { ScopeFiles } from "./memory-nav";
+
+export function useMemoryListing(
+ projectId: string | null,
+ agentId: string | null,
+ wanted: boolean,
+ changes: readonly MemoryChangeRow[],
+): { scopes: ScopeFiles[] | null; error: string | null } {
+ const [state, setState] = useState<{
+ forAgent: string | null;
+ scopes: ScopeFiles[] | null;
+ error: string | null;
+ }>({ forAgent: null, scopes: null, error: null });
+
+ useEffect(() => {
+ if (!wanted || projectId === null || agentId === null) return;
+ let cancelled = false;
+ void (async () => {
+ try {
+ const overview = await api.getMemoryOverview(projectId, agentId);
+ const scopes = await Promise.all(
+ overview.scopes.map(async (info) => ({
+ info,
+ files: (await api.getMemoryFiles(projectId, agentId, info.scopeKey)).files,
+ })),
+ );
+ if (!cancelled) setState({ forAgent: agentId, scopes, error: null });
+ } catch (err) {
+ if (!cancelled) setState({ forAgent: agentId, scopes: null, error: apiErrorText(err) });
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [wanted, projectId, agentId, changes]);
+
+ // A listing loaded for another Agent is not this Agent's memory — report it as not loaded
+ // rather than briefly showing (and delete-marking against) the wrong tree.
+ if (state.forAgent !== agentId) return { scopes: null, error: null };
+ return { scopes: state.scopes, error: state.error };
+}
diff --git a/packages/web/src/features/chat/use-memory-panel.ts b/packages/web/src/features/chat/use-memory-panel.ts
new file mode 100644
index 00000000..2df6d6a7
--- /dev/null
+++ b/packages/web/src/features/chat/use-memory-panel.ts
@@ -0,0 +1,78 @@
+/**
+ * Memory panel state machine — the Memory side panel is a peer of the subagents and files
+ * panels (chat-page wraps all three setOpens with the same exclusivity choreography) and
+ * mirrors use-files-panel.ts: open/close, the responsive docked-vs-Sheet breakpoint, and
+ * one navigation command. The command (`openMemory`) carries the Memory view's entry
+ * routing (memory-nav.ts): a locate target lands on that memory's detail, null lands on
+ * the list — so every entry point (toolbar toggle, card header, card row) goes through it
+ * and the view never needs to guess where the user came from.
+ *
+ * Only the navigation command resets when sessionId changes; the open/closed state
+ * persists across Sessions, matching the other two panels.
+ */
+import { useCallback, useEffect, useState } from "react";
+import type { SheetSnap } from "../../components/ui/sheet";
+import type { MemoryLocateTarget } from "../../lib/omni/memory-changes";
+import { usePanelWidth } from "./use-panel-width";
+import type { PanelWidthState } from "./use-panel-width";
+
+export interface MemoryPanelState extends PanelWidthState {
+ open: boolean;
+ setOpen: (open: boolean) => void;
+ /** Snap point for the mobile bottom Sheet; unused in the desktop docked state. */
+ sheetSnap: SheetSnap;
+ setSheetSnap: (snap: SheetSnap) => void;
+ /** Navigation command: a target lands on that memory's detail (card row), null on the list (toolbar / card header). */
+ openMemory: (target: MemoryLocateTarget | null) => void;
+ /** The command produced by openMemory; a new object per call so repeating the same target still re-triggers the view's routing effect (compared by identity, like the files panel's openRequest). */
+ memoryRequest: { target: MemoryLocateTarget | null } | null;
+ /** Docked at >=1024px (lg); otherwise falls back to the bottom Sheet — same breakpoint as the sibling panels. */
+ isDocked: boolean;
+}
+
+const DOCK_QUERY = "(min-width: 1024px)";
+
+export function useMemoryPanel(sessionId: string | null): MemoryPanelState {
+ const [open, setOpenRaw] = useState(false);
+ const [sheetSnap, setSheetSnap] = useState<SheetSnap>("half");
+ const [memoryRequest, setMemoryRequest] = useState<{
+ target: MemoryLocateTarget | null;
+ } | null>(null);
+
+ /** Opening defaults to browsing intent (Sheet at half); openMemory's locate overrides to full in the same batch. */
+ const setOpen = useCallback((next: boolean) => {
+ if (next) setSheetSnap("half");
+ setOpenRaw(next);
+ }, []);
+ const widthState = usePanelWidth();
+ const [isDocked, setIsDocked] = useState(() => window.matchMedia(DOCK_QUERY).matches);
+
+ // Switching Session/Agent only resets the navigation command (which pointed at the old
+ // session's changes); the open/closed state deliberately survives.
+ useEffect(() => {
+ setMemoryRequest(null);
+ }, [sessionId]);
+
+ useEffect(() => {
+ const mq = window.matchMedia(DOCK_QUERY);
+ const onChange = (e: MediaQueryListEvent) => setIsDocked(e.matches);
+ mq.addEventListener("change", onChange);
+ return () => mq.removeEventListener("change", onChange);
+ }, []);
+
+ const openMemory = useCallback((target: MemoryLocateTarget | null) => {
+ if (target !== null) setSheetSnap("full"); // A located memory's content needs the space, like file preview
+ setMemoryRequest({ target });
+ }, []);
+
+ return {
+ open,
+ setOpen,
+ sheetSnap,
+ setSheetSnap,
+ openMemory,
+ memoryRequest,
+ isDocked,
+ ...widthState,
+ };
+}
diff --git a/packages/web/src/features/chat/use-panel-width.ts b/packages/web/src/features/chat/use-panel-width.ts
index 4449808e..fda5282e 100644
--- a/packages/web/src/features/chat/use-panel-width.ts
+++ b/packages/web/src/features/chat/use-panel-width.ts
@@ -1,18 +1,18 @@
/**
* Width shared by everything that docks beside the chat: the Workspace files panel, the
- * Agents panel, and a left or right terminal pane — plus the drag-to-resize machinery the
- * two panels mount.
+ * Agents panel, the Memory panel, and a left or right terminal pane — plus the drag-to-resize
+ * machinery the three panels mount.
*
- * All three are MUTUALLY EXCLUSIVE — opening one displaces the others — so to the user they
+ * All of them are MUTUALLY EXCLUSIVE — opening one displaces the others — so to the user they
* read as a single side panel that swaps its content. Independent widths made that swap
* jump, which is why the width is one value here rather than a per-surface preference: a
* width dragged on any of them is the width the next one opens at, immediately and after a
* reload. The terminal pane brings its own resize gesture (it can dock on either side) and
* writes through setPanelWidth.
*
- * "Immediately" is what rules out two `useState`s over one storage key: only the panel that was
- * mounted and dragged would update, and the other would keep a stale copy until its next
- * remount. So the value lives in a module-level store both hooks subscribe to, and the
+ * "Immediately" is what rules out a `useState` per panel over one storage key: only the panel
+ * that was mounted and dragged would update, and the others would keep a stale copy until their
+ * next remount. So the value lives in a module-level store every hook subscribes to, and the
* persisted preference is written once per drag (mouseup), not per frame.
*
* Width is a layout preference, not session data: it is never reset on a Session switch.
@@ -171,7 +171,7 @@ export function usePanelWidth(): PanelWidthState {
// When the window shrinks, clamp the width back within the cap so the docked panel can't
// crowd out the chat column. Shrinks only, never grows back, and never overwrites the stored
// preference: enlarging the window again relies on a refresh or a double-click on the handle.
- // Both panels register this; the clamp is idempotent, so the duplicate is harmless.
+ // All three panels register this; the clamp is idempotent, so the duplicates are harmless.
useEffect(() => {
const onResize = () => writeWidth(Math.min(readWidth(), maxWidthFor(window.innerWidth)));
window.addEventListener("resize", onResize);
diff --git a/packages/web/src/features/chat/use-subagents-panel.ts b/packages/web/src/features/chat/use-subagents-panel.ts
index f6a23016..04568e72 100644
--- a/packages/web/src/features/chat/use-subagents-panel.ts
+++ b/packages/web/src/features/chat/use-subagents-panel.ts
@@ -3,11 +3,12 @@
* mechanics): panel open/close, the desktop-dock vs. mobile-Sheet breakpoint, the "focus this
* child conversation" command driven by clicking a subagent chip inside a message, and the
* displayed Task scope (latest vs. the historical Task a chip was clicked on — see taskScope).
- * Width and drag-to-resize live in use-panel-width.ts, shared with the Files panel so the two
- * mutually exclusive panels always open at the same width.
+ * Width and drag-to-resize live in use-panel-width.ts, shared with the Files and Memory panels
+ * so the mutually exclusive panels always open at the same width.
*
* Visibility now follows the Files panel: an open panel survives a Session switch, and only a
- * NEW chat resets both to closed (the chat page owns that reset — it owns both panels). What
+ * NEW chat resets them all to closed (the chat page owns that reset — it owns every docked
+ * panel). What
* stays specific to this panel is the AUTO-OPEN: the current Task's first live spawn opens it
* once, re-armed at each task boundary, so a manual close mid-task is respected. The pure
* tracker below (createPanelTaskScope/advancePanelTaskScope) owns that decision; the chat page
diff --git a/packages/web/src/lib/frontmatter.ts b/packages/web/src/lib/frontmatter.ts
new file mode 100644
index 00000000..e5b571db
--- /dev/null
+++ b/packages/web/src/lib/frontmatter.ts
@@ -0,0 +1,8 @@
+/**
+ * Frontmatter helpers shared by the memory views (agents settings tab, chat side panel).
+ */
+
+/** The body without its frontmatter block: callers render the metadata fields themselves, so rendering the raw YAML too would only repeat them. */
+export function bodyWithoutFrontmatter(content: string): string {
+ return content.replace(/^\ufeff?---\r?\n[\s\S]*?\r?\n---\r?\n?/, "");
+}
diff --git a/packages/web/src/lib/omni/memory-changes.ts b/packages/web/src/lib/omni/memory-changes.ts
new file mode 100644
index 00000000..3bd72332
--- /dev/null
+++ b/packages/web/src/lib/omni/memory-changes.ts
@@ -0,0 +1,145 @@
+/**
+ * Memory-change rows for the Task summary card and the side panel's memory view: classifies
+ * structured file-tool writes (`write_file` / `edit_file`) against the Session's Memory root
+ * (`<agent_state>/memory/`, see core's state/memory.ts for the on-disk layout) and merges
+ * repeated changes of one topic file into a single row — the minimal record the displays
+ * need: which file, in which scope, what kind of change, and when it last happened.
+ *
+ * Like the file-summary card, this only sees the structured signal: memory files touched
+ * through an opaque `exec_command` shell (including deletions — no builtin delete tool
+ * exists) are invisible here, so the rows are a summary of tool-recorded changes, not an
+ * audit trail.
+ */
+
+/** How a memory file was changed: `write` = full-content write (write_file, which also creates), `edit` = in-place edit (edit_file). */
+export type MemoryChangeOp = "write" | "edit";
+
+/** One merged row: a memory topic file that was changed. */
+export interface MemoryChangeRow {
+ /** Memory scope the file belongs to: the Agent-wide User scope or one Workspace scope. */
+ scope: "user" | "workspace";
+ /** The Workspace scope's directory key (`memory/<key>/`); absent for the User scope. */
+ scopeKey?: string;
+ /** Path relative to the scope directory (usually `<topic>.md`). */
+ file: string;
+ /** Merged summary op: `write` when any call wrote the whole file, else `edit`. */
+ op: MemoryChangeOp;
+ /** Execution start (message time) of the file's latest qualifying call. */
+ atMs?: number;
+}
+
+/** A classified memory path (no op yet — the caller derives that from the tool name). */
+export type MemoryPathClass = Omit<MemoryChangeRow, "op" | "atMs">;
+
+/** A single change before merging. */
+export type MemoryChangeEntry = MemoryPathClass & { op: MemoryChangeOp; atMs?: number };
+
+/** Row identity used by "locate this row in the memory view" requests. */
+export interface MemoryLocateTarget {
+ scope: "user" | "workspace";
+ scopeKey?: string;
+ file: string;
+}
+
+/** The locate key of a row or target: one file within one scope. */
+export function memoryRowKey(row: MemoryLocateTarget): string {
+ return `${row.scope} ${row.scopeKey ?? ""} ${row.file}`;
+}
+
+/** Splits an absolute path into non-empty segments, tolerating either separator (server paths may be Windows-style). */
+function segments(p: string): string[] {
+ return p.split(/[\\/]/).filter((s) => s.length > 0);
+}
+
+/**
+ * Classifies one file-tool path against the Memory root. Returns null when the path is not a
+ * display-worthy memory change: outside `<agent_state>/memory/`, the scope directory itself,
+ * a scope's `MEMORY.md` index (rewritten alongside almost every topic change — listing it
+ * would double every row), or the `.workspace` marker file.
+ */
+export function classifyMemoryPath(filePath: string, agentState: string): MemoryPathClass | null {
+ const root = [...segments(agentState), "memory"];
+ const parts = segments(filePath);
+ if (parts.length <= root.length + 1) return null; // too short for <root>/memory/<scope>/<file>
+ for (let i = 0; i < root.length; i++) {
+ if (parts[i] !== root[i]) return null;
+ }
+ const scopeSeg = parts[root.length]!;
+ const file = parts.slice(root.length + 1).join("/");
+ if (file === "MEMORY.md" || file === ".workspace") return null;
+ return scopeSeg === "user"
+ ? { scope: "user", file }
+ : { scope: "workspace", scopeKey: scopeSeg, file };
+}
+
+/**
+ * Content equality of two aggregated row lists. The chat page re-derives rows from the
+ * stream on every streamed message; consumers key effects (listing refetch, detail refetch)
+ * and memos on the rows' identity, so the page keeps the previous array whenever this says
+ * nothing actually changed — a streaming tick must not re-fire those effects.
+ */
+export function sameMemoryChanges(
+ a: readonly MemoryChangeRow[],
+ b: readonly MemoryChangeRow[],
+): boolean {
+ if (a === b) return true;
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) {
+ const ra = a[i]!;
+ const rb = b[i]!;
+ if (
+ ra.scope !== rb.scope ||
+ ra.scopeKey !== rb.scopeKey ||
+ ra.file !== rb.file ||
+ ra.op !== rb.op ||
+ ra.atMs !== rb.atMs
+ ) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/**
+ * Merges the Task's classified changes into one row per file, preserving first-seen order.
+ * A `write` dominates regardless of order — "wrote the file, then tweaked it" still
+ * summarizes as a write, and "edited, then rewrote" even more so; `atMs` follows the
+ * latest call.
+ */
+export function mergeMemoryChanges(entries: readonly MemoryChangeEntry[]): MemoryChangeRow[] {
+ const rows = new Map<string, MemoryChangeRow>();
+ for (const e of entries) {
+ const k = memoryRowKey(e);
+ const prev = rows.get(k);
+ if (prev === undefined) {
+ const row: MemoryChangeRow = { scope: e.scope, file: e.file, op: e.op };
+ if (e.scopeKey !== undefined) row.scopeKey = e.scopeKey;
+ if (e.atMs !== undefined) row.atMs = e.atMs;
+ rows.set(k, row);
+ } else {
+ if (e.op === "write") prev.op = "write";
+ if (e.atMs !== undefined) prev.atMs = e.atMs;
+ }
+ }
+ return [...rows.values()];
+}
+
+/**
+ * Merges several Tasks' row lists (in Task order) into one per-file list for the side
+ * panel: the summary op stays write-dominant, `atMs` follows the latest Task's, order is
+ * first appearance across the whole session.
+ */
+export function aggregateMemoryChanges(
+ rowLists: readonly (readonly MemoryChangeRow[])[],
+): MemoryChangeRow[] {
+ const entries: MemoryChangeEntry[] = [];
+ for (const rows of rowLists) {
+ for (const row of rows) {
+ const entry: MemoryChangeEntry = { scope: row.scope, file: row.file, op: row.op };
+ if (row.scopeKey !== undefined) entry.scopeKey = row.scopeKey;
+ if (row.atMs !== undefined) entry.atMs = row.atMs;
+ entries.push(entry);
+ }
+ }
+ return mergeMemoryChanges(entries);
+}
diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.ts
index 0259c9fa..2f9137bf 100644
--- a/packages/web/src/lib/omni/stream-model.ts
+++ b/packages/web/src/lib/omni/stream-model.ts
@@ -80,6 +80,8 @@ import {
trackSubagentUsage,
} from "./task-stats";
import type { TaskStats, TaskStatsTracker } from "./task-stats";
+import { classifyMemoryPath, mergeMemoryChanges } from "./memory-changes";
+import type { MemoryChangeEntry, MemoryChangeRow } from "./memory-changes";
// ---------------------------------------------------------------------------
// View model types
@@ -336,6 +338,8 @@ export interface TaskStatsItem {
forkPosition?: TracePosition;
/** True only when the final assistant segment and its Request completed normally. */
forkable?: boolean;
+ /** Memory topic files this Task changed through the structured file tools (merged, one row per file); absent when there were none. */
+ memoryChanges?: MemoryChangeRow[];
}
export type ChatItem =
@@ -376,6 +380,8 @@ export interface StreamModel {
nested: boolean;
/** Child-session identity from its session_meta (nested models only; null until it arrives). */
meta: NestedSessionMeta | null;
+ /** Absolute `agent_state` path from session_meta (null until it arrives); the Memory root `<agent_state>/memory/` for the Task summary's memory-change rows. */
+ agentState: string | null;
/**
* Elapsed-time stamps for the subagents panel's topology nodes (nested models only — the main
* session's timing is covered by task stats). Stamped in routeNested: the `firstSeen` pair when
@@ -525,6 +531,7 @@ function newModel(nested: boolean, localDecisions: Set<string>): StreamModel {
items: [],
nested,
meta: null,
+ agentState: null,
stats: createTaskStatsTracker(),
openText: null,
openThinking: null,
@@ -646,11 +653,16 @@ export function pushMessage(
advanceLastTs(model, msg.timestamp);
return;
}
- // session_meta: never rendered as an item. For the main session it carries nothing the view
- // model needs (identity/config are all surfaced through the Session DTO). For a NESTED child
- // session no DTO is loaded here, so capture the identity the subagents panel needs (which
- // agent runs this child, on which model) — a rewritten session_meta (file rotation) simply
- // overwrites with the same values.
+ // session_meta: never rendered as an item, but read at BOTH levels. Both keep the
+ // agent_state path — the main session's Task summary classifies file-tool writes against
+ // `<agent_state>/memory/` for its memory-change rows, so a model built from a window that
+ // never carries a session_meta derives none. A NESTED child session additionally has no DTO
+ // loaded here, so it captures the identity the subagents panel needs (which agent runs this
+ // child, on which model); the main session takes the rest of its identity/config from the
+ // Session DTO. A rewritten session_meta (file rotation) overwrites with the same values.
+ if (msg.type === "session_meta") {
+ model.agentState = (msg.payload as SessionMetaPayload).agent_state;
+ }
if (msg.type === "session_meta" && model.nested) {
const p = msg.payload as SessionMetaPayload;
const meta: NestedSessionMeta = {
@@ -870,6 +882,7 @@ function finalizeOpenTask(model: StreamModel): void {
const stats = endTask(model.stats, elapsed);
if (model.nested) return;
const reply = collectTaskAssistant(model);
+ const memoryChanges = collectTaskMemoryChanges(model);
// No token_usage (the reply was interrupted mid-way) → there are no stats
// to show, but as long as this round produced any text, there still needs
// to be a footer: the timestamp and copy are both rendered by the stats
@@ -884,6 +897,7 @@ function finalizeOpenTask(model: StreamModel): void {
forkable: reply.completed,
...(reply.atMs !== undefined ? { atMs: reply.atMs } : {}),
...(reply.tracePosition !== undefined ? { forkPosition: reply.tracePosition } : {}),
+ ...(memoryChanges.length > 0 ? { memoryChanges } : {}),
};
// The stats row is inserted **before any trailing run of compaction banners**: compaction
// is its own round, housekeeping outside this one, so it belongs after this round's ledger
@@ -934,6 +948,42 @@ function collectTaskAssistant(model: StreamModel): {
};
}
+/**
+ * Collect this Task's memory changes (same walk as collectTaskAssistant: backward until the
+ * previous task_stats): successfully completed `write_file` / `edit_file` calls whose path
+ * falls under `<agent_state>/memory/`, merged to one row per file. Only this level's tool
+ * cards are consulted — a subagent's memory writes belong to that child's own Agent and are
+ * out of this Task summary's scope.
+ */
+function collectTaskMemoryChanges(model: StreamModel): MemoryChangeRow[] {
+ if (model.agentState === null) return [];
+ const entries: MemoryChangeEntry[] = [];
+ for (let i = model.items.length - 1; i >= 0; i--) {
+ const it = model.items[i]!;
+ if (it.kind === "task_stats") break;
+ if (it.kind !== "tool_call" || !it.outputComplete || it.outputStopReason !== "completed")
+ continue;
+ if (it.name !== "write_file" && it.name !== "edit_file") continue;
+ let args: unknown;
+ try {
+ args = JSON.parse(it.argumentsText);
+ } catch {
+ continue; // a malformed argument record can't name a file
+ }
+ const filePath = (args as { file_path?: unknown }).file_path;
+ if (typeof filePath !== "string") continue;
+ const classed = classifyMemoryPath(filePath, model.agentState);
+ if (classed === null) continue;
+ const entry: MemoryChangeEntry = {
+ ...classed,
+ op: it.name === "write_file" ? "write" : "edit",
+ };
+ if (it.callStartedAtMs !== undefined) entry.atMs = it.callStartedAtMs;
+ entries.push(entry);
+ }
+ return mergeMemoryChanges(entries.reverse()); // walked backward; merge in call order
+}
+
// ---------------------------------------------------------------------------
// Streamed fragments
// ---------------------------------------------------------------------------
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 1e20bc8f..63da1ce9 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1400,6 +1400,20 @@ Scenarios:
openPreview: "Click to preview",
showMoreFiles: (n: number) => `Show ${n} more ${n === 1 ? "file" : "files"}`,
showLess: "Show less",
+ memoryChangesTitle: (n: number) => `${n} memory ${n === 1 ? "update" : "updates"}`,
+ memoryScopeWorkspace: (key: string) => `Workspace memory (${key})`,
+ memoryOpWrite: "Wrote",
+ memoryOpEdit: "Edited",
+ memoryViewTitle: "Memory",
+ memoryChangedMark: "Changed in this conversation",
+ memoryContentUnavailable: "Content unavailable (the file may have been moved or deleted)",
+ openMemoryPanel: "Open memory",
+ memoryRowOpen: "View content",
+ memoryBack: "Back to the list",
+ memoryEmptyAll: "No memory yet — say “remember …” in a chat to have the agent save one",
+ /** Visible label on the Memory panel's header link (not a tooltip-only glyph): says what the click does and where it lands. */
+ openAgentMemory: "Manage in agent settings",
+ memoryShowMore: (n: number) => `Show ${n} more`,
/** Reveal the next page of sidebar groups (#139); n = groups still hidden. */
moreGroups: (n: number) => `More groups (${n})`,
contextUsage: "Context usage",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 839a78c7..9c4eb603 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1353,6 +1353,21 @@ Benchmark:
openPreview: "点击预览",
showMoreFiles: (n: number) => `显示其余 ${n} 个文件`,
showLess: "收起",
+ /** Memory-change card below the file summary and the Memory side panel: titles, scope/op tooltips, collapsed row. */
+ memoryChangesTitle: (n: number) => `${n} 条记忆更新`,
+ memoryScopeWorkspace: (key: string) => `工作区记忆(${key})`,
+ memoryOpWrite: "写入",
+ memoryOpEdit: "编辑",
+ memoryViewTitle: "记忆",
+ memoryChangedMark: "本次对话已更改",
+ memoryContentUnavailable: "无法加载内容(文件可能已被移动或删除)",
+ openMemoryPanel: "打开记忆",
+ memoryRowOpen: "查看内容",
+ memoryBack: "返回列表",
+ memoryEmptyAll: "还没有任何记忆——在对话里说「记住……」即可让 agent 保存",
+ /** Visible label on the Memory panel's header link (not a tooltip-only glyph): says what the click does and where it lands. */
+ openAgentMemory: "在 Agent 设置中管理",
+ memoryShowMore: (n: number) => `显示其余 ${n} 条`,
/** Reveal the next page of sidebar groups (#139); n = groups still hidden. */
moreGroups: (n: number) => `更多分组(${n})`,
contextUsage: "上下文占用",
diff --git a/packages/web/test/frontmatter.test.ts b/packages/web/test/frontmatter.test.ts
new file mode 100644
index 00000000..ea8444eb
--- /dev/null
+++ b/packages/web/test/frontmatter.test.ts
@@ -0,0 +1,44 @@
+/**
+ * frontmatter.ts unit tests: stripping the leading YAML block from a memory file's content,
+ * shared by the agent-settings memory tab and the chat Memory panel. The cases that matter are
+ * the ones a hand-written topic file actually produces — no block, an unterminated block, CRLF,
+ * a BOM, and a `---` rule further down the body.
+ */
+import { describe, expect, it } from "vitest";
+import { bodyWithoutFrontmatter } from "../src/lib/frontmatter";
+
+describe("bodyWithoutFrontmatter", () => {
+ it("strips a well-formed block and keeps the body verbatim", () => {
+ expect(bodyWithoutFrontmatter("---\nname: Prefs\n---\nBody line\n")).toBe("Body line\n");
+ });
+
+ it("leaves content that has no frontmatter untouched", () => {
+ expect(bodyWithoutFrontmatter("# Title\n\nBody\n")).toBe("# Title\n\nBody\n");
+ });
+
+ it("leaves an unterminated block untouched — a half-written file must not lose its body", () => {
+ expect(bodyWithoutFrontmatter("---\nname: Prefs\nBody\n")).toBe("---\nname: Prefs\nBody\n");
+ });
+
+ it("closes on the FIRST fence, so a horizontal rule further down stays in the body", () => {
+ expect(bodyWithoutFrontmatter("---\nname: P\n---\nOne\n\n---\n\nTwo\n")).toBe(
+ "One\n\n---\n\nTwo\n",
+ );
+ });
+
+ it("handles CRLF line endings", () => {
+ expect(bodyWithoutFrontmatter("---\r\nname: P\r\n---\r\nBody\r\n")).toBe("Body\r\n");
+ });
+
+ it("tolerates a leading BOM", () => {
+ expect(bodyWithoutFrontmatter("---\nname: P\n---\nBody\n")).toBe("Body\n");
+ });
+
+ it("returns an empty string for empty content", () => {
+ expect(bodyWithoutFrontmatter("")).toBe("");
+ });
+
+ it("keeps a body that is only the block (nothing follows the closing fence)", () => {
+ expect(bodyWithoutFrontmatter("---\nname: P\n---\n")).toBe("");
+ });
+});
diff --git a/packages/web/test/memory-changes.test.ts b/packages/web/test/memory-changes.test.ts
new file mode 100644
index 00000000..b061289f
--- /dev/null
+++ b/packages/web/test/memory-changes.test.ts
@@ -0,0 +1,150 @@
+/**
+ * memory-changes.ts unit tests: classifying file-tool paths against the Memory root
+ * (scopes, index/marker filtering, separator tolerance) and merging a Task's entries
+ * into one row per file.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ aggregateMemoryChanges,
+ classifyMemoryPath,
+ mergeMemoryChanges,
+ sameMemoryChanges,
+} from "../src/lib/omni/memory-changes";
+import type { MemoryChangeEntry } from "../src/lib/omni/memory-changes";
+
+const STATE = "/root/proj/agents/a1/agent_state";
+
+describe("classifyMemoryPath", () => {
+ it("classifies a User-scope topic file", () => {
+ expect(classifyMemoryPath(`${STATE}/memory/user/prefs.md`, STATE)).toEqual({
+ scope: "user",
+ file: "prefs.md",
+ });
+ });
+
+ it("classifies a Workspace-scope topic file with its scope key", () => {
+ expect(classifyMemoryPath(`${STATE}/memory/ws-1a2b/conventions.md`, STATE)).toEqual({
+ scope: "workspace",
+ scopeKey: "ws-1a2b",
+ file: "conventions.md",
+ });
+ });
+
+ it("keeps subdirectory structure below the scope in `file`", () => {
+ expect(classifyMemoryPath(`${STATE}/memory/user/topics/deep.md`, STATE)).toEqual({
+ scope: "user",
+ file: "topics/deep.md",
+ });
+ });
+
+ it("filters the MEMORY.md index and the .workspace marker", () => {
+ expect(classifyMemoryPath(`${STATE}/memory/user/MEMORY.md`, STATE)).toBeNull();
+ expect(classifyMemoryPath(`${STATE}/memory/ws-1a2b/.workspace`, STATE)).toBeNull();
+ });
+
+ it("keeps a nested file that merely ends in MEMORY.md-like names", () => {
+ // Only the scope's own index is noise; a topic file inside a subdirectory is content.
+ expect(classifyMemoryPath(`${STATE}/memory/user/notes/MEMORY.md`, STATE)).toEqual({
+ scope: "user",
+ file: "notes/MEMORY.md",
+ });
+ });
+
+ it("rejects paths outside the memory root", () => {
+ expect(classifyMemoryPath("/w/src/app.ts", STATE)).toBeNull();
+ expect(classifyMemoryPath(`${STATE}/AGENTS.md`, STATE)).toBeNull();
+ expect(classifyMemoryPath(`${STATE}/memories/user/x.md`, STATE)).toBeNull();
+ });
+
+ it("rejects the memory root and a bare scope directory", () => {
+ expect(classifyMemoryPath(`${STATE}/memory`, STATE)).toBeNull();
+ expect(classifyMemoryPath(`${STATE}/memory/user`, STATE)).toBeNull();
+ });
+
+ it("tolerates Windows separators on either side", () => {
+ const winState = "C:\\penguin\\proj\\agents\\a1\\agent_state";
+ expect(
+ classifyMemoryPath(
+ "C:\\penguin\\proj\\agents\\a1\\agent_state\\memory\\user\\prefs.md",
+ winState,
+ ),
+ ).toEqual({
+ scope: "user",
+ file: "prefs.md",
+ });
+ expect(classifyMemoryPath(`${STATE}\\memory\\user\\prefs.md`, STATE)).toEqual({
+ scope: "user",
+ file: "prefs.md",
+ });
+ });
+});
+
+const write = (file: string, atMs?: number): MemoryChangeEntry => ({
+ scope: "user",
+ file,
+ op: "write",
+ ...(atMs !== undefined ? { atMs } : {}),
+});
+const edit = (file: string, atMs?: number): MemoryChangeEntry => ({
+ scope: "user",
+ file,
+ op: "edit",
+ ...(atMs !== undefined ? { atMs } : {}),
+});
+
+describe("mergeMemoryChanges", () => {
+ it("keeps one row per file, preserving first-seen order; atMs follows the latest call", () => {
+ expect(mergeMemoryChanges([edit("a.md", 1), write("b.md", 2), edit("a.md", 3)])).toEqual([
+ { scope: "user", file: "a.md", op: "edit", atMs: 3 },
+ { scope: "user", file: "b.md", op: "write", atMs: 2 },
+ ]);
+ });
+
+ it("write dominates the summary op regardless of order", () => {
+ expect(mergeMemoryChanges([edit("a.md"), write("a.md")])[0]!.op).toBe("write");
+ expect(mergeMemoryChanges([write("a.md"), edit("a.md")])[0]!.op).toBe("write");
+ });
+
+ it("does not merge the same file name across scopes", () => {
+ const rows = mergeMemoryChanges([
+ { scope: "user", file: "notes.md", op: "edit" },
+ { scope: "workspace", scopeKey: "ws-1", file: "notes.md", op: "edit" },
+ { scope: "workspace", scopeKey: "ws-2", file: "notes.md", op: "edit" },
+ ]);
+ expect(rows).toHaveLength(3);
+ });
+});
+
+describe("aggregateMemoryChanges", () => {
+ it("merges one file across Tasks (write-dominant, latest atMs) and keeps first-appearance order", () => {
+ const task1 = mergeMemoryChanges([edit("a.md", 1), write("b.md", 2)]);
+ const task2 = mergeMemoryChanges([write("a.md", 5)]);
+ expect(aggregateMemoryChanges([task1, task2])).toEqual([
+ { scope: "user", file: "a.md", op: "write", atMs: 5 },
+ { scope: "user", file: "b.md", op: "write", atMs: 2 },
+ ]);
+ });
+
+ it("returns [] for no lists and leaves single-task rows unchanged", () => {
+ expect(aggregateMemoryChanges([])).toEqual([]);
+ const task = mergeMemoryChanges([edit("a.md", 1)]);
+ expect(aggregateMemoryChanges([task])).toEqual(task);
+ });
+});
+
+describe("sameMemoryChanges", () => {
+ it("treats re-derived rows with identical content as the same — a streaming tick must not re-fire effects keyed on identity", () => {
+ const a = mergeMemoryChanges([edit("a.md", 1), write("b.md", 2)]);
+ const b = mergeMemoryChanges([edit("a.md", 1), write("b.md", 2)]);
+ expect(a).not.toBe(b);
+ expect(sameMemoryChanges(a, b)).toBe(true);
+ });
+
+ it("detects every content move: rows, ops, files, and times", () => {
+ const base = mergeMemoryChanges([edit("a.md", 1)]);
+ expect(sameMemoryChanges(base, mergeMemoryChanges([write("a.md", 1)]))).toBe(false);
+ expect(sameMemoryChanges(base, mergeMemoryChanges([edit("b.md", 1)]))).toBe(false);
+ expect(sameMemoryChanges(base, mergeMemoryChanges([edit("a.md", 2)]))).toBe(false);
+ expect(sameMemoryChanges(base, [])).toBe(false);
+ });
+});
diff --git a/packages/web/test/memory-nav.test.ts b/packages/web/test/memory-nav.test.ts
new file mode 100644
index 00000000..a021397d
--- /dev/null
+++ b/packages/web/test/memory-nav.test.ts
@@ -0,0 +1,126 @@
+/**
+ * memory-nav.ts unit tests: entry routing (locate target → detail, panel entry → list),
+ * back behavior, the list view-model (markers; deleted topics absent once the listing is
+ * loaded; change-derived rows while it is not), and the deleted-key filter set.
+ */
+import { describe, expect, it } from "vitest";
+import type { MemoryFileInfo, MemoryScopeInfo } from "@prismshadow/penguin-server/api";
+import type { MemoryChangeRow } from "../src/lib/omni/memory-changes";
+import {
+ buildMemoryList,
+ deletedChangeKeys,
+ memoryNavBack,
+ memoryNavForRequest,
+} from "../src/features/chat/memory-nav";
+import type { ScopeFiles } from "../src/features/chat/memory-nav";
+
+describe("memoryNavForRequest / memoryNavBack", () => {
+ it("no request, and a request without a target (panel or card-header entry), land on the list", () => {
+ expect(memoryNavForRequest(null)).toEqual({ kind: "list" });
+ expect(memoryNavForRequest({ target: null })).toEqual({ kind: "list" });
+ });
+
+ it("a locate target (card row click) lands directly on that memory's detail", () => {
+ const target = { scope: "user" as const, file: "prefs.md" };
+ expect(memoryNavForRequest({ target })).toEqual({ kind: "detail", target });
+ });
+
+ it("back always returns to the list", () => {
+ expect(memoryNavBack()).toEqual({ kind: "list" });
+ });
+});
+
+function scopeInfo(
+ overrides: Partial<MemoryScopeInfo> & Pick<MemoryScopeInfo, "scopeKey" | "kind">,
+): MemoryScopeInfo {
+ return { fileCount: 0, hasIndex: true, ...overrides };
+}
+
+function fileInfo(name: string, title = name): MemoryFileInfo {
+ return { name, title, description: "", size: 1, modifiedAt: "2026-08-20T00:00:00.000Z" };
+}
+
+const LISTING: ScopeFiles[] = [
+ { info: scopeInfo({ scopeKey: "user", kind: "user" }), files: [fileInfo("prefs.md", "Prefs")] },
+ {
+ info: scopeInfo({ scopeKey: "ws-1", kind: "workspace", workspacePath: "/w/app" }),
+ files: [fileInfo("conventions.md")],
+ },
+];
+
+const change = (
+ scope: "user" | "workspace",
+ file: string,
+ op: "write" | "edit",
+ scopeKey?: string,
+): MemoryChangeRow => ({
+ scope,
+ ...(scopeKey !== undefined ? { scopeKey } : {}),
+ file,
+ op,
+});
+
+describe("buildMemoryList", () => {
+ it("keeps listing order and marks changed topics", () => {
+ const groups = buildMemoryList(LISTING, [change("user", "prefs.md", "edit")]);
+ expect(groups).toHaveLength(2);
+ expect(groups[0]!.rows).toEqual([
+ {
+ target: { scope: "user", file: "prefs.md" },
+ title: "Prefs",
+ modifiedAt: "2026-08-20T00:00:00.000Z",
+ changed: "edit",
+ },
+ ]);
+ expect(groups[1]!.workspacePath).toBe("/w/app");
+ expect(groups[1]!.rows[0]!.changed).toBeUndefined();
+ });
+
+ it("a changed file the loaded listing no longer carries was deleted: it does not appear", () => {
+ const groups = buildMemoryList(LISTING, [change("user", "gone.md", "write")]);
+ expect(groups[0]!.rows.map((r) => r.target.file)).toEqual(["prefs.md"]);
+ });
+
+ it("a null listing (not loaded) shows change-derived rows — unknown must not read as deleted", () => {
+ const groups = buildMemoryList(null, [
+ change("user", "a.md", "write"),
+ change("workspace", "b.md", "edit", "ws-9"),
+ ]);
+ expect(groups).toEqual([
+ {
+ scope: "user",
+ scopeKey: "user",
+ rows: [{ target: { scope: "user", file: "a.md" }, title: "a.md", changed: "write" }],
+ },
+ {
+ scope: "workspace",
+ scopeKey: "ws-9",
+ rows: [
+ {
+ target: { scope: "workspace", scopeKey: "ws-9", file: "b.md" },
+ title: "b.md",
+ changed: "edit",
+ },
+ ],
+ },
+ ]);
+ });
+});
+
+describe("deletedChangeKeys", () => {
+ const changes = [change("user", "prefs.md", "edit"), change("user", "gone.md", "write")];
+
+ it("null while the listing hasn't loaded — unknown must not read as deleted", () => {
+ expect(deletedChangeKeys(null, changes)).toBeNull();
+ });
+
+ it("marks exactly the changed files the loaded listing no longer carries", () => {
+ const keys = deletedChangeKeys(LISTING, changes);
+ expect(keys).not.toBeNull();
+ expect([...keys!]).toEqual(["user gone.md"]);
+ });
+
+ it("empty set when every changed file is still listed", () => {
+ expect([...deletedChangeKeys(LISTING, [change("user", "prefs.md", "edit")])!]).toEqual([]);
+ });
+});
diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.ts
index 35360fd5..dbd51cee 100644
--- a/packages/web/test/stream-model.test.ts
+++ b/packages/web/test/stream-model.test.ts
@@ -2164,3 +2164,75 @@ describe("fidelity-only messages render nothing (empty assistant bubble after th
expect((texts[0] as AssistantTextItem).streaming).toBe(false);
});
});
+
+describe("task_stats memory changes", () => {
+ const MEM = "/a/memory"; // meta() sets agent_state to "/a"
+
+ /** One completed file-tool call (write_file / edit_file) against `path`. */
+ function fileTool(m: StreamModel, name: string, path: string, id: string, stop = "completed") {
+ pushMessage(
+ m,
+ toolCall({ name, arguments: JSON.stringify({ file_path: path }), toolCallId: id }),
+ );
+ pushMessage(
+ m,
+ toolCallOutput({ output: "ok", toolCallId: id, stopReason: stop as "completed" }),
+ );
+ }
+
+ it("collects completed write_file/edit_file under the memory root; write dominates the merged row", () => {
+ const m = createStreamModel();
+ pushMessage(m, meta("s1"));
+ pushMessage(m, userText("remember this"));
+ fileTool(m, "write_file", `${MEM}/user/prefs.md`, "t1");
+ fileTool(m, "edit_file", `${MEM}/user/prefs.md`, "t2");
+ fileTool(m, "edit_file", `${MEM}/ws-1/conventions.md`, "t3");
+ pushMessage(m, tokenUsage(counts(100), counts(100)));
+ notifyTaskIdle(m);
+ const stats = items(m).find((i) => i.kind === "task_stats") as TaskStatsItem;
+ // toMatchObject: rows also carry the latest call's start timestamp, which the builders stamp.
+ expect(stats.memoryChanges).toMatchObject([
+ { scope: "user", file: "prefs.md", op: "write" },
+ { scope: "workspace", scopeKey: "ws-1", file: "conventions.md", op: "edit" },
+ ]);
+ expect(stats.memoryChanges).toHaveLength(2);
+ });
+
+ it("excludes failed/denied calls, index rewrites, non-memory paths, and other tools", () => {
+ const m = createStreamModel();
+ pushMessage(m, meta("s1"));
+ pushMessage(m, userText("q"));
+ fileTool(m, "write_file", `${MEM}/user/failed.md`, "t1", "failed");
+ fileTool(m, "write_file", `${MEM}/user/denied.md`, "t2", "aborted");
+ fileTool(m, "edit_file", `${MEM}/user/MEMORY.md`, "t3");
+ fileTool(m, "write_file", "/w/src/app.ts", "t4");
+ fileTool(m, "exec_command", `${MEM}/user/via-shell.md`, "t5");
+ pushMessage(m, tokenUsage(counts(100), counts(100)));
+ notifyTaskIdle(m);
+ const stats = items(m).find((i) => i.kind === "task_stats") as TaskStatsItem;
+ expect(stats.memoryChanges).toBeUndefined();
+ });
+
+ it("without session_meta no rows are derived; a later Task doesn't inherit an earlier Task's rows", () => {
+ const m = createStreamModel();
+ pushMessage(m, userText("q"));
+ fileTool(m, "write_file", `${MEM}/user/x.md`, "t0");
+ pushMessage(m, tokenUsage(counts(100), counts(100)));
+ notifyTaskIdle(m);
+ const first = items(m).find((i) => i.kind === "task_stats") as TaskStatsItem;
+ expect(first.memoryChanges).toBeUndefined(); // no agent_state known yet
+
+ pushMessage(m, meta("s1"));
+ pushMessage(m, userText("task 2 with memory"));
+ fileTool(m, "edit_file", `${MEM}/user/y.md`, "t6");
+ pushMessage(m, tokenUsage(counts(100), counts(100)));
+ notifyTaskIdle(m);
+ pushMessage(m, userText("task 3 without memory"));
+ pushMessage(m, tokenUsage(counts(100), counts(100)));
+ notifyTaskIdle(m);
+ const all = items(m).filter((i) => i.kind === "task_stats") as TaskStatsItem[];
+ expect(all).toHaveLength(3);
+ expect(all[1]!.memoryChanges).toMatchObject([{ scope: "user", file: "y.md", op: "edit" }]);
+ expect(all[2]!.memoryChanges).toBeUndefined(); // walk stops at the previous task_stats
+ });
+});