Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): make nudge tiers measure agent active time, not wall-clock
Diego Zacariasbb92e68f7ed1
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex 4fcc2e210..034cb1673 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.318",+ "version": "0.1.319","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.318",+ "version": "0.1.319","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex 6803ebb82..d044facc6 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.318",+ "version": "0.1.319","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",diff --git a/desktop-app/ui/src/components/agents/__tests__/nudgeArea.test.tsx b/desktop-app/ui/src/components/agents/__tests__/nudgeArea.test.tsxindex d4d336119..5f4c936e9 100644--- a/desktop-app/ui/src/components/agents/__tests__/nudgeArea.test.tsx+++ b/desktop-app/ui/src/components/agents/__tests__/nudgeArea.test.tsx@@ -139,6 +139,15 @@ describe('NudgeArea (D.5b)', () => {}})+ it('renders nothing right after an approval when the active age is short', () => {+ // The reported symptom, at the surface the user sees: approving after a+ // 10min gate wait leaves a wall-clock age of ~620s (T4 territory), but the+ // agent only worked ~20s. `useTaskTier` deducts the accumulated `pausedMs`,+ // so no "still working" nudge fires on resume.+ const { container } = renderNudge(task(620_000, { pausedMs: 600_000 }))+ expect(container.firstChild).toBeNull()+ })+it('stops showing a nudge after switching to a chat with no task', () => {// Key-aware fake: agent-x::c1 has a long-running (T3) task; c2 has none.const byKey = new Map<string, TaskState>([['agent-x::c1', task(150_000)]])diff --git a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/__tests__/taskTracker.test.ts b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/__tests__/taskTracker.test.tsindex 698e3680f..78e54c0ff 100644--- a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/__tests__/taskTracker.test.ts+++ b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/__tests__/taskTracker.test.ts@@ -1,5 +1,6 @@// @vitest-environment jsdomimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { classifyTier } from '@hooks/useTaskTier'import { TaskTracker } from '../taskTracker'import { type TaskKey, type TaskState, makeTaskKey } from '../types'@@ -276,6 +277,9 @@ describe('TaskTracker', () => {expect(tracker.get(KEY)?.pausedAt).toBe(firstPausedAt)expect(tracker.get(KEY)?.status).toBe('suspended')expect(tracker.get(KEY)?.pendingApproval?.requestId).toBe('req-1')+ // The other half of the invariant: a replay must not CLOSE (or double-count)+ // the open segment either — the accumulator stays untouched.+ expect(tracker.get(KEY)?.pausedMs).toBeUndefined()})it('a genuine re-suspension after a resume DOES re-stamp pausedAt', async () => {@@ -308,6 +312,124 @@ describe('TaskTracker', () => {expect(tracker.get(KEY)?.pausedAt).toBe(firstPausedAt! + 120_000)expect(tracker.get(KEY)?.pendingApproval?.requestId).toBe('req-2')+ // The first wait (60s) closed into the accumulator when `tool_start` resumed.+ expect(tracker.get(KEY)?.pausedMs).toBe(60_000)+ })++ it('resuming closes the pause segment so the tier stays on ACTIVE time (§AC3)', async () => {+ // THE reported bug: approve after 10min at the gate and the task resumed+ // straight into T4 ("your agent is still working, safe to close this window"),+ // because the age went back to `now - startedAt` — human wait included.+ let clock = Date.now()+ vi.spyOn(Date, 'now').mockImplementation(() => clock)+ tracker.setCallbacks({ onTerminal: vi.fn(), onSuspended: vi.fn(), onResumed: vi.fn() })+ tracker.start(KEY, 'task-1', 'um-1')+ const startedAt = tracker.get(KEY)!.startedAt++ clock += 20_000 // 20s of real agent work before the gate+ await rpc.emit({+ type: 'suspended',+ data: { taskId: 'task-1', requestId: 'req-1', displayName: 'Shell', reason: 'approval' },+ })+ clock += 600_000 // the user thinks about it for 10 minutes+ await rpc.emit({+ type: 'tool_start',+ data: { taskId: 'task-1', toolCallId: 'tc-1', toolName: 'shell', iteration: 2 },+ })++ const state = tracker.get(KEY)!+ expect(state.pausedMs).toBe(600_000)+ expect(state.pausedAt).toBeUndefined() // invariant: no OPEN segment while running+ expect(classifyTier(clock - startedAt - (state.pausedMs ?? 0))).toBe('T1')+ })++ it('accumulates pausedMs across two suspend/resume cycles', async () => {+ let clock = Date.now()+ vi.spyOn(Date, 'now').mockImplementation(() => clock)+ tracker.setCallbacks({ onTerminal: vi.fn(), onSuspended: vi.fn(), onResumed: vi.fn() })+ tracker.start(KEY, 'task-1', 'um-1')+ const startedAt = tracker.get(KEY)!.startedAt++ const suspend = (requestId: string) =>+ rpc.emit({+ type: 'suspended',+ data: { taskId: 'task-1', requestId, displayName: 'Shell', reason: 'approval' },+ })+ const resumeViaTool = (toolCallId: string) =>+ rpc.emit({+ type: 'tool_start',+ data: { taskId: 'task-1', toolCallId, toolName: 'shell', iteration: 2 },+ })++ clock += 10_000 // active+ await suspend('req-1')+ clock += 300_000 // paused+ await resumeViaTool('tc-1')+ clock += 15_000 // active+ await suspend('req-2')+ clock += 600_000 // paused+ await resumeViaTool('tc-2')+ clock += 5_000 // active++ const state = tracker.get(KEY)!+ expect(state.pausedMs).toBe(900_000)+ expect(state.pausedAt).toBeUndefined()+ // 30s of active work across the two gates — nowhere near the 15min wall-clock.+ expect(clock - startedAt - state.pausedMs!).toBe(30_000)+ })++ it('resuming via llm_in_progress also closes the pause segment', async () => {+ let clock = Date.now()+ vi.spyOn(Date, 'now').mockImplementation(() => clock)+ tracker.setCallbacks({ onTerminal: vi.fn(), onSuspended: vi.fn(), onResumed: vi.fn() })+ tracker.start(KEY, 'task-1', 'um-1')+ await rpc.emit({+ type: 'suspended',+ data: { taskId: 'task-1', requestId: 'req-1', displayName: 'Shell', reason: 'approval' },+ })+ clock += 420_000+ await rpc.emit({+ type: 'llm_in_progress',+ data: { taskId: 'task-1', elapsedMs: 1_200, iteration: 3 },+ })++ const state = tracker.get(KEY)!+ expect(state.status).toBe('streaming')+ expect(state.pausedMs).toBe(420_000)+ expect(state.pausedAt).toBeUndefined()+ expect(state.pendingApproval).toBeUndefined()+ })++ it('a terminal reached with the pause segment still OPEN reports active_ms (deny path)', async () => {+ // A denied approval can end the run straight from `suspended` — no resume+ // event ever closes the segment, so `fireTerminal` has to.+ let clock = Date.now()+ vi.spyOn(Date, 'now').mockImplementation(() => clock)+ const logs: unknown[][] = []+ vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {+ logs.push(args)+ })+ tracker.setCallbacks({ onTerminal: vi.fn(), onSuspended: vi.fn() })+ tracker.start(KEY, 'task-1', 'um-1')+ clock += 20_000+ await rpc.emit({+ type: 'suspended',+ data: { taskId: 'task-1', requestId: 'req-1', displayName: 'Shell', reason: 'approval' },+ })+ clock += 900_000 // 15min at the gate, then the user denies+ await rpc.emit({+ type: 'terminal',+ data: { taskId: 'task-1', status: 'cancelled', reason: 'denied' },+ })++ const telemetry = logs.find(([label]) => label === '[telemetry] task_duration_seconds')+ expect(telemetry?.[1]).toMatchObject({+ duration_ms: 920_000, // wall-clock, unchanged+ paused_ms: 900_000,+ active_ms: 20_000,+ status: 'cancelled',+ tier_at_terminal: 'T1', // classified off active_ms, not the 15min wait+ })})it('subscribe returns an unsubscribe that stops further notifications', async () => {diff --git a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.ts b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.tsindex e31c9614e..466c69cb2 100644--- a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.ts+++ b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.ts@@ -34,6 +34,24 @@ function errMessage(err: unknown): string {return err instanceof Error ? err.message : String(err)}+/**+ * Folds the OPEN pause segment (if any) into the `pausedMs` accumulator and+ * re-establishes the §AC3 invariant `pausedAt !== undefined` ⟺ segment OPEN.+ *+ * The D.5b tier is meant to measure how long the AGENT has been working, not+ * wall-clock: freezing the clock while suspended is only half of it, because on+ * resume the age would jump back to `now - startedAt` and swallow the whole+ * human wait (approve after 10min → instant T4 "your agent is still working").+ * Closed segments live here; the open one stays covered by the `pausedAt`+ * freeze in `useTaskTier`. Idempotent (no open segment → no-op), so callers can+ * invoke it defensively on any resume/terminal path.+ */+function closePauseSegment(s: TaskState): void {+ if (s.pausedAt === undefined) return+ s.pausedMs = (s.pausedMs ?? 0) + Math.max(0, Date.now() - s.pausedAt)+ s.pausedAt = undefined+}+/*** Lifecycle owner for in-flight agent tasks. Lives in a React context provider* (so it survives controller re-renders) but is a plain class — testable@@ -446,8 +464,12 @@ export class TaskTracker implements AgentTaskTracker {s.currentIteration = step.iteration || s.currentIteration// Execution moved past the approval (decided on ANY surface: in-chat,// notification, another device) — drop it so the suspended affordance- // can't linger on a running task.- if (wasSuspended) s.pendingApproval = undefined+ // can't linger on a running task, and CLOSE the pause segment: the wait+ // is over and must not count as agent work in the D.5b tier (§AC3).+ if (wasSuspended) {+ s.pendingApproval = undefined+ closePauseSegment(s)+ }})if (wasSuspended) this.fireResumed(key)return@@ -531,7 +553,12 @@ export class TaskTracker implements AgentTaskTracker {s.status = 'streaming's.llmElapsedMs = elapsedMss.currentIteration = iteration ?? s.currentIteration- if (wasSuspended) s.pendingApproval = undefined+ // Same resume bookkeeping as `tool_start` — the approval was decided and+ // the pause segment closes here too (§AC3, tier = active time).+ if (wasSuspended) {+ s.pendingApproval = undefined+ closePauseSegment(s)+ }})if (wasSuspended) this.fireResumed(key)return@@ -539,9 +566,11 @@ export class TaskTracker implements AgentTaskTracker {case 'suspended': {const sd = event.data- // Stamp `pausedAt` ONLY on the TRANSITION into suspended (§AC3 freezes the- // D.5b tier timer at `pausedAt` so an approval wait can't escalate the- // nudges). This event is NOT once-per-suspension: mcp-host keeps the last+ // OPEN a pause segment: stamp `pausedAt` ONLY on the TRANSITION into+ // suspended (§AC3 freezes the D.5b tier timer at `pausedAt` so an approval+ // wait can't escalate the nudges; the segment is closed into `pausedMs` on+ // resume/terminal, which is what keeps the tier measuring ACTIVE time once+ // the task runs again). This event is NOT once-per-suspension: mcp-host keeps the last// `suspended` as a sticky event and replays it to every new subscriber, and// the main-process bridge (`appService.startTaskProgressStream`) reconnects// the SSE transparently whenever the 300s RPC token lapses mid-stream@@ -717,16 +746,30 @@ export class TaskTracker implements AgentTaskTracker {if (this.terminalFired.has(key)) returnthis.terminalFired.add(key)this.clearTimers(key)+ // A task can reach terminal with its pause segment still OPEN — a denied+ // approval that ends the run goes suspended → `terminal: cancelled` with no+ // resume event in between, and a gate can also fail/time out. Close it here so+ // the §AC3 invariant holds at terminal and the totals below are complete.+ // Guarded: `mutate` always emits, and the common case (no open segment) must+ // not fire an extra notification to every subscriber on each terminal.+ if (this.states.get(key)?.pausedAt !== undefined) this.mutate(key, s => closePauseSegment(s))const state = this.states.get(key)if (!state) return// Telemetry (§4.8): the coordinator owns the task lifecycle, so it emits the// duration + elapsed-time tier on the terminal (moved off the hook, which- // previously logged it in `onTrackerTerminal`).+ // previously logged it in `onTrackerTerminal`). `duration_ms` stays wall-clock+ // (that's what the user waited), but the tier is classified off `active_ms`:+ // the tier exists to describe how long the AGENT worked, and a long approval+ // wait would otherwise report a T4/T5 that no nudge ever showed.const durationMs = Date.now() - state.startedAt+ const pausedMs = state.pausedMs ?? 0+ const activeMs = Math.max(0, durationMs - pausedMs)console.log('[telemetry] task_duration_seconds', {duration_ms: durationMs,+ paused_ms: pausedMs,+ active_ms: activeMs,status: state.status,- tier_at_terminal: classifyTier(durationMs),+ tier_at_terminal: classifyTier(activeMs),})// B8 — a throwing consumer callback must never wedge the coordinator: the// timers are already cleared above (before the await), and the error is caughtdiff --git a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.ts b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.tsindex 38e1eeaa2..e8415b96f 100644--- a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.ts+++ b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.ts@@ -67,8 +67,22 @@ export interface TaskState {startedAt: number/** epoch ms, updated on every SSE event; feeds the idle watchdog. */lastEventAt: number- /** epoch ms when the task suspended on an approval (D.5b nudge freeze). */+ /**+ * epoch ms when the task suspended on an approval (D.5b nudge freeze, §AC3).+ * INVARIANT: `pausedAt !== undefined` ⟺ there is an OPEN pause segment — the+ * task is parked on a gate and that wait has NOT been folded into `pausedMs`+ * yet. The tracker opens the segment on the transition into `suspended` and+ * closes it on resume/terminal; nothing else may write this field.+ */pausedAt?: number+ /**+ * Total ms spent in already-CLOSED pause segments (approval waits that ended).+ * `useTaskTier` subtracts it from the age so the D.5b tier measures the+ * agent's ACTIVE time, not wall-clock: without it, approving after a 10min+ * wait resumed the task straight into T4 ("still working… safe to close"),+ * because the human's thinking time counted as agent work (§AC3).+ */+ pausedMs?: numbersteps: ProgressStep[]currentIteration: numberllmElapsedMs?: numberdiff --git a/desktop-app/ui/src/hooks/__tests__/useTaskTier.test.ts b/desktop-app/ui/src/hooks/__tests__/useTaskTier.test.tsindex c7220d32c..57e7a4ba1 100644--- a/desktop-app/ui/src/hooks/__tests__/useTaskTier.test.ts+++ b/desktop-app/ui/src/hooks/__tests__/useTaskTier.test.ts@@ -78,12 +78,41 @@ describe('useTaskTier', () => {it('unfreezes once no longer suspended (stale pausedAt is ignored)', () => {const now = Date.now()// Ran 150s ago, suspended at the 50s mark, but has since resumed (streaming).+ // (A streaming state with `pausedAt` still set violates the §AC3 invariant —+ // the tracker closes the segment on resume — so this is a defensive case.)const tier = renderHook(() =>useTaskTier(task({ status: 'streaming', startedAt: now - 150_000, pausedAt: now - 100_000 }))).result.currentexpect(tier).toBe('T3') // age = 150s from startedAt, NOT frozen at pausedAt's 50s})+ it('subtracts pausedMs so a resumed task is tiered on ACTIVE time (§AC3)', () => {+ const now = Date.now()+ // The reported bug: 10min parked on an approval + ~20s of real work. Without+ // the accumulator the resume lands on T4 ("still working, safe to close").+ const tier = renderHook(() =>+ useTaskTier(task({ status: 'streaming', startedAt: now - 620_000, pausedMs: 600_000 }))+ ).result.current+ expect(tier).toBe('T1') // active age = 20s+ })++ it('combines the closed accumulator with the open-segment freeze', () => {+ const now = Date.now()+ // 10min of earlier waits already closed, 20s of work, now parked again for+ // another 10min: both waits must stay out of the age.+ const tier = renderHook(() =>+ useTaskTier(+ task({+ status: 'suspended',+ startedAt: now - 1_220_000,+ pausedMs: 600_000,+ pausedAt: now - 600_000,+ })+ )+ ).result.current+ expect(tier).toBe('T1') // active age = 1_220_000 - 600_000 (open) - 600_000 = 20s+ })+it('recomputes every 5s without a manual rerender', () => {vi.useFakeTimers()const base = Date.now()diff --git a/desktop-app/ui/src/hooks/useTaskTier.ts b/desktop-app/ui/src/hooks/useTaskTier.tsindex f31c9b0b4..98054d8d6 100644--- a/desktop-app/ui/src/hooks/useTaskTier.ts+++ b/desktop-app/ui/src/hooks/useTaskTier.ts@@ -35,10 +35,17 @@ export function classifyTier(}/**- * Tier of a task based on observed wall-clock age since `startedAt`. Recomputes- * every 5s (the user can't perceive sub-5s tier boundaries — §6.2). A suspended- * task freezes its timer at `pausedAt` so an approval wait doesn't escalate the- * nudges (§AC3).+ * Tier of a task based on its ACTIVE age — how long the agent has been working,+ * not how long the user has been waiting. Recomputes every 5s (the user can't+ * perceive sub-5s tier boundaries — §6.2).+ *+ * Approval waits are excluded from the age in two complementary ways (§AC3),+ * because every T3+ nudge asserts the agent is busy:+ * - the OPEN pause segment: while `status === 'suspended'` the clock freezes at+ * `pausedAt`, so sitting at the gate never escalates the tier;+ * - CLOSED segments: `pausedMs` (accumulated by the tracker on resume) is+ * subtracted, so approving after a 10min wait resumes at the tier the work+ * actually earned instead of jumping straight to T4/T5.*/export function useTaskTier(taskState: TaskState | undefined,@@ -65,6 +72,6 @@ export function useTaskTier(const effectiveNow =taskState.status === 'suspended' && taskState.pausedAt ? taskState.pausedAt : now- const age = Math.max(0, effectiveNow - taskState.startedAt)+ const age = Math.max(0, effectiveNow - taskState.startedAt - (taskState.pausedMs ?? 0))return classifyTier(age, thresholds)}