Skip to content
Python

fix(memhub): align graph scope and startup states

kristinhe082aeee1f2ce
diff --git a/memhub/apps/core/src/one_memory/api.py b/memhub/apps/core/src/one_memory/api.py
index 50513be..563c580 100644
--- a/memhub/apps/core/src/one_memory/api.py
+++ b/memhub/apps/core/src/one_memory/api.py
@@ -2978,13 +2978,21 @@ def create_app(
(`hy_graph_projection`, the visualization exception). Shape matches
the legacy map so the same view draws both.
"""
+ revoked_sources = await asyncio.to_thread(
+ _read_access(app).revoked_source_ids,
+ user_id="local",
+ )
+ if source in revoked_sources:
+ raise HTTPException(status_code=409, detail="memory_source_revoked")
try:
client = await _sdk_client_handle(app).client()
- # The map draws the page the list shows, so it reads the same
- # source filter and window rather than the newest memories overall.
+ # The map visualizes the active source scope, independently of the
+ # left list's 20-row pagination window.
raw = await asyncio.to_thread(
client.list_memories,
user_id="local",
+ scene="all",
+ statuses=["active"],
include_sources=[source] if source else None,
limit=limit,
offset=offset,
@@ -2998,7 +3006,8 @@ def create_app(
raise _sdk_http_error(error, "hy_memory_list_failed") from None
vdb = raw.get("vdb") if isinstance(raw, dict) else None
total = vdb.get("total") if isinstance(vdb, dict) else None
- memories = [memory for memory in page.memories if memory.layer != "l1_raw"]
+ visible = [memory for memory in page.memories if memory.layer != "l1_raw"]
+ memories = [memory for memory in visible if memory.source not in revoked_sources]
catalog = await asyncio.to_thread(_source_catalog, app)
nodes: dict[str, MemoryGraphNode] = {}
edges: list[MemoryGraphEdge] = []
@@ -3092,7 +3101,11 @@ def create_app(
)
)
return MemoryGraphResponse(
- total_memories=total if isinstance(total, int) else len(memories),
+ total_memories=(
+ total
+ if isinstance(total, int) and not revoked_sources
+ else len(memories)
+ ),
projected_memories=len(memories),
nodes=tuple(nodes.values()),
edges=tuple(edges),
diff --git a/memhub/apps/core/src/one_memory/source_read_access.py b/memhub/apps/core/src/one_memory/source_read_access.py
index 19103fc..c523a78 100644
--- a/memhub/apps/core/src/one_memory/source_read_access.py
+++ b/memhub/apps/core/src/one_memory/source_read_access.py
@@ -135,3 +135,14 @@ class SourceReadAccess:
).fetchone()
is not None
)
+
+ def revoked_source_ids(self, *, user_id: str) -> frozenset[str]:
+ with main_database(self.database_path).read() as db:
+ return frozenset(
+ str(row[0])
+ for row in db.execute(
+ "SELECT source_id FROM source_grants "
+ "WHERE user_id=? AND revoked_at IS NOT NULL",
+ (user_id,),
+ )
+ )
diff --git a/memhub/apps/core/tests/test_sdk_data_plane_migration.py b/memhub/apps/core/tests/test_sdk_data_plane_migration.py
index 31d41f7..4971bea 100644
--- a/memhub/apps/core/tests/test_sdk_data_plane_migration.py
+++ b/memhub/apps/core/tests/test_sdk_data_plane_migration.py
@@ -1194,6 +1194,17 @@ def test_the_sdk_memory_map_draws_sdk_memories_without_legacy_tables(tmp_path) -
"source": "default",
}
for memory_id in ("c", "d")
+ ] + [
+ {
+ "memory_id": "revoked",
+ "content": "must not be returned",
+ "layer": "l2_fact",
+ "status": "active",
+ "user_id": "local",
+ "agent_id": "all-apps",
+ "session_id": "revoked-session",
+ "source": "workbuddy",
+ }
]
listed = []
@@ -1221,6 +1232,15 @@ def test_the_sdk_memory_map_draws_sdk_memories_without_legacy_tables(tmp_path) -
):
original = app.state.sdk_client_handle
app.state.sdk_client_handle = Handle()
+ database = app.state.settings.data_dir / "one-memory.sqlite3"
+ with sqlite3.connect(database) as db:
+ db.execute(
+ "INSERT INTO source_grants "
+ "(user_id,source_id,root_path,requested_path,root_identity,"
+ "candidate_kind,granted_at,revoked_at,revision) VALUES "
+ "('local','workbuddy','/fixture','/fixture','fixture','default',"
+ "'2026-10-01T00:00:00Z','2026-10-02T00:00:00Z',1)"
+ )
async def graph_snapshot(*, limit):
del limit
@@ -1238,22 +1258,30 @@ def test_the_sdk_memory_map_draws_sdk_memories_without_legacy_tables(tmp_path) -
"/api/v2/memories/graph",
params={"source": "cursor", "offset": 100, "limit": 100},
)
+ revoked = await client.get(
+ "/api/v2/memories/graph",
+ params={"source": "workbuddy", "limit": 100},
+ )
app.state.sdk_client_handle = original
assert response.status_code == 200
+ assert revoked.status_code == 409
+ assert revoked.json()["detail"] == "memory_source_revoked"
return response.json()
graph = asyncio.run(scenario())
assert listed[0]["include_sources"] == ["cursor"]
+ assert listed[0]["scene"] == "all"
+ assert listed[0]["statuses"] == ["active"]
assert (listed[0]["offset"], listed[0]["limit"]) == (100, 100)
- assert (graph["total_memories"], graph["projected_memories"]) == (7, 4)
+ assert (graph["total_memories"], graph["projected_memories"]) == (4, 4)
assert {node["node_id"] for node in graph["nodes"]} == {
"memory:a",
"memory:b",
"memory:c",
"memory:d",
"source:cursor",
- "hy:t1",
}
+ assert "memory:revoked" not in {node["node_id"] for node in graph["nodes"]}
# "default_session" is the SDK's filler, not a conversation.
assert [
(edge["source_node_id"], edge["target_node_id"])
@@ -1263,9 +1291,8 @@ def test_the_sdk_memory_map_draws_sdk_memories_without_legacy_tables(tmp_path) -
assert {edge["relation"] for edge in graph["edges"]} == {
"evidence_source",
"same_conversation",
- "derived_from",
}
- assert graph["hy_graph_available"] is True
+ assert graph["hy_graph_available"] is False
def test_a_completed_sdk_write_does_not_touch_retired_evidence(store) -> None:
diff --git a/memhub/apps/web/src/ApplicationsHome.test.tsx b/memhub/apps/web/src/ApplicationsHome.test.tsx
index b6d2de2..5f8f2b5 100644
--- a/memhub/apps/web/src/ApplicationsHome.test.tsx
+++ b/memhub/apps/web/src/ApplicationsHome.test.tsx
@@ -172,7 +172,7 @@ it.each([
expect(sedimentation).toHaveBeenCalledOnce();
},
);
-it("localizes failure and empty states without leaking errors", async () => {
+it("localizes startup recovery and empty states without leaking errors", async () => {
summary.mockRejectedValue(new Error("synthetic_private_error"));
Object.assign(window.oneMemory ?? {}, {
getLanguagePreference: vi
@@ -191,12 +191,15 @@ it("localizes failure and empty states without leaking errors", async () => {
</LanguageProvider>,
);
expect(
- await screen.findByText("No se puede leer el estado de las memorias"),
+ await screen.findByText(
+ "El servicio se está iniciando; se actualizará automáticamente",
+ ),
).toBeTruthy();
+ expect(screen.getByText("0")).toBeTruthy();
expect(screen.getByText("Aún no hay aplicaciones para mostrar")).toBeTruthy();
expect(
- screen.getByRole("button", { name: "Reintentar lectura" }),
- ).toBeTruthy();
+ screen.queryByRole("button", { name: "Reintentar lectura" }),
+ ).toBeNull();
expect(document.body.textContent).not.toContain("synthetic_private_error");
});
it("shows latest recorded call separately without exposing recent-update detail entries", async () => {
@@ -765,7 +768,7 @@ it("keeps authoritative home and processing data when only the source snapshot b
expect(screen.getAllByText("整理中")).toHaveLength(2);
expect(screen.queryByText("状态待核对")).toBeNull();
});
-it("does not turn a failed home summary into zero or expose a private error", async () => {
+it("keeps a neutral zero while the first home summary read recovers", async () => {
summary.mockRejectedValue(new Error("private offline detail"));
render(
<ApplicationsHome
@@ -775,10 +778,39 @@ it("does not turn a failed home summary into zero or expose a private error", as
onSettings={() => {}}
/>,
);
- await waitFor(() => expect(screen.getByText("暂无法读取")).toBeTruthy());
- expect(screen.queryByText("0")).toBeNull();
+ await waitFor(() =>
+ expect(screen.getByText("后台正在启动,稍后自动更新")).toBeTruthy(),
+ );
+ expect(screen.getByText("0")).toBeTruthy();
+ expect(screen.getByText("正在准备记忆概览")).toBeTruthy();
+ expect(screen.queryByText(/暂时?无法读取|读取失败/)).toBeNull();
expect(document.body.textContent).not.toContain("private offline detail");
});
+it("offers a calm retry after repeated home summary failures", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ try {
+ summary.mockRejectedValue(new Error("private offline detail"));
+ render(
+ <ApplicationsHome
+ imports={imports}
+ onManage={() => {}}
+ onMemories={() => {}}
+ onSettings={() => {}}
+ />,
+ );
+ await waitFor(() =>
+ expect(screen.getByText("后台正在启动,稍后自动更新")).toBeTruthy(),
+ );
+ await act(async () => vi.advanceTimersByTimeAsync(10_000));
+ expect(await screen.findByText("记忆概览还没准备好")).toBeTruthy();
+ expect(
+ screen.getByText("后台恢复后会自动更新,也可以重新读取。"),
+ ).toBeTruthy();
+ expect(screen.getByRole("button", { name: "重新读取" })).toBeTruthy();
+ } finally {
+ vi.useRealTimers();
+ }
+});
it("never calls a recall event a success when only stored memories are available", async () => {
render(
<ApplicationsHome
@@ -1200,7 +1232,7 @@ it("keeps the conversation-sync checking copy before the first home read", () =>
expect(screen.queryByText(/个应用已开启/)).toBeNull();
});
-it("does not claim there are no memories while the first summary read is pending", async () => {
+it("shows a provisional zero while the first summary read is pending", async () => {
summary.mockImplementation(() => new Promise(() => {}));
history.mockResolvedValue({
available: true,
@@ -1216,7 +1248,9 @@ it("does not claim there are no memories while the first summary read is pending
onSettings={() => {}}
/>,
);
- await screen.findByText("正在读取动态");
+ await screen.findByText("正在准备记忆概览");
+ expect(screen.getByText("0")).toBeTruthy();
+ expect(screen.getByText("正在核对本机记忆…")).toBeTruthy();
expect(screen.queryByText("还没有已生成的记忆")).toBeNull();
});
diff --git a/memhub/apps/web/src/ApplicationsHome.tsx b/memhub/apps/web/src/ApplicationsHome.tsx
index 71d6288..28f7334 100644
--- a/memhub/apps/web/src/ApplicationsHome.tsx
+++ b/memhub/apps/web/src/ApplicationsHome.tsx
@@ -195,7 +195,7 @@ export function ApplicationsHome({
null,
);
const [syncHealth, setSyncHealth] = useState<LiveSyncHealth[]>([]);
- const [failed, setFailed] = useState(false);
+ const [summaryFailures, setSummaryFailures] = useState(0);
const [recentCall, setRecentCall] = useState<CallEvent | null>(null);
const [callEvents, setCallEvents] = useState<CallEvent[]>([]);
const [callState, setCallState] = useState<
@@ -554,13 +554,13 @@ export function ApplicationsHome({
busy = false;
if (stopped) return;
if (home.status === "fulfilled") {
- setFailed(false);
+ setSummaryFailures(0);
// stale=true 表示这轮读取超时,数字不代表现状:保留上一次的概览,
// 等 10 秒后的下一轮轮询补上,绝不清零也不报错。
if (!("stale" in home.value) || !home.value.stale)
setSummary(home.value);
} else {
- setFailed(true);
+ setSummaryFailures((count) => count + 1);
}
if (state.status === "fulfilled") setProcessing(state.value);
if (sync.status === "fulfilled") setSyncHealth(sync.value);
@@ -578,7 +578,7 @@ export function ApplicationsHome({
}, [active, requestKey]);
const visible = summary;
const latest = visible?.latest;
- const summaryUnavailable = failed;
+ const summaryUnavailable = visible === null && summaryFailures >= 2;
const hasCall =
recentCall !== null &&
(callState === "ready" || callState === "incomplete");
@@ -642,7 +642,7 @@ export function ApplicationsHome({
? t("apps.running")
: sedimentation?.enabled === false
? t("apps.paused")
- : t("apps.unchecked");
+ : t("apps.checkingStatus");
const stateDetail =
sedimentation?.enabled === false
? t("apps.stoppedNew")
@@ -823,40 +823,23 @@ export function ApplicationsHome({
<div className="r6-home-metrics">
<div>
<p>{t("apps.memories")}</p>
- {/* The figure slot used to hold the word 读取中 while the first
- read was in flight, which is how "大数字不可见" (D51) shows up
- on a slow link: the biggest type on the page spends the first
- frame saying something that is not a number. A bar of the same
- height reserves the digits instead, and the wording moves to a
- live region so screen readers still hear it. 暂无法读取 stays a
- word, because that is a settled state rather than progress. */}
- {!visible && !summaryUnavailable ? (
- <>
- <p className="r6-home-figure">
- <span
- className="r6-home-figure-pending"
- aria-hidden="true"
- />
- </p>
- <small role="status">{t("apps.readingCount")}</small>
- </>
- ) : (
- <>
- <p className="r6-home-figure">
- <strong className={visible ? "" : "r6-home-word"}>
- {visible
- ? new Intl.NumberFormat(locale).format(
- visible.memory_count,
- )
- : t("apps.unreadable")}
- </strong>
- {visible && t("apps.unit") ? (
- <i>{t("apps.unit")}</i>
- ) : null}
- </p>
- <small>{t("apps.scope")}</small>
- </>
- )}
+ <p className="r6-home-figure">
+ <strong>
+ {new Intl.NumberFormat(locale).format(
+ visible?.memory_count ?? 0,
+ )}
+ </strong>
+ {t("apps.unit") ? <i>{t("apps.unit")}</i> : null}
+ </p>
+ <small {...(visible ? {} : { role: "status" })}>
+ {visible
+ ? t("apps.scope")
+ : summaryUnavailable
+ ? t("apps.countWillUpdate")
+ : summaryFailures
+ ? t("apps.startingRetry")
+ : t("apps.readingCount")}
+ </small>
</div>
<div>
<p>{t("apps.processing")}</p>
@@ -867,12 +850,16 @@ export function ApplicationsHome({
<p>{t("apps.recentUpdate")}</p>
<strong className={time ? "r6-home-time" : "r6-home-word"}>
{time ??
- (visible ? t("apps.notGenerated") : t("apps.unchecked"))}
+ (visible
+ ? t("apps.notGenerated")
+ : t("apps.checkingRecent"))}
</strong>
<small>
{time
? `${latestClock?.today ? `${t("apps.today")}· ` : ""}${t("apps.saved")}`
- : t("apps.separate")}
+ : visible
+ ? t("apps.separate")
+ : t("apps.recentWillUpdate")}
</small>
</div>
</div>
@@ -972,7 +959,9 @@ export function ApplicationsHome({
.join(" · ")
: activity === "importing"
? t("apps.savingConversations")
- : t("apps.waitingMemories")}
+ : activity === "loading"
+ ? t("apps.recentWillUpdate")
+ : t("apps.waitingMemories")}
</small>
</section>
{(activity === "unavailable" ||
diff --git a/memhub/apps/web/src/MemoryMap.test.tsx b/memhub/apps/web/src/MemoryMap.test.tsx
index beec1a5..5a3caff 100644
--- a/memhub/apps/web/src/MemoryMap.test.tsx
+++ b/memhub/apps/web/src/MemoryMap.test.tsx
@@ -355,6 +355,7 @@ function Host({
processing = null,
loaded = true,
deferMemoryId,
+ graphValue = graph,
onViewHistory,
onConfigureModel = () => {},
libraryView,
@@ -370,6 +371,7 @@ function Host({
processing?: MemoryProcessingSummary | null;
loaded?: boolean;
deferMemoryId?: string;
+ graphValue?: MemoryGraphResponse;
onViewHistory?(): void;
onConfigureModel?(): void;
libraryView?: Parameters<typeof MemoryMap>[0]["libraryView"];
@@ -382,7 +384,7 @@ function Host({
hidden={hidden}
overlayBlocked={overlayBlocked}
memories={items}
- graph={graph}
+ graph={graphValue}
sources={sources}
arrival={arrival}
onViewHistory={onViewHistory}
@@ -470,10 +472,32 @@ it("does not present an unverified empty page as zero memories", () => {
view.rerender(
<Host simplified items={[]} libraryView={{ ...base, stale: true }} />,
);
- expect(screen.getByText("正在核对来源…")).toBeTruthy();
+ expect(screen.getAllByText("正在核对来源…")).toHaveLength(2);
expect(screen.queryByText(/0 条/)).toBeNull();
expect(screen.queryByText("还没有已生成的记忆")).toBeNull();
});
+
+it("does not show the previous source graph while a searched source is changing", () => {
+ render(
+ <Host
+ simplified
+ libraryView={{
+ ...pagedView({
+ items: memories,
+ total: memories.length,
+ offset: 0,
+ limit: 20,
+ source_ids_by_memory: { m0: ["codex"], m1: ["codex"] },
+ }),
+ query: "项目",
+ stale: true,
+ }}
+ />,
+ );
+ expect(screen.queryByTestId("canvas")).toBeNull();
+ expect(screen.getAllByText("正在核对来源…")).toHaveLength(2);
+});
+
it("starts with receipt-backed source grouping, keeping topics secondary", () => {
render(<Host />);
expect(
@@ -485,6 +509,118 @@ it("starts with receipt-backed source grouping, keeping topics secondary", () =>
expect(screen.getByRole("button", { name: "Codex2" })).toBeDefined();
});
+it("restores the full graph scope when the source filter returns to all applications", async () => {
+ const workbuddyMemory = {
+ ...memories[1],
+ memory_id: "workbuddy-memory",
+ content: "较早的 WorkBuddy 记忆",
+ };
+ const allGraph = {
+ total_memories: 2,
+ projected_memories: 2,
+ hy_graph_available: false,
+ nodes: [
+ graph.nodes.find((node) => node.node_id === "memory:m0"),
+ graph.nodes.find((node) => node.node_id === "source:codex"),
+ {
+ node_id: "memory:workbuddy-memory",
+ node_type: "memory",
+ memory_id: "workbuddy-memory",
+ label: workbuddyMemory.content,
+ },
+ {
+ node_id: "source:workbuddy",
+ node_type: "source",
+ source_id: "workbuddy",
+ label: "WorkBuddy",
+ },
+ ].filter(Boolean),
+ edges: [
+ {
+ edge_id: "cursor-memory",
+ source_node_id: "source:codex",
+ target_node_id: "memory:m0",
+ relation: "evidence_source",
+ origin: "provenance",
+ },
+ {
+ edge_id: "workbuddy-memory",
+ source_node_id: "source:workbuddy",
+ target_node_id: "memory:workbuddy-memory",
+ relation: "evidence_source",
+ origin: "provenance",
+ },
+ ],
+ } as MemoryGraphResponse;
+ const cursorGraph = {
+ ...allGraph,
+ total_memories: 1,
+ projected_memories: 1,
+ nodes: allGraph.nodes.filter(
+ (node) => node.node_id === "memory:m0" || node.node_id === "source:codex",
+ ),
+ edges: [allGraph.edges[0]],
+ };
+
+ function ScopeHarness() {
+ const [source, setSource] = useState("codex");
+ return (
+ <Host
+ simplified
+ items={[memories[0]]}
+ graphValue={source ? cursorGraph : allGraph}
+ sources={
+ [
+ {
+ source_id: "codex",
+ display_name: "Cursor",
+ authorized: true,
+ },
+ {
+ source_id: "workbuddy",
+ display_name: "WorkBuddy",
+ authorized: true,
+ },
+ {
+ source_id: "retired",
+ display_name: "Retired",
+ authorized: false,
+ },
+ ] as SourceResponse[]
+ }
+ libraryView={{
+ ...pagedView({
+ items: [memories[0]],
+ total: source ? 1 : 2,
+ offset: 0,
+ limit: 20,
+ source_ids_by_memory: { m0: ["codex"] },
+ }),
+ source,
+ onSource: setSource,
+ }}
+ />
+ );
+ }
+
+ render(<ScopeHarness />);
+ expect(
+ screen.queryByRole("button", {
+ name: "图中选择 较早的 WorkBuddy 记忆",
+ }),
+ ).toBeNull();
+ await userEvent.click(screen.getByRole("combobox", { name: "来源" }));
+ await userEvent.click(screen.getByRole("option", { name: "全部应用" }));
+ expect(
+ screen.getByRole("button", {
+ name: "图中选择 较早的 WorkBuddy 记忆",
+ }),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole("button", { name: "图中选择 WorkBuddy" }),
+ ).toBeTruthy();
+});
+
function pagedView(
page: Parameters<typeof MemoryMap>[0]["libraryView"] extends infer V
? V extends { page: infer P }
diff --git a/memhub/apps/web/src/MemoryMap.tsx b/memhub/apps/web/src/MemoryMap.tsx
index b1fc273..367a427 100644
--- a/memhub/apps/web/src/MemoryMap.tsx
+++ b/memhub/apps/web/src/MemoryMap.tsx
@@ -308,6 +308,29 @@ export function MemoryMap(props: Props) {
[active, group, search, serverPaged, axis, groupKey],
);
const projection = useMemo(() => {
+ if (serverPaged && library?.stale)
+ return {
+ total_memories: library.page?.total ?? 0,
+ projected_memories: 0,
+ hy_graph_available: false,
+ nodes: [],
+ edges: [],
+ };
+ // Source filtering owns the graph scope, while pagination owns only the
+ // left-hand list window. Projecting the graph back down to the current
+ // 20-row page made "All applications" look like whichever source happened
+ // to dominate that page. Keyword search is intentionally page-scoped.
+ if (serverPaged && !library?.query) {
+ return (
+ baseGraph ??
+ projectMap(
+ graph,
+ active,
+ axis,
+ filtered.map((m) => m.memory_id),
+ )
+ );
+ }
const result = projectMap(
graph,
active,
@@ -339,7 +362,20 @@ export function MemoryMap(props: Props) {
confidence: null,
})),
};
- }, [graph, axis, filtered, active, groupKey, search, sources, serverPaged]);
+ }, [
+ baseGraph,
+ graph,
+ axis,
+ filtered,
+ active,
+ groupKey,
+ search,
+ sources,
+ serverPaged,
+ library?.query,
+ library?.stale,
+ library?.page?.total,
+ ]);
const visibleGroupNode = groupNode
? (projection.nodes.find(
(node) =>
@@ -1012,7 +1048,7 @@ export function MemoryMap(props: Props) {
<Network size={32} strokeWidth={1} />
<p>
{library?.stale
- ? text("可在沉淀记忆后查看视图")
+ ? text("正在核对来源…")
: library?.failed
? text("记忆暂时无法读取")
: library?.page &&
diff --git a/memhub/apps/web/src/MemorySpace.sdk-authority.test.tsx b/memhub/apps/web/src/MemorySpace.sdk-authority.test.tsx
index 410cee3..3409cb5 100644
--- a/memhub/apps/web/src/MemorySpace.sdk-authority.test.tsx
+++ b/memhub/apps/web/src/MemorySpace.sdk-authority.test.tsx
@@ -5,6 +5,7 @@ import type {
SdkMemoryRecord,
} from "@one-memory/contracts";
import {
+ act,
cleanup,
fireEvent,
render,
@@ -63,6 +64,7 @@ vi.mock("./MemoryMap", () => ({
source_ids_by_memory?: Record<string, string[]>;
offset: number;
} | null;
+ stale: boolean;
unattributedSource?: string;
onSource(value: string): void;
onQuery(value: string): void;
@@ -91,6 +93,7 @@ vi.mock("./MemoryMap", () => ({
<span data-testid="map-busy">{String(busy)}</span>
<span data-testid="map-detail">{detail?.memory.memory_id ?? ""}</span>
<span data-testid="map-offset">{libraryView?.page?.offset ?? ""}</span>
+ <span data-testid="map-stale">{String(libraryView?.stale)}</span>
<button type="button" onClick={() => onOpenMemory("e1")}>
open e1
</button>
@@ -133,6 +136,15 @@ vi.mock("./MemoryMap", () => ({
>
pick workbuddy
</button>
+ <button
+ type="button"
+ onClick={() => {
+ libraryView?.onSource("");
+ libraryView?.resetPage();
+ }}
+ >
+ pick all
+ </button>
</div>
),
}));
@@ -214,7 +226,7 @@ it("draws the map from SDK memories on SDK authority, without legacy reads", asy
expect.any(AbortSignal),
);
expect(api.sdkGraph).toHaveBeenCalledWith(
- { source: undefined, offset: 0, limit: 100 },
+ { source: undefined, offset: 0, limit: 300 },
expect.any(AbortSignal),
);
});
@@ -251,12 +263,148 @@ it("keeps rows, sources, count and graph on the one filtered page", async () =>
expect.any(AbortSignal),
);
expect(api.sdkGraph).toHaveBeenLastCalledWith(
- { source: "workbuddy", offset: 0, limit: 100 },
+ { source: "workbuddy", offset: 0, limit: 300 },
expect.any(AbortSignal),
);
expect(await screen.findByText(/566/)).toBeTruthy();
});
+it("hides the previous source graph until the all-applications graph settles", async () => {
+ sdkAuthority();
+ render(<MemorySpace simplified active />);
+ await waitFor(() =>
+ expect(screen.getByTestId("map-nodes").textContent).toBe("3"),
+ );
+
+ const workbuddyPage = {
+ memories: [{ ...record("w1"), source: "workbuddy" }],
+ total: 1,
+ limit: 20,
+ offset: 0,
+ };
+ const workbuddyGraph: MemoryGraphResponse = {
+ total_memories: 1,
+ projected_memories: 1,
+ nodes: [
+ {
+ node_id: "memory:w1",
+ node_type: "memory",
+ label: "w1",
+ memory_id: "w1",
+ source_id: null,
+ kind: null,
+ status: "active",
+ confidence: null,
+ },
+ {
+ node_id: "source:workbuddy",
+ node_type: "source",
+ label: "WorkBuddy",
+ source_id: "workbuddy",
+ memory_id: null,
+ kind: null,
+ status: null,
+ confidence: null,
+ },
+ ],
+ edges: [],
+ hy_graph_available: false,
+ };
+ api.sdkLibrary.mockResolvedValue(workbuddyPage);
+ api.sdkGraph.mockResolvedValue(workbuddyGraph);
+ fireEvent.click(screen.getByText("pick workbuddy"));
+ await waitFor(() =>
+ expect(screen.getByTestId("map-nodes").textContent).toBe("2"),
+ );
+
+ const allPage = {
+ memories: [record("a"), { ...record("w1"), source: "workbuddy" }],
+ total: 2,
+ limit: 20,
+ offset: 0,
+ };
+ const allGraph: MemoryGraphResponse = {
+ ...workbuddyGraph,
+ total_memories: 2,
+ projected_memories: 2,
+ nodes: [
+ ...workbuddyGraph.nodes,
+ {
+ node_id: "memory:a",
+ node_type: "memory",
+ label: "a",
+ memory_id: "a",
+ source_id: null,
+ kind: null,
+ status: "active",
+ confidence: null,
+ },
+ {
+ node_id: "source:cursor",
+ node_type: "source",
+ label: "Cursor",
+ source_id: "cursor",
+ memory_id: null,
+ kind: null,
+ status: null,
+ confidence: null,
+ },
+ ],
+ };
+ let releasePage: (value: typeof allPage) => void = () => {};
+ let releaseGraph: (value: MemoryGraphResponse) => void = () => {};
+ api.sdkLibrary.mockReturnValueOnce(
+ new Promise((resolve) => {
+ releasePage = resolve;
+ }),
+ );
+ api.sdkGraph.mockReturnValueOnce(
+ new Promise((resolve) => {
+ releaseGraph = resolve;
+ }),
+ );
+
+ fireEvent.click(screen.getByText("pick all"));
+ await waitFor(() =>
+ expect(screen.getByTestId("map-stale").textContent).toBe("true"),
+ );
+ expect(screen.getByTestId("map-nodes").textContent).toBe("none");
+
+ await act(async () => {
+ releasePage(allPage);
+ releaseGraph(allGraph);
+ });
+ await waitFor(() =>
+ expect(screen.getByTestId("map-nodes").textContent).toBe("4"),
+ );
+ expect(screen.getByTestId("map-stale").textContent).toBe("false");
+
+ const searchPage = {
+ memories: [record("search-result")],
+ total: 1,
+ limit: 20,
+ offset: 0,
+ };
+ let releaseSearch: (value: typeof searchPage) => void = () => {};
+ api.sdkLibrary.mockReturnValueOnce(
+ new Promise((resolve) => {
+ releaseSearch = resolve;
+ }),
+ );
+ const graphCalls = api.sdkGraph.mock.calls.length;
+ fireEvent.click(screen.getByText("search deploy"));
+ await waitFor(() =>
+ expect(screen.getByTestId("map-stale").textContent).toBe("true"),
+ );
+ expect(screen.getByTestId("map-nodes").textContent).toBe("none");
+ expect(api.sdkGraph).toHaveBeenCalledTimes(graphCalls);
+
+ await act(async () => releaseSearch(searchPage));
+ await waitFor(() =>
+ expect(screen.getByTestId("map-stale").textContent).toBe("false"),
+ );
+});
+
it("opens an SDK memory in place instead of switching away from the map", async () => {
sdkAuthority();
api.sdkMemory.mockResolvedValue(record("a"));
diff --git a/memhub/apps/web/src/MemorySpace.tsx b/memhub/apps/web/src/MemorySpace.tsx
index 8d665c3..ef4efc7 100644
--- a/memhub/apps/web/src/MemorySpace.tsx
+++ b/memhub/apps/web/src/MemorySpace.tsx
@@ -166,11 +166,13 @@ export function MemorySpace({
// The SDK library is no longer where a memory opens from the map; the id is
// kept so the panel still has a focus target for its own tests.
const [sdkFocusedMemoryId] = useState<string | null>(null);
- // The list, its count, its source and time labels and the graph are all one
- // page: the library page and the graph for that same source and window,
- // read together. Reading the graph from a different, unfiltered window made
- // rows, sources and totals disagree.
- const [sdkGraph, setSdkGraph] = useState<MemoryGraphResponse | null>(null);
+ // The graph covers the active source scope (up to its visual cap), while the
+ // list pages through that scope. Keep source+query with the value so a
+ // filter change cannot paint the previous filter's graph during the new read.
+ const [sdkGraph, setSdkGraph] = useState<{
+ scope: string;
+ value: MemoryGraphResponse | null;
+ } | null>(null);
// Bumping this re-reads the page and graph after an edit or a delete.
const [sdkMapRevision, setSdkMapRevision] = useState(0);
const bumpSdkMap = useCallback(() => setSdkMapRevision((v) => v + 1), []);
@@ -191,6 +193,13 @@ export function MemorySpace({
const [sdkLibraryQuery, setSdkLibraryQuery] = useState("");
const [sdkLibrarySource, setSdkLibrarySource] = useState("");
const [sdkLibraryOffset, setSdkLibraryOffset] = useState(0);
+ const sdkRequestedScope = JSON.stringify([
+ sdkLibraryQuery.trim(),
+ sdkLibrarySource,
+ ]);
+ const sdkGraphSettled = sdkGraph?.scope === sdkRequestedScope;
+ const visibleSdkGraph =
+ sdkGraph?.scope === sdkRequestedScope ? sdkGraph.value : null;
// A keyword search pages through one server-side result window. The id is
// kept for the query and source it was searched with; a new query or
// source starts without one, so the server searches afresh.
@@ -233,22 +242,20 @@ export function MemorySpace({
request.signal,
),
// The overlay is decoration: the list stands without it. It reads
- // chat memories only, newest first; a mixed page's chat rows are
- // among the newest offset+page chat memories, so that prefix holds
- // every relation the page can draw.
- getSdkMemoryGraph(
- {
- source,
- offset: 0,
- limit: query
- ? 100
- : Math.min(
- 300,
- Math.max(100, sdkLibraryOffset + SDK_MEMORY_PAGE_SIZE),
- ),
- },
- request.signal,
- ).catch(() => null),
+ // the full active/source-filtered scene up to the API's visual cap.
+ // Reading only the first list-page prefix made "All applications"
+ // look identical to Cursor whenever newer Cursor memories occupied
+ // that prefix.
+ query
+ ? Promise.resolve(null)
+ : getSdkMemoryGraph(
+ {
+ source,
+ offset: 0,
+ limit: 300,
+ },
+ request.signal,
+ ).catch(() => null),
]);
if (cancelled) return;
if (sdkSearchWindow.current.key === windowKey)
@@ -265,7 +272,7 @@ export function MemorySpace({
settledSource: sdkLibrarySource,
settledQuery: sdkLibraryQuery,
});
- setSdkGraph(graph);
+ setSdkGraph({ scope: windowKey, value: graph });
} catch {
if (cancelled || request.signal.aborted) return;
setSdkLibrary((current) => ({
@@ -1026,7 +1033,7 @@ export function MemorySpace({
page: sdkLibrary.page,
loading: sdkLibrary.loading,
failed: sdkLibrary.failed,
- stale: false,
+ stale: !sdkGraphSettled,
unattributedSource: UNATTRIBUTED_SOURCE_ID,
onQuery: setSdkLibraryQuery,
onSource: setSdkLibrarySource,
@@ -1038,7 +1045,7 @@ export function MemorySpace({
}
hidden={!active || displayedMode !== "map"}
memories={sdkLibrary.page?.items ?? []}
- graph={sdkGraph}
+ graph={visibleSdkGraph}
sources={sources}
processing={processing}
arrival={memoryArrival}
diff --git a/memhub/packages/i18n/src/gui-i18n-applications.ts b/memhub/packages/i18n/src/gui-i18n-applications.ts
index 703e557..47c53b5 100644
--- a/memhub/packages/i18n/src/gui-i18n-applications.ts
+++ b/memhub/packages/i18n/src/gui-i18n-applications.ts
@@ -7,7 +7,9 @@ export const applicationsChineseMessages = {
"apps.back": "返回首页",
"apps.overview": "记忆概览",
"apps.memories": "已沉淀记忆",
- "apps.readingCount": "正在读取已沉淀记忆数量…",
+ "apps.readingCount": "正在核对本机记忆…",
+ "apps.startingRetry": "后台正在启动,稍后自动更新",
+ "apps.countWillUpdate": "记忆数量稍后自动更新",
"apps.unreadable": "暂无法读取",
"apps.unit": "条",
"apps.scope": "按应用授权范围使用",
@@ -16,9 +18,12 @@ export const applicationsChineseMessages = {
"apps.paused": "已暂停",
"apps.stoppedNew": "已停止生成新记忆",
"apps.checkingProcessing": "正在核对整理状态",
+ "apps.checkingStatus": "正在核对",
"apps.unchecked": "待核对",
"apps.organizingNew": "新的对话正在整理",
"apps.recentUpdate": "最近更新",
+ "apps.checkingRecent": "正在核对",
+ "apps.recentWillUpdate": "最近更新会自动显示",
"apps.notGenerated": "尚未生成",
"apps.saved": "记忆已保存",
"apps.separate": "历史与记忆分别处理",
@@ -26,14 +31,14 @@ export const applicationsChineseMessages = {
"apps.activityUnavailable": "动态暂不可用",
"apps.firstBatch": "首批沉淀",
"apps.callsUnavailable": "暂时无法读取调用记录",
- "apps.memoryUnavailable": "暂时无法读取记忆状态",
+ "apps.memoryUnavailable": "记忆概览还没准备好",
"apps.importing": "对话持续导入中,即将沉淀你的记忆",
"apps.firstRunning": "正在沉淀第一批记忆",
"apps.firstQueued": "准备沉淀第一批记忆",
- "apps.readingActivity": "正在读取动态",
+ "apps.readingActivity": "正在准备记忆概览",
"apps.emptyMemories": "还没有已生成的记忆",
"apps.callReadFailure": "已有记忆仍可查看;重试不会发起新的调用。",
- "apps.memoryReadFailure": "读取失败不会当作没有记忆。",
+ "apps.memoryReadFailure": "后台恢复后会自动更新,也可以重新读取。",
"apps.savingConversations": "对话正在后台持续保存。",
"apps.waitingMemories": "历史已保存,记忆生成后会显示在这里。",
"apps.reread": "重新读取",
@@ -121,7 +126,10 @@ export const applicationsSpanishMessages: Record<
"apps.back": "Volver al inicio",
"apps.overview": "Resumen de memorias",
"apps.memories": "Memorias guardadas",
- "apps.readingCount": "Leyendo el total de memorias…",
+ "apps.readingCount": "Comprobando las memorias locales…",
+ "apps.startingRetry":
+ "El servicio se está iniciando; se actualizará automáticamente",
+ "apps.countWillUpdate": "El total de memorias se actualizará automáticamente",
"apps.unreadable": "No disponible",
"apps.unit": "",
"apps.scope": "Según los permisos de cada aplicación",
@@ -130,9 +138,12 @@ export const applicationsSpanishMessages: Record<
"apps.paused": "En pausa",
"apps.stoppedNew": "Se dejó de generar memorias nuevas",
"apps.checkingProcessing": "Comprobando el estado del procesamiento",
+ "apps.checkingStatus": "Verificando",
"apps.unchecked": "Sin verificar",
"apps.organizingNew": "Organizando nuevas conversaciones",
"apps.recentUpdate": "Última actualización",
+ "apps.checkingRecent": "Verificando",
+ "apps.recentWillUpdate": "La última actualización aparecerá automáticamente",
"apps.notGenerated": "Sin generar",
"apps.saved": "Memoria guardada",
"apps.separate": "Historial y memorias se procesan por separado",
@@ -140,16 +151,16 @@ export const applicationsSpanishMessages: Record<
"apps.activityUnavailable": "Actividad no disponible",
"apps.firstBatch": "Primeras memorias",
"apps.callsUnavailable": "No se pueden leer las consultas",
- "apps.memoryUnavailable": "No se puede leer el estado de las memorias",
+ "apps.memoryUnavailable": "El resumen de memorias aún no está listo",
"apps.importing": "Importando conversaciones para generar memorias",
"apps.firstRunning": "Generando las primeras memorias",
"apps.firstQueued": "Preparando las primeras memorias",
- "apps.readingActivity": "Leyendo actividad",
+ "apps.readingActivity": "Preparando el resumen de memorias",
"apps.emptyMemories": "Aún no hay memorias generadas",
"apps.callReadFailure":
"Puedes ver las memorias guardadas. Reintentar no inicia otra consulta.",
"apps.memoryReadFailure":
- "Un error de lectura no significa que no haya memorias.",
+ "Se actualizará cuando el servicio se recupere. También puedes volver a leerlo.",
"apps.savingConversations": "Las conversaciones se guardan en segundo plano.",
"apps.waitingMemories":
"El historial está guardado. Las memorias aparecerán cuando se generen.",
diff --git a/memhub/packages/i18n/src/gui-i18n-english.ts b/memhub/packages/i18n/src/gui-i18n-english.ts
index 8cd10e6..3e88081 100644
--- a/memhub/packages/i18n/src/gui-i18n-english.ts
+++ b/memhub/packages/i18n/src/gui-i18n-english.ts
@@ -1305,7 +1305,10 @@ const baseEnglishMessages = {
"apps.back": "Back to home",
"apps.overview": "Memory overview",
"apps.memories": "Saved memories",
- "apps.readingCount": "Loading memory count…",
+ "apps.readingCount": "Checking local memories…",
+ "apps.startingRetry":
+ "The background service is starting; this will update automatically",
+ "apps.countWillUpdate": "The memory count will update automatically",
"apps.unreadable": "Unavailable",
"apps.unit": "items",
"apps.scope": "Used within app permissions",
@@ -1314,9 +1317,12 @@ const baseEnglishMessages = {
"apps.paused": "Paused",
"apps.stoppedNew": "No new memories are being created",
"apps.checkingProcessing": "Checking processing status",
+ "apps.checkingStatus": "Checking",
"apps.unchecked": "Needs review",
"apps.organizingNew": "Processing new conversations",
"apps.recentUpdate": "Recent update",
+ "apps.checkingRecent": "Checking",
+ "apps.recentWillUpdate": "The latest update will appear automatically",
"apps.notGenerated": "Not created yet",
"apps.saved": "Memory saved",
"apps.separate": "History and memories are processed separately",
@@ -1324,16 +1330,16 @@ const baseEnglishMessages = {
"apps.activityUnavailable": "Activity unavailable",
"apps.firstBatch": "First memories",
"apps.callsUnavailable": "Could not read call history",
- "apps.memoryUnavailable": "Could not read memory status",
+ "apps.memoryUnavailable": "The memory overview is not ready yet",
"apps.importing": "Importing conversations before creating memories",
"apps.firstRunning": "Creating the first memories",
"apps.firstQueued": "Preparing the first memories",
- "apps.readingActivity": "Loading activity",
+ "apps.readingActivity": "Preparing memory overview",
"apps.emptyMemories": "No memories created yet",
"apps.callReadFailure":
"You can still view saved memories. Retrying will not make a new call.",
"apps.memoryReadFailure":
- "A failed read does not mean there are no memories.",
+ "This will update when the service recovers. You can also retry now.",
"apps.savingConversations":
"Conversations are still being saved in the background.",
"apps.waitingMemories": "History is saved. New memories will appear here.",