Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: cancel stale CmdK search + clear Security media timeout on unmount/reschedule (#2543)

Adam Eivya7716c6dbf27
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5f90ac8d2f..ebde272250 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,7 @@
## Fixed
+- **[issue-2543] Cancel stale ⌘K global search responses and clear the Security device-change restart timer.** The command palette's global `search(query)` effect debounced the request but had no in-flight guard, so a slow response for an older query could resolve after the user typed on and overwrite the newer query's results (or flip the loading spinner off prematurely) — the sibling catalog-search effect already used a `cancelled` flag. The global-search effect now mirrors that `cancelled` guard so only the latest query's response applies. Separately, `Security.jsx`'s device-change handler scheduled `setTimeout(startMedia, 100)` with no clear on unmount or before rescheduling, so rapid device switches stacked multiple `startMedia()` calls and a navigation-away could fire the restart into an unmounted component; the timer id is now held in a ref, cleared before each reschedule, and cleared in an unmount cleanup effect. A regression test asserts a stale search response can't clobber the current query's results.
- **POST session run page crashed (React error #130) when transitioning into a cognitive drill.** `DrillTransition.jsx`'s `DOMAIN_ICONS` map was missing a `cognitive` entry, yet `DRILL_TO_DOMAIN` maps every cognitive drill type (n-back, digit-span, stroop, schulte-table, mental-rotation, reaction-time) to the `cognitive` domain — so finishing a drill whose successor was a cognitive drill (e.g. a Doubling Chain followed by a cognitive drill) resolved the transition-card icon to `undefined` and blanked the run page with a minified React error. Added the `cognitive: Brain` icon and hardened the lookup to fall back to `ChevronRight` for any unmapped domain, so a future domain gap degrades gracefully instead of crashing. A regression test renders the transition for every `DRILL_TO_DOMAIN` type.
- **[issue-2536] Catch unhandled rejections from Telegram handlers and health/probe timers.** Several async boundaries were fire-and-forget: the Telegram client dispatched `onText`/`emitter.on` handlers without awaiting or catching, `telegram.js` ran `setInterval(healthCheck)` and a couple of sync-context `bot.sendMessage(...)` calls without a `.catch`, and `instances.js` scheduled `probeAllPeers()` from `setTimeout`/`setInterval` without one — so a rejected handler or a failed fs/network read leaked an unhandled promise rejection (process-killing on Node ≥15). The client now routes every handler invocation through a `runHandler` wrapper that logs a single emoji-prefixed line on rejection; the health-check interval and both probe timers wrap their async callback in `.catch`; and the `/start`, `/help`, and unauthorized-notice sends now await or `.catch` their promise. A vitest suite drives the client's `onText` and `message` paths with a throwing handler and asserts no `unhandledRejection` escapes.
- **[issue-2519] CoS handlers no longer flash a false-success toast after a failed API call.** Several Chief of Staff actions (`handleForceEvaluate` on the CoS page, the Tasks tab "Run Now" button, and the Config tab's Save + autonomy-level change) `.catch`-swallowed the request rejection and then unconditionally toasted success and mutated optimistic UI — so a network/server error still read as "done." Each now awaits inside try/catch and only toasts success / advances state after the request resolves: a failed Save keeps the editor open, and a failed autonomy-level change reverts the optimistic form params. Errors surface via a single `toast.error` (the calls already pass `{ silent: true }`).
diff --git a/client/src/components/CmdKSearch.jsx b/client/src/components/CmdKSearch.jsx
index 8f408b1627..84b85d8242 100644
--- a/client/src/components/CmdKSearch.jsx
+++ b/client/src/components/CmdKSearch.jsx
@@ -170,12 +170,16 @@ export default function CmdKSearch() {
return;
}
setLoading(true);
+ // Mirror the catalog effect's cancelled guard so a slow in-flight
+ // response for an older query can't overwrite results for a newer one
+ // (or flip loading off) after the user has typed on.
+ let cancelled = false;
const timer = setTimeout(() => {
search(query)
- .then((data) => setSearchResults(data?.sources ?? []))
- .finally(() => setLoading(false));
+ .then((data) => { if (!cancelled) setSearchResults(data?.sources ?? []); })
+ .finally(() => { if (!cancelled) setLoading(false); });
}, 300);
- return () => clearTimeout(timer);
+ return () => { cancelled = true; clearTimeout(timer); };
}, [query]);
useEffect(() => {
diff --git a/client/src/components/CmdKSearch.test.jsx b/client/src/components/CmdKSearch.test.jsx
index 1ff7bf7b22..82b2dc202d 100644
--- a/client/src/components/CmdKSearch.test.jsx
+++ b/client/src/components/CmdKSearch.test.jsx
@@ -5,9 +5,10 @@ import { RECENT_KEY } from '../utils/navWorkingSet.js';
const getPaletteManifest = vi.fn();
const getDashboardLayouts = vi.fn();
+const search = vi.fn(() => Promise.resolve({ sources: [] }));
vi.mock('../services/api', () => ({
- search: vi.fn(() => Promise.resolve({ sources: [] })),
+ search: (...args) => search(...args),
getPaletteManifest: (...args) => getPaletteManifest(...args),
runPaletteAction: vi.fn(() => Promise.resolve({ ok: true })),
getDashboardLayouts: (...args) => getDashboardLayouts(...args),
@@ -33,6 +34,8 @@ function LocationProbe() {
beforeEach(() => {
getPaletteManifest.mockResolvedValue({ nav: NAV, actions: [] });
getDashboardLayouts.mockResolvedValue({ layouts: [] });
+ search.mockReset();
+ search.mockResolvedValue({ sources: [] });
HTMLElement.prototype.scrollIntoView = vi.fn();
});
@@ -68,3 +71,51 @@ describe('CmdKSearch recent destinations', () => {
await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/apps/example-app'));
});
});
+
+describe('CmdKSearch global search staleness', () => {
+ it('does not let a slow older-query response overwrite the newer query results', async () => {
+ vi.useFakeTimers();
+
+ // First (stale) query resolves late; second (current) query resolves fast.
+ let resolveStale;
+ const stalePromise = new Promise((res) => { resolveStale = res; });
+ search
+ .mockImplementationOnce(() => stalePromise)
+ .mockImplementationOnce(() => Promise.resolve({
+ sources: [{ id: 'brain', label: 'Brain', icon: 'Brain', results: [{ title: 'Fresh result', snippet: 'new', url: '/brain/x' }] }],
+ }));
+
+ render(
+ <MemoryRouter initialEntries={['/current']}>
+ <CmdKSearch />
+ </MemoryRouter>,
+ );
+
+ await act(async () => {
+ fireEvent.keyDown(document, { key: 'k', metaKey: true });
+ });
+
+ const input = screen.getByPlaceholderText(/Go to page/);
+
+ // Type first query and let its debounce elapse so the stale request fires.
+ await act(async () => { fireEvent.change(input, { target: { value: 'aa' } }); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });
+ expect(search).toHaveBeenNthCalledWith(1, 'aa');
+
+ // Type second query; its cleanup marks the first effect cancelled.
+ await act(async () => { fireEvent.change(input, { target: { value: 'bb' } }); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });
+ expect(search).toHaveBeenNthCalledWith(2, 'bb');
+
+ // Now the stale response finally arrives — it must be ignored.
+ await act(async () => {
+ resolveStale({ sources: [{ id: 'brain', label: 'Brain', icon: 'Brain', results: [{ title: 'Stale result', snippet: 'old', url: '/brain/y' }] }] });
+ await Promise.resolve();
+ });
+
+ expect(screen.getByText('Fresh result')).toBeInTheDocument();
+ expect(screen.queryByText('Stale result')).not.toBeInTheDocument();
+
+ vi.useRealTimers();
+ });
+});
diff --git a/client/src/pages/Security.jsx b/client/src/pages/Security.jsx
index 05dd6391eb..e36399d32f 100644
--- a/client/src/pages/Security.jsx
+++ b/client/src/pages/Security.jsx
@@ -13,6 +13,7 @@ export default function Security() {
const audioContextRef = useRef(null);
const analyserRef = useRef(null);
const animationFrameRef = useRef(null);
+ const deviceRestartTimerRef = useRef(null);
const [streaming, setStreaming] = useState(false);
const [videoEnabled, setVideoEnabled] = useState(true);
@@ -241,11 +242,23 @@ export default function Security() {
// Restart stream with new device if currently streaming
if (streaming) {
- // Small delay to let state update
- setTimeout(() => startMedia(), 100);
+ // Small delay to let state update. Clear any pending restart first so
+ // rapid device switches don't stack multiple startMedia() calls, and
+ // so an unmount can cancel the last one (see cleanup effect below).
+ if (deviceRestartTimerRef.current) clearTimeout(deviceRestartTimerRef.current);
+ deviceRestartTimerRef.current = setTimeout(() => {
+ deviceRestartTimerRef.current = null;
+ startMedia();
+ }, 100);
}
}, [streaming, startMedia]);
+ // Cancel any pending device-change restart on unmount so a deferred
+ // startMedia() can't fire into a component that's no longer mounted.
+ useEffect(() => () => {
+ if (deviceRestartTimerRef.current) clearTimeout(deviceRestartTimerRef.current);
+ }, []);
+
return (
<div>
{/* Header */}