Files
fusion/packages/dashboard/app/utils/taskStuck.ts
gsxdsm f26cbedf4f fix(dashboard): close the code-review findings on the mobile tab-discard work
An 11-reviewer pass over f157bf7460..f5163d8351 found defects in the mobile
tab-discard change set itself. This fixes them.

Silent data loss (the recurring defect class):
- AgentDetailView reconnect refetched limit:100 and replaced wholesale, so 380
  displayed lines vanished with no "Load older" and no indicator; it now
  reconciles through the shared logStreamReconcile helper.
- useActivityLog.loadMore past the cap discarded the page it had just fetched
  while advancing the cursor and leaving hasMore true, so the feed silently
  stopped paginating behind a live-looking button.
- useAgentLogs: loadMore and resyncFromServer had no mutual exclusion, a
  no-overlap resync discarded explicitly paged-back history, a resync outliving
  the reconnect delay left an unmarked gap, and the live-tail trim could evict
  the gap marker itself.
- useLiveTranscript's resync overwrote live entries that raced the refetch.

The premise itself was not fully delivered:
- useProjects, useNodes, and useMeshState never called clearInterval, so they
  polled the whole time the tab was hidden. useProjects is mounted for the
  entire session, so the page never went idle -- the primary mechanism this
  work depends on. All three now use the shared visibility gate.
- sse-bus fired onReconnect twice per reconnect cycle and fanned out ~28
  subscribers in one tick, against a ~6-connection-per-origin cap on a waking
  radio. The successful open is now the single authority, and the fan-out uses
  the same exported stagger primitive as the polling path rather than a second
  copy of the slot formula.
- A channel first subscribed during the hidden window opened a live EventSource
  and keepalive; suspension is now a module-level condition openChannel
  consults, and a channel opened inside the grace window re-arms it.

Credentials and correctness:
- The service worker persisted every GET /api/* to durable Cache Storage,
  including /api/settings with daemonToken, githubAuthToken, gitlabAuthToken
  and ntfyAccessToken in plaintext, with no exclusion and no purge path --
  "Clear all cached data" only walked localStorage. Now gated, bounded, and
  genuinely purgeable.
- useTasks cleared its own snapshot when the mount revalidation failed on a
  waking radio, so the board blanked and the next restore was empty too.
  Suspension-class failures no longer destroy the cache.
- A single-row SSE update reset lastFetchTimeMs to now while an hours-old
  hydrated snapshot was on screen, re-marking every in-progress card stuck.
- ListView's "Select all visible tasks" acted on the full filtered set while
  only 50 rows rendered, so a bulk delete reached rows the operator could not
  see. Column's search window reset keyed on a boolean, so refining a query
  kept the expanded window.

Tests that could not fail:
- App.test.tsx mocked TerminalModal as isOpen ? <div/> : null, making the
  unmount-on-close invariant unobservable; MockEventSource kept its listeners
  after close(), so cases passed with their onReconnect handlers deleted.
- The SSE resync ratchet scanned only hooks/, exempting ~13 component call
  sites -- the exact regression it exists to prevent.
- MissionControlPanel's bespoke poll and the xterm scrollback constants and
  WebGL disposal had no coverage at all.

Verified: tsc -p tsconfig.app.json clean, pnpm lint clean, pnpm
check:changesets clean, 877 tests passing across 36 scoped files.
Known unrelated red: MailboxView.test.tsx's FN-8407 CSS guard fails at HEAD
too -- this diff adds no @media rule and no .mailbox-view--mobile selector,
the only two things that assertion inspects. Left alone deliberately.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 11:17:52 -07:00

68 lines
2.4 KiB
TypeScript

import type { Task } from "@fusion/core";
import { isOverdue } from "./dataFreshness";
const NON_STUCK_STATUSES = new Set(["failed", "stuck-killed"]);
/**
* Check if a task is stuck based on the project's stuck timeout setting.
*
* A task is considered stuck when:
* - It is in the "in-progress" column
* - A positive `taskStuckTimeoutMs` value is provided (stuck detection enabled)
* - Its `updatedAt` timestamp is older than `taskStuckTimeoutMs` milliseconds ago
* compared to `dataAsOfMs` (or `Date.now()` if `dataAsOfMs` is not provided)
*
* When `taskStuckTimeoutMs` is undefined, null, or 0, stuck detection is
* disabled and this function always returns false.
*
* The optional `dataAsOfMs` parameter represents when the task data was last
* confirmed fresh by the server. When provided, it is used instead of `Date.now()`
* for the comparison. This prevents false positives when the tab has been in
* the background and the task data is stale.
*/
export function isTaskStuck(task: Task, taskStuckTimeoutMs: number | undefined, dataAsOfMs?: number): boolean {
if (task.column !== "in-progress") {
return false;
}
if (task.status && NON_STUCK_STATUSES.has(task.status)) {
return false;
}
if (!taskStuckTimeoutMs || taskStuckTimeoutMs <= 0) {
return false;
}
/*
FNXC:MobileTabDiscard 2026-07-26-10:16:
The clock choice moved to `isOverdue` (utils/dataFreshness.ts) so the same rule serves every
staleness verdict in the client and `dataAsOfMs` cannot be omitted at a call site. Behavior is
unchanged: `dataAsOfMs ?? Date.now()`, strict `>` against a threshold already proven positive above,
and an unparseable `updatedAt` (NaN) still yields false.
*/
const updatedAt = new Date(task.updatedAt).getTime();
return isOverdue(updatedAt, taskStuckTimeoutMs, dataAsOfMs);
}
/**
* Derive the stuck task count from a list of tasks using the given threshold.
*
* Returns 0 when stuck detection is disabled (undefined/0 threshold).
*
* The optional `dataAsOfMs` parameter is passed through to `isTaskStuck()` for
* freshness-aware stuck detection.
*/
export function countStuckTasks(tasks: Task[], taskStuckTimeoutMs: number | undefined, dataAsOfMs?: number): number {
if (!taskStuckTimeoutMs || taskStuckTimeoutMs <= 0) {
return 0;
}
let count = 0;
for (const task of tasks) {
if (isTaskStuck(task, taskStuckTimeoutMs, dataAsOfMs)) {
count++;
}
}
return count;
}