Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix: load actions beyond the first page (#1524)

Som Samantray8a81e1d85bf3
diff --git a/src/functions/actions.ts b/src/functions/actions.ts
index 9bf583f6..6e263b3b 100644
--- a/src/functions/actions.ts
+++ b/src/functions/actions.ts
@@ -2,6 +2,7 @@ import type { IIIClient } from "iii-sdk";
import type { StateKV } from "../state/kv.js";
import { KV, generateId } from "../state/schema.js";
import { withKeyedLock } from "../state/keyed-mutex.js";
+import { pageAfterCursor, sortByKeyDesc } from "../state/list-query.js";
import type { Action, ActionEdge } from "../types.js";
import { recordAudit } from "./audit.js";
@@ -208,6 +209,7 @@ export function registerActionsFunction(sdk: IIIClient, kv: StateKV): void {
parentId?: string;
tags?: string[];
limit?: number;
+ cursor?: string;
}) => {
let actions = await kv.list<Action>(KV.actions);
@@ -226,13 +228,18 @@ export function registerActionsFunction(sdk: IIIClient, kv: StateKV): void {
);
}
- actions.sort(
- (a, b) =>
- new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
- );
+ const actionSortKey = (action: Action) => action.updatedAt || action.createdAt || "";
+ sortByKeyDesc(actions, actionSortKey, (action) => action.id);
- const limit = data.limit || 50;
- return { success: true, actions: actions.slice(0, limit) };
+ const limit = Math.max(1, data.limit || 50);
+ const paged = pageAfterCursor(
+ actions,
+ actionSortKey,
+ (action) => action.id,
+ data.cursor,
+ limit,
+ );
+ return { success: true, actions: paged.page, nextCursor: paged.nextCursor };
},
);
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index f4eaf079..05ec0e65 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -3204,10 +3204,13 @@ export function registerApiTriggers(
async (req: HttpRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
+ const listQuery = parseListQuery(req.query_params);
const result = await sdk.trigger({ function_id: "mem::action-list", payload: {
status: req.query_params?.["status"],
project: req.query_params?.["project"],
parentId: req.query_params?.["parentId"],
+ limit: listQuery.limit,
+ cursor: listQuery.cursor,
} });
return { status_code: 200, body: result };
},
diff --git a/src/viewer/index.html b/src/viewer/index.html
index e4eb16e8..9873cc96 100644
--- a/src/viewer/index.html
+++ b/src/viewer/index.html
@@ -1676,7 +1676,7 @@
audit: { opFilter: '', selectedIdx: null, from: '', to: '', q: '', query: null, loadingMore: false, exhausted: {}, fresh: {} },
activity: { loaded: false, observations: [], sessionCount: 0, typeFilter: '', fileFilter: '', day: '' },
lessons: { search: '', selectedId: null, projectFilter: '', notice: null, busy: '' },
- actions: { frontier: [], statusFilter: '', search: '', selectedId: null, notice: null, busy: '' },
+ actions: { frontier: [], statusFilter: '', search: '', selectedId: null, notice: null, busy: '', detailLoading: '', detailAttemptedId: '', detailRequestFailedId: '', loadError: false },
crystals: { search: '', selectedId: null },
profile: { loaded: false, selectedProject: '', data: null, dataProject: '', userPicked: false, notice: null },
health: { error: null, checking: false, consolidating: false, reveal: '' },
@@ -1714,7 +1714,7 @@
memory: { path: 'memories?latest=true&limit=100&facets=true', key: 'memories' },
session: { path: 'sessions?limit=100&facets=true', key: 'sessions' },
lesson: { path: 'lessons', key: 'lessons' },
- action: { path: 'actions', key: 'actions' },
+ action: { path: 'actions', key: 'actions', allPages: true },
crystal: { path: 'crystals', key: 'crystals' },
semantic: { path: 'semantic', key: 'facts', fallbackKey: 'semantic' },
procedural: { path: 'procedural', key: 'procedures', fallbackKey: 'procedural' },
@@ -2314,6 +2314,20 @@
store.entities[kind] = bucket;
}
+ async function loadAllPages(spec, apiGet) {
+ var rows = [];
+ var cursor = null;
+ var result;
+ do {
+ var path = spec.path + '?limit=500' + (cursor ? '&cursor=' + encodeURIComponent(cursor) : '');
+ result = await apiGet(path);
+ if (result === null) return null;
+ rows.push.apply(rows, listOr([], result, spec.key, spec.fallbackKey));
+ cursor = result.nextCursor || null;
+ } while (cursor);
+ return Object.assign({}, result, { [spec.key]: rows });
+ }
+
async function ensureLoaded(kind) {
if (store.loaded[kind]) return;
if (store.loading[kind]) return store.loading[kind];
@@ -2323,8 +2337,16 @@
try {
await bootGate;
var seqAtStart = eventSeq;
- var result = await apiGet(spec.path);
- if (result === null) return;
+ var result;
+ if (spec.allPages) {
+ result = await loadAllPages(spec, apiGet);
+ } else {
+ result = await apiGet(spec.path);
+ }
+ if (result === null) {
+ if (kind === 'action') state.actions.loadError = true;
+ return;
+ }
replaceBucket(kind, listOr([], result, spec.key, spec.fallbackKey));
if (kind === 'memory') {
state.memories.nextCursor = result.nextCursor || null;
@@ -2343,6 +2365,9 @@
}
replayEventsSince(seqAtStart, kind);
store.loaded[kind] = true;
+ if (kind === 'action') state.actions.loadError = false;
+ } catch {
+ if (kind === 'action') state.actions.loadError = true;
} finally {
store.loading[kind] = null;
}
@@ -6551,12 +6576,15 @@
function renderActions() {
var el = document.getElementById('view-actions');
var a = state.actions;
- if (!store.loaded.action) {
+ var all = entityList('action');
+ if (!store.loaded.action && !all.length) {
listDetailShell(el, 'actions', '');
- setViewHtml(document.getElementById('actions-list'), skeleton(8));
+ setViewHtml(document.getElementById('actions-list'), a.loadError
+ ? '<div class="empty-state compact"><div class="empty-title">Could not load actions</div><div class="empty-what">Check that agentmemory is running, then try again.</div><button type="button" class="btn" data-action="action-list-retry">Retry</button></div>'
+ : skeleton(8));
+ renderActionDetail({});
return;
}
- var all = entityList('action');
var rows = actionRows();
var frontierIds = {};
(a.frontier || []).forEach(function(f) {
@@ -6614,24 +6642,82 @@
html += '</tbody></table></div>';
if (all.length < 8) html += usageCard('action');
}
+ if (a.loadError) {
+ html = '<div class="inline-note"><strong>Could not refresh actions.</strong> Showing previously loaded actions. <button type="button" class="btn" data-action="action-list-retry">Retry</button></div>' + html;
+ }
setViewHtml(document.getElementById('actions-list'), html);
+ renderActionDetail(frontierIds);
+ }
+
+ function renderActionDetail(frontierIds) {
+ var a = state.actions;
var detail = document.getElementById('actions-detail');
var sel = a.selectedId ? store.entities.action[a.selectedId] : null;
if (a.selectedId && !sel) {
- setViewHtml(detail, '<div id="action-detail" class="detail-panel mem-detail"><div class="mem-detail-head"><span>Action</span><button type="button" class="icon-btn icon-close" data-action="action-close" aria-label="Close action details">close</button></div>' + emptyState({
+ ensureActionById(a.selectedId);
+ var loadingAction = a.detailLoading === a.selectedId;
+ var actionBody = loadingAction ? '<div class="empty-state compact"><div class="empty-title">Loading action…</div></div>' : a.detailRequestFailedId === a.selectedId
+ ? '<div class="empty-state compact"><div class="empty-title">Could not load action</div><div class="empty-what">Check that agentmemory is running, then try again.</div><button type="button" class="btn" data-action="action-retry">Retry</button></div>'
+ : emptyState({
compact: true,
icon: '&#128269;',
title: 'Action not found',
what: 'Action links anywhere in the viewer open this panel by id.',
why: 'No action has the id <code>' + esc(a.selectedId) + '</code>. It was removed, or the link comes from another install.',
steps: [{ label: 'Check from a terminal:', cmd: curlGet('actions/get?actionId=' + encodeURIComponent(a.selectedId)) }]
- }) + '</div>');
+ });
+ setViewHtml(detail, '<div id="action-detail" class="detail-panel mem-detail"><div class="mem-detail-head"><span>Action</span><button type="button" class="icon-btn icon-close" data-action="action-close" aria-label="Close action details">close</button></div>' + actionBody + '</div>');
} else {
setViewHtml(detail, sel ? actionDetailHtml(sel, !!frontierIds[sel.id]) : '');
}
document.getElementById('actions-layout').classList.toggle('has-detail', !!detail.firstElementChild);
}
+ async function ensureActionById(id) {
+ var a = state.actions;
+ if (!id || store.entities.action[id] || a.detailLoading === id || a.detailAttemptedId === id) return;
+ a.detailAttemptedId = id;
+ a.detailLoading = id;
+ try {
+ var result = await apiGet('actions/get?actionId=' + encodeURIComponent(id));
+ if (result && result.success && result.action && result.action.id) {
+ store.entities.action[result.action.id] = result.action;
+ a.detailRequestFailedId = '';
+ renderActions();
+ } else if (result === null) {
+ a.detailRequestFailedId = id;
+ }
+ } catch (_) {
+ a.detailRequestFailedId = id;
+ } finally {
+ if (a.detailLoading === id) {
+ a.detailLoading = '';
+ if (!store.entities.action[id]) renderActions();
+ }
+ }
+ }
+
+ function retryActionById(id) {
+ var a = state.actions;
+ if (a.detailLoading === id) return;
+ a.detailAttemptedId = '';
+ a.detailRequestFailedId = '';
+ return ensureActionById(id);
+ }
+
+ async function retryActionList() {
+ if (store.loading.action) return store.loading.action;
+ state.actions.loadError = false;
+ store.loaded.action = false;
+ renderActions();
+ await ensureLoaded('action');
+ if (state.actions.selectedId && !store.entities.action[state.actions.selectedId]) {
+ state.actions.detailAttemptedId = '';
+ state.actions.detailRequestFailedId = '';
+ }
+ renderActions();
+ }
+
async function setActionStatus(id, status) {
var a = state.actions;
a.busy = id;
@@ -6733,6 +6819,8 @@
return true;
}
if (action === 'action-close') { state.actions.selectedId = null; setRouteEntity('actions', ''); renderActions(); return true; }
+ if (action === 'action-retry') { retryActionById(state.actions.selectedId); return true; }
+ if (action === 'action-list-retry') { retryActionList(); return true; }
if (action === 'action-set-status') { setActionStatus(target.getAttribute('data-action-id'), target.getAttribute('data-status')); return true; }
if (action === 'action-clear-filters') { state.actions.search = ''; state.actions.statusFilter = ''; var ai = document.getElementById('actions-search'); if (ai) ai.value = ''; renderActions(); return true; }
if (action === 'activity-type' || action === 'activity-file' || action === 'activity-day' || action === 'activity-clear') { handleActivityAction(action, target); return true; }
@@ -7843,6 +7931,14 @@
}
var resyncing = null;
+ function resetLoadedKindForReload(kind) {
+ store.loaded[kind] = false;
+ if (kind === 'action') {
+ state.actions.detailAttemptedId = '';
+ state.actions.detailRequestFailedId = '';
+ }
+ }
+
async function resyncAfterConnect(firstConnect) {
openBootGate();
if (resyncing) return resyncing;
@@ -7852,7 +7948,7 @@
await loadSnapshot();
scheduleHealthStaleCheck();
if (!firstConnect || reloadKinds.length) {
- reloadKinds.forEach(function(k) { store.loaded[k] = false; });
+ reloadKinds.forEach(resetLoadedKindForReload);
await Promise.all(reloadKinds.map(ensureLoaded));
state.graph.dirty = state.graph.loaded;
state.activity.loaded = false;
diff --git a/test/actions.test.ts b/test/actions.test.ts
index 156ba795..9111ff82 100644
--- a/test/actions.test.ts
+++ b/test/actions.test.ts
@@ -5,6 +5,7 @@ vi.mock("../src/logger.js", () => ({
}));
import { registerActionsFunction } from "../src/functions/actions.js";
+import { KV } from "../src/state/schema.js";
import type { Action, ActionEdge } from "../src/types.js";
import { mockKV, mockSdk } from "./helpers/mocks.js";
@@ -391,6 +392,52 @@ describe("Actions Functions", () => {
expect(result.success).toBe(true);
expect(result.actions.length).toBe(2);
});
+
+ it("preserves direct function limits above the REST page cap", async () => {
+ const now = new Date().toISOString();
+ for (let i = 0; i < 501; i++) {
+ const action = {
+ id: `act_limit_${i}`,
+ title: `Limit action ${i}`,
+ status: "pending",
+ priority: 5,
+ createdAt: now,
+ updatedAt: now,
+ createdBy: "test",
+ tags: [],
+ sourceObservationIds: [],
+ sourceMemoryIds: [],
+ } as Action;
+ await kv.set(KV.actions, action.id, action);
+ }
+
+ const result = (await sdk.trigger("mem::action-list", { limit: 502 })) as {
+ actions: Action[];
+ };
+
+ expect(result.actions).toHaveLength(502);
+ });
+
+ it("pages actions beyond the first 50 rows", async () => {
+ for (let i = 0; i < 55; i++) {
+ await sdk.trigger("mem::action-create", { title: `Page action ${i}` });
+ }
+
+ const first = (await sdk.trigger("mem::action-list", { limit: 50 })) as {
+ actions: Action[];
+ nextCursor: string | null;
+ };
+ expect(first.actions).toHaveLength(50);
+ expect(first.nextCursor).toEqual(expect.any(String));
+
+ const second = (await sdk.trigger("mem::action-list", {
+ limit: 50,
+ cursor: first.nextCursor,
+ })) as { actions: Action[]; nextCursor: string | null };
+ expect(second.actions).toHaveLength(8);
+ expect(second.nextCursor).toBeNull();
+ expect(new Set([...first.actions, ...second.actions].map((action) => action.id)).size).toBe(58);
+ });
});
describe("mem::action-get", () => {
diff --git a/test/api-list-pagination.test.ts b/test/api-list-pagination.test.ts
index 23fb8635..70bfeef3 100644
--- a/test/api-list-pagination.test.ts
+++ b/test/api-list-pagination.test.ts
@@ -47,7 +47,7 @@ function setup(seed: Record<string, Record<string, unknown>>) {
};
const kv = mockKV(seed);
registerApiTriggers(sdk as never, kv as never);
- return { handlers, kv };
+ return { handlers, kv, sdk };
}
async function call(handlers: Map<string, Handler>, id: string, query_params: Record<string, string>) {
@@ -269,4 +269,29 @@ describe("paginated and filtered list endpoints", () => {
expect(bad.status_code).toBe(400);
index.remove("obs_locate_1");
});
+
+ it("forwards action pagination parameters and returns the next cursor", async () => {
+ const { handlers, sdk } = setup({});
+ const firstPage = {
+ success: true,
+ actions: [{ id: "act_1" }, { id: "act_2" }],
+ nextCursor: "next-page",
+ };
+ sdk.trigger.mockResolvedValueOnce(firstPage as never);
+
+ const first = await call(handlers, "api::action-list", { limit: "2" });
+ expect(first.body).toEqual(firstPage);
+ expect(sdk.trigger).toHaveBeenLastCalledWith({
+ function_id: "mem::action-list",
+ payload: { status: undefined, project: undefined, parentId: undefined, limit: 2, cursor: undefined },
+ });
+
+ sdk.trigger.mockResolvedValueOnce({ ...firstPage, actions: [{ id: "act_3" }], nextCursor: null } as never);
+ const second = await call(handlers, "api::action-list", { limit: "2", cursor: "next-page" });
+ expect(second.body.nextCursor).toBeNull();
+ expect(sdk.trigger).toHaveBeenLastCalledWith({
+ function_id: "mem::action-list",
+ payload: { status: undefined, project: undefined, parentId: undefined, limit: 2, cursor: "next-page" },
+ });
+ });
});
diff --git a/test/viewer-actions.test.ts b/test/viewer-actions.test.ts
new file mode 100644
index 00000000..079d07a0
--- /dev/null
+++ b/test/viewer-actions.test.ts
@@ -0,0 +1,196 @@
+import { describe, it, expect, vi } from "vitest";
+import { readFileSync } from "node:fs";
+
+const viewer = readFileSync("src/viewer/index.html", "utf-8");
+
+function extractFunction(name: string): string {
+ let start = viewer.indexOf(`function ${name}(`);
+ if (start < 0) throw new Error(`function ${name} not found in viewer`);
+ if (viewer.slice(start - 6, start) === "async ") start -= 6;
+ let depth = 0;
+ for (let i = viewer.indexOf("{", start); i < viewer.length; i++) {
+ if (viewer[i] === "{") depth++;
+ if (viewer[i] === "}") {
+ depth--;
+ if (depth === 0) return viewer.slice(start, i + 1);
+ }
+ }
+ throw new Error(`function ${name} is not balanced`);
+}
+
+describe("viewer actions", () => {
+ it("loads every action page for the Actions tab", () => {
+ expect(viewer).toMatch(/action: \{ path: 'actions', key: 'actions', allPages: true \}/);
+ });
+
+ it("resets selected-action lookup state when reloading actions", () => {
+ const resetLoadedKindForReload = new Function(
+ "state",
+ "store",
+ `return ${extractFunction("resetLoadedKindForReload")};`,
+ ) as (
+ state: { actions: { detailAttemptedId: string; detailRequestFailedId: string } },
+ store: { loaded: Record<string, boolean> },
+ ) => (kind: string) => void;
+ const state = { actions: { detailAttemptedId: "act_selected", detailRequestFailedId: "act_selected" } };
+ const store = { loaded: { action: true, lesson: true } };
+ const reset = resetLoadedKindForReload(state, store);
+
+ reset("lesson");
+ expect(store.loaded.lesson).toBe(false);
+ expect(state.actions.detailAttemptedId).toBe("act_selected");
+
+ reset("action");
+ expect(store.loaded.action).toBe(false);
+ expect(state.actions.detailAttemptedId).toBe("");
+ expect(state.actions.detailRequestFailedId).toBe("");
+ });
+
+ it("follows action cursors and combines all pages", async () => {
+ const loadAllPages = new Function(
+ "listOr",
+ `return ${extractFunction("loadAllPages")};`,
+ )((fallback: unknown[], result: Record<string, unknown>, key: string) => result[key] || fallback) as (
+ spec: { path: string; key: string },
+ apiGet: (path: string) => Promise<Record<string, unknown>>,
+ ) => Promise<Record<string, unknown>>;
+ const apiGet = vi.fn()
+ .mockResolvedValueOnce({ actions: [{ id: "a" }], nextCursor: "next /?" })
+ .mockResolvedValueOnce({ actions: [{ id: "b" }], nextCursor: null });
+
+ const result = await loadAllPages({ path: "actions", key: "actions" }, apiGet);
+
+ expect(apiGet.mock.calls).toEqual([
+ ["actions?limit=500"],
+ ["actions?limit=500&cursor=next%20%2F%3F"],
+ ]);
+ expect(result.actions).toEqual([{ id: "a" }, { id: "b" }]);
+ });
+
+ it("stops the all-pages load when a later page fails", async () => {
+ const loadAllPages = new Function(
+ "listOr",
+ `return ${extractFunction("loadAllPages")};`,
+ )((fallback: unknown[], result: Record<string, unknown>, key: string) => result[key] || fallback) as (
+ spec: { path: string; key: string },
+ apiGet: (path: string) => Promise<Record<string, unknown> | null>,
+ ) => Promise<Record<string, unknown> | null>;
+ const apiGet = vi.fn()
+ .mockResolvedValueOnce({ actions: [{ id: "a" }], nextCursor: "next" })
+ .mockResolvedValueOnce(null);
+
+ await expect(loadAllPages({ path: "actions", key: "actions" }, apiGet)).resolves.toBeNull();
+ expect(apiGet).toHaveBeenCalledTimes(2);
+ });
+
+ it("exposes retry after an action collection load failure while retaining cached rows", () => {
+ const ensureLoaded = extractFunction("ensureLoaded");
+ const renderActions = extractFunction("renderActions");
+ expect(ensureLoaded).toMatch(/if \(result === null\) \{\s*if \(kind === 'action'\) state\.actions\.loadError = true;/);
+ expect(ensureLoaded).toMatch(/if \(kind === 'action'\) state\.actions\.loadError = false;/);
+ expect(renderActions).toMatch(/var all = entityList\('action'\);\s*if \(!store\.loaded\.action && !all\.length\)/);
+ expect(renderActions).toMatch(/data-action="action-list-retry"/);
+ expect(renderActions).toMatch(/Showing previously loaded actions/);
+ expect(extractFunction("handlePageAction")).toMatch(/action === 'action-list-retry'\) \{ retryActionList\(\); return true; \}/);
+ });
+
+ it("continues selected-action lookup when the action list has failed", () => {
+ const renderActions = extractFunction("renderActions");
+ const renderActionDetail = extractFunction("renderActionDetail");
+ expect(renderActions).toMatch(/if \(!store\.loaded\.action && !all\.length\) \{[\s\S]*?renderActionDetail\(\{\}\);\s*return;/);
+ expect(renderActionDetail).toMatch(/if \(a\.selectedId && !sel\) \{\s*ensureActionById\(a\.selectedId\);/);
+ });
+
+ it("retries the action collection and clears its failed state before loading", async () => {
+ const retryActionList = new Function(
+ "state",
+ "store",
+ "renderActions",
+ "ensureLoaded",
+ `return ${extractFunction("retryActionList")};`,
+ ) as (
+ state: { actions: { loadError: boolean; selectedId: string; detailAttemptedId: string; detailRequestFailedId: string } },
+ store: { loaded: { action: boolean }; loading: { action: Promise<void> | null }; entities: { action: Record<string, unknown> } },
+ renderActions: () => void,
+ ensureLoaded: (kind: string) => Promise<void>,
+ ) => () => Promise<void>;
+ const state = { actions: { loadError: true, selectedId: "act_deep_link", detailAttemptedId: "act_deep_link", detailRequestFailedId: "act_deep_link" } };
+ const store = { loaded: { action: true }, loading: { action: null }, entities: { action: {} } };
+ const renderActions = vi.fn();
+ const ensureLoaded = vi.fn(async () => { state.actions.loadError = false; store.loaded.action = true; });
+
+ await retryActionList(state, store, renderActions, ensureLoaded)();
+
+ expect(state.actions.loadError).toBe(false);
+ expect(state.actions.detailAttemptedId).toBe("");
+ expect(state.actions.detailRequestFailedId).toBe("");
+ expect(store.loaded.action).toBe(true);
+ expect(ensureLoaded).toHaveBeenCalledWith("action");
+ expect(renderActions).toHaveBeenCalledTimes(2);
+ });
+
+ it("fetches a selected action by id when it is missing from the loaded list", async () => {
+ const loadEnsureActionById = new Function(
+ "state",
+ "store",
+ "apiGet",
+ "renderActions",
+ `return ${extractFunction("ensureActionById")};`,
+ ) as (
+ state: { actions: { detailLoading: string; detailAttemptedId: string; detailRequestFailedId: string } },
+ store: { entities: { action: Record<string, unknown> } },
+ apiGet: (path: string) => Promise<{ success: boolean; action: { id: string } }>,
+ renderActions: () => void,
+ ) => (id: string) => Promise<void>;
+ const action = { id: "act_outside_first_page" };
+ const apiGet = vi.fn(async () => ({ success: true, action }));
+ const renderActions = vi.fn();
+ const state = { actions: { detailLoading: "", detailAttemptedId: "", detailRequestFailedId: "" } };
+ const store = { entities: { action: {} } };
+
+ await loadEnsureActionById(state, store, apiGet, renderActions)("act_outside_first_page");
+
+ expect(apiGet).toHaveBeenCalledWith("actions/get?actionId=act_outside_first_page");
+ expect(store.entities.action.act_outside_first_page).toBe(action);
+ expect(renderActions).toHaveBeenCalledOnce();
+ });
+
+ it("allows retrying an action lookup after a request failure", async () => {
+ const loadEnsureActionById = new Function(
+ "state",
+ "store",
+ "apiGet",
+ "renderActions",
+ `return ${extractFunction("ensureActionById")};`,
+ ) as (
+ state: { actions: { detailLoading: string; detailAttemptedId: string; detailRequestFailedId: string } },
+ store: { entities: { action: Record<string, unknown> } },
+ apiGet: (path: string) => Promise<{ success: boolean; action: { id: string } } | null>,
+ renderActions: () => void,
+ ) => (id: string) => Promise<void>;
+ const action = { id: "act_outside_first_page" };
+ const apiGet = vi.fn()
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce({ success: true, action });
+ const renderActions = vi.fn();
+ const state = { actions: { detailLoading: "", detailAttemptedId: "", detailRequestFailedId: "" } };
+ const store = { entities: { action: {} } };
+ const ensureActionById = loadEnsureActionById(state, store, apiGet, renderActions);
+
+ await ensureActionById(action.id);
+ expect(state.actions.detailRequestFailedId).toBe(action.id);
+ await ensureActionById(action.id);
+ expect(apiGet).toHaveBeenCalledOnce();
+
+ const retryActionById = new Function(
+ "state",
+ "ensureActionById",
+ `return ${extractFunction("retryActionById")};`,
+ )(state, ensureActionById) as (id: string) => Promise<void>;
+ await retryActionById(action.id);
+
+ expect(apiGet).toHaveBeenCalledTimes(2);
+ expect(store.entities.action[action.id]).toBe(action);
+ expect(state.actions.detailRequestFailedId).toBe("");
+ });
+});
diff --git a/test/viewer-dashboard-reliability.test.ts b/test/viewer-dashboard-reliability.test.ts
index 07211a86..a52e6646 100644
--- a/test/viewer-dashboard-reliability.test.ts
+++ b/test/viewer-dashboard-reliability.test.ts
@@ -104,7 +104,7 @@ describe("viewer streams instead of polling", () => {
it("fetches the snapshot once per connection and replays events that arrived during a list load", () => {
const resync = extractFunction("resyncAfterConnect");
expect(resync).toMatch(/await loadSnapshot\(\);/);
- expect(resync).toMatch(/reloadKinds\.forEach\(function\(k\) \{ store\.loaded\[k\] = false; \}\);/);
+ expect(resync).toMatch(/reloadKinds\.forEach\(resetLoadedKindForReload\);/);
expect(extractFunction("loadSnapshot")).toMatch(/apiGet\('viewer\/snapshot'\)/);
const ensure = extractFunction("ensureLoaded");
expect(ensure).toMatch(/var seqAtStart = eventSeq;/);