The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): open never-closed cron runs view-only, not as a writable chat
Austin Pickett7f90f079444b
diff --git a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.test.tsx b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.test.tsxindex 5afa63b248a..5c35991139e 100644--- a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.test.tsx@@ -1,61 +1,72 @@-import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { cleanup, render, screen, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { I18nProvider, TRANSLATIONS } from '@/i18n'import { fmtDayTime } from '@/lib/time'+import { $readOnlyCronRuns, isStoredTranscriptReadOnly } from '@/store/read-only-transcript'import type { CronJob, SessionInfo } from '@/types/hermes'import { SidebarCronJobsSection } from './cron-jobs-section'-// Hoisted so the vi.mock factory (also hoisted) can close over it.-const { getCronJobRuns } = vi.hoisted(() => ({ getCronJobRuns: vi.fn() }))--vi.mock('@/hermes', async importOriginal => ({- ...(await importOriginal<object>()),- getCronJobRuns-}))--// A cron run row as the backend serves it: the job's owning profile plus the-// connection tag the desktop stamps on backend-returned session pages.-const RUN = {- connection_id: 'gw-tailscale',- ended_at: null,- id: 'cron-nightly-1',- input_tokens: 0,- is_active: false,- last_active: 1_700_000_000,- message_count: 2,- model: null,- output_tokens: 0,- profile: 'research',- source: 'cron'-} as SessionInfo--const JOB = { enabled: true, id: 'job-1', name: 'nightly', schedule: '* * * * *', state: 'scheduled' } as CronJob+// The peek's run list comes off the backend; the liveness flags below are the+// endpoint's own (`hermes_cli/web_routers/cron.py` computes `is_active` as+// `ended_at IS NULL` + a recent-activity window).+const getCronJobRuns = vi.fn<() => Promise<SessionInfo[]>>()-beforeEach(() => {- getCronJobRuns.mockResolvedValue([RUN])+vi.mock('@/hermes', async importOriginal => {+ const actual = (await importOriginal()) as Record<string, unknown>++ return {+ ...actual,+ deleteCronJob: vi.fn(),+ getCronJobRuns: (...args: unknown[]) => getCronJobRuns(...(args as [])),+ pauseCronJob: vi.fn(),+ resumeCronJob: vi.fn()+ }})-afterEach(() => {- cleanup()+const job: CronJob = { enabled: true, id: 'job-1', name: 'Daily digest', schedule_display: '30 8 * * *' }++const run = (over: Partial<SessionInfo>): SessionInfo =>+ ({+ ended_at: 1_700_000_600,+ id: 'cron_job-1_1700000000',+ is_active: false,+ last_active: 1_700_000_600,+ source: 'cron',+ started_at: 1_700_000_000,+ ...over+ }) as SessionInfo++const runLabel = (row: SessionInfo) => fmtDayTime.format(new Date((row.last_active || row.started_at) * 1000))++beforeEach(() => {+ $readOnlyCronRuns.set(new Set())getCronJobRuns.mockReset()})-function renderSection(onOpenRun: (sessionId: string, session?: SessionInfo) => void) {- return render(- <I18nProvider configClient={null} initialLocale="en">- <SidebarCronJobsSection- jobs={[JOB]}- label="Cron jobs"- onManageJob={() => {}}- onOpenRun={onOpenRun}- onToggle={() => {}}- onTriggerJob={async () => {}}- open- />- </I18nProvider>+afterEach(cleanup)++async function renderRunsPeek(rows: SessionInfo[]) {+ getCronJobRuns.mockResolvedValue(rows)++ const onOpenRun = vi.fn()++ render(+ <SidebarCronJobsSection+ jobs={[job]}+ label="Cron Jobs"+ onManageJob={vi.fn()}+ onOpenRun={onOpenRun}+ onToggle={vi.fn()}+ onTriggerJob={vi.fn()}+ open+ />)++ // Expand the job row's run peek.+ screen.getByRole('button', { name: 'Show runs' }).click()++ return { onOpenRun }}describe('SidebarCronJobsSection run rows', () => {@@ -64,17 +75,68 @@ describe('SidebarCronJobsSection run rows', () => {// the resume cannot name the backend that holds the run and falls to the// ambient one — so an SSH/remote run's transcript never loads.it('opens a run with the run ROW so the resume can pin its owning backend', async () => {- const onOpenRun = vi.fn()- renderSection(onOpenRun)+ const remote = run({ connection_id: 'gw-tailscale', id: 'cron_remote', profile: 'research' })+ const { onOpenRun } = await renderRunsPeek([remote])++ const row = await screen.findByRole('button', { name: runLabel(remote) })+ row.click()++ expect(onOpenRun).toHaveBeenCalledWith('cron_remote', remote)+ })+})- fireEvent.click(screen.getByRole('button', { name: TRANSLATIONS.en.cron.showRuns }))+describe('SidebarCronJobsSection run peek — zombie cron runs (#88443)', () => {+ it('opens a never-closed run (ended_at NULL, not live) READ-ONLY', async () => {+ const zombie = run({ ended_at: null, id: 'cron_zombie', is_active: false })+ const { onOpenRun } = await renderRunsPeek([zombie])++ const closeable = await screen.findByRole('button', { name: runLabel(zombie) })+ closeable.click()++ // The click still opens the run — its output stays one click away …+ expect(onOpenRun).toHaveBeenCalledWith('cron_zombie', zombie)+ // … but the composer can no longer route a send into the dead session.+ expect(isStoredTranscriptReadOnly('cron_zombie')).toBe(true)+ })++ it('leaves a properly closed run writable', async () => {+ const closed = run({ ended_at: 1_700_000_600, id: 'cron_closed', is_active: false })+ const { onOpenRun } = await renderRunsPeek([closed])++ const row = await screen.findByRole('button', { name: runLabel(closed) })+ row.click()++ expect(onOpenRun).toHaveBeenCalledWith('cron_closed', closed)+ expect(isStoredTranscriptReadOnly('cron_closed')).toBe(false)+ })++ it('leaves a live run writable', async () => {+ const live = run({ ended_at: null, id: 'cron_live', is_active: true })+ const { onOpenRun } = await renderRunsPeek([live])++ const row = await screen.findByRole('button', { name: runLabel(live) })+ row.click()++ expect(onOpenRun).toHaveBeenCalledWith('cron_live', live)+ expect(isStoredTranscriptReadOnly('cron_live')).toBe(false)+ })++ it('does not latch anything merely by rendering the peek', async () => {+ await renderRunsPeek([run({ ended_at: null, id: 'cron_zombie', is_active: false })])++ await screen.findByRole('button', { name: runLabel(run({ ended_at: null, id: 'cron_zombie' })) })++ expect(isStoredTranscriptReadOnly('cron_zombie')).toBe(false)+ })- const runButton = await screen.findByRole('button', {- name: fmtDayTime.format(new Date(RUN.last_active * 1000))- })+ it('still shows the run time for script-only output rows', async () => {+ const output = run({ ended_at: null, id: 'cron_output:job-1:latest', is_active: false, source: 'cron_output' })- fireEvent.click(runButton)+ await renderRunsPeek([output])- expect(onOpenRun).toHaveBeenCalledWith(RUN.id, RUN)+ await waitFor(() => expect(screen.getByText(runLabel(output))).toBeTruthy())+ // No chat affordance to click, and nothing latched.+ expect(screen.queryByRole('button', { name: runLabel(output) })).toBeNull()+ expect(isStoredTranscriptReadOnly(output.id)).toBe(false)})})diff --git a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsxindex a940ea9fee7..c90ac1f0dee 100644--- a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx+++ b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx@@ -21,6 +21,7 @@ import { $selectedStoredSessionId } from '@/store/session'import type { CronJob } from '@/types/hermes'import { jobState, jobTitle, nextRunOverdueMs, STATE_DOT } from '../../cron/job-state'+import { openCronRun } from '../../cron/open-cron-run'import { SidebarPanelLabel } from '../../shell/sidebar-label'import { SidebarRowBody, SidebarRowLabel, SidebarRowLead, SidebarRowShell } from './chrome'@@ -79,7 +80,8 @@ interface SidebarCronJobsSectionProps {max?: number// Open a run session's chat (1 click to output). The run ROW rides along so// the open can pin its owning (connection, profile) — the same owner-aware- // door every other session-list row uses.+ // door every other session-list row uses. A run the scheduler never closed+ // opens view-only — see `openCronRun` (#88443).onOpenRun: (sessionId: string, session?: SessionInfo) => void// Open the full Cron page focused on this job (manage / full history).onManageJob: (jobId: string) => void@@ -475,6 +477,8 @@ function CronJobSidebarRuns({{formatRunTime(run.last_active || run.started_at)}</div>) : (+ // One click to the run's transcript; a run the scheduler never+ // closed (watchdog kill / crash) opens view-only (#88443).<buttonclassName={cn('truncate rounded-md px-1.5 py-0.5 text-left text-[0.6875rem] tabular-nums focus-visible:bg-(--chrome-action-hover) focus-visible:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40',@@ -483,7 +487,7 @@ function CronJobSidebarRuns({: 'text-(--ui-text-secondary) hover:bg-(--chrome-action-hover) hover:text-foreground')}key={run.id}- onClick={() => onOpenRun(run.id, run)}+ onClick={() => openCronRun(run, onOpenRun)}type="button">{formatRunTime(run.last_active || run.started_at)}diff --git a/apps/desktop/src/app/cron/index.tsx b/apps/desktop/src/app/cron/index.tsxindex a8634d9836c..929a247ddfc 100644--- a/apps/desktop/src/app/cron/index.tsx+++ b/apps/desktop/src/app/cron/index.tsx@@ -87,6 +87,7 @@ import {validateCronEditor} from './cron-job-model'import { jobState, jobTitle, nextRunOverdueMs, STATE_DOT } from './job-state'+import { openCronRun } from './open-cron-run'const DEFAULT_DELIVER = 'local'@@ -979,10 +980,12 @@ function CronJobRuns({</span></div>) : (+ // One click to the run's transcript; a run the scheduler never+ // closed opens view-only (see `openCronRun`, #88443).<buttonclassName="row-hover flex items-center justify-between gap-3 rounded-md px-2 py-1 text-left text-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"key={run.id}- onClick={() => onOpenSession?.(run.id, run)}+ onClick={onOpenSession ? () => openCronRun(run, onOpenSession) : undefined}type="button"><span className="truncate text-foreground/85">diff --git a/apps/desktop/src/app/cron/open-cron-run.test.ts b/apps/desktop/src/app/cron/open-cron-run.test.tsnew file mode 100644index 00000000000..d7743a7894e--- /dev/null+++ b/apps/desktop/src/app/cron/open-cron-run.test.ts@@ -0,0 +1,71 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { $readOnlyCronRuns, isCronRunReadOnly, isStoredTranscriptReadOnly } from '@/store/read-only-transcript'++import { isResumableCronRun, openCronRun } from './open-cron-run'++const run = (over: Partial<{ ended_at: null | number; id: string; is_active: boolean }> = {}) => ({+ ended_at: 1_700_000_600 as null | number,+ id: 'cron_job-1_1700000000',+ is_active: false,+ ...over+})++beforeEach(() => {+ $readOnlyCronRuns.set(new Set())+})++describe('isResumableCronRun', () => {+ it('treats a live run as resumable (the scheduler agent still owns it)', () => {+ expect(isResumableCronRun(run({ ended_at: null, is_active: true }))).toBe(true)+ })++ it('treats a properly closed run as resumable', () => {+ expect(isResumableCronRun(run({ ended_at: 1_700_000_600, is_active: false }))).toBe(true)+ })++ it('treats a never-closed, not-live run as a zombie (NOT resumable)', () => {+ // The incident shape: end_session never ran (watchdog kill / crash), so+ // ended_at is NULL while no agent owns the session any more.+ expect(isResumableCronRun(run({ ended_at: null, is_active: false }))).toBe(false)+ })++ it('fails SAFE when an older backend omits is_active', () => {+ expect(isResumableCronRun({ ended_at: null, is_active: undefined as never })).toBe(false)+ expect(isResumableCronRun({ ended_at: 1_700_000_600, is_active: undefined as never })).toBe(true)+ })+})++describe('openCronRun', () => {+ it('opens a live / completed run without latching it read-only', () => {+ const open = vi.fn()++ const live = run({ ended_at: null, is_active: true, id: 'live-run' })+ const closed = run({ ended_at: 1_700_000_600, id: 'closed-run' })++ openCronRun(live, open)+ openCronRun(closed, open)++ expect(open.mock.calls).toEqual([+ ['live-run', live],+ ['closed-run', closed]+ ])+ expect(isStoredTranscriptReadOnly('live-run')).toBe(false)+ expect(isStoredTranscriptReadOnly('closed-run')).toBe(false)+ })++ it('opens a zombie run but latches it read-only before the route flips', () => {+ const open = vi.fn(() => {+ // The route has flipped by the time the open runs: the latch must already+ // be in place, or the first send lands inside the cron session.+ expect(isStoredTranscriptReadOnly('zombie-run')).toBe(true)+ })++ const zombie = run({ ended_at: null, is_active: false, id: 'zombie-run' })++ openCronRun(zombie, open)++ expect(open).toHaveBeenCalledWith('zombie-run', zombie)+ expect(isCronRunReadOnly('zombie-run')).toBe(true)+ })+})diff --git a/apps/desktop/src/app/cron/open-cron-run.ts b/apps/desktop/src/app/cron/open-cron-run.tsnew file mode 100644index 00000000000..c2ea8aceefa--- /dev/null+++ b/apps/desktop/src/app/cron/open-cron-run.ts@@ -0,0 +1,47 @@+import { markCronRunReadOnly } from '@/store/read-only-transcript'+import type { SessionInfo } from '@/types/hermes'++/**+ * Cron run sessions are autonomous scheduled executions, never interactive+ * chat targets (#88443). Two states may be opened as a normal, WRITABLE+ * desktop chat: the run is still LIVE (`is_active`, the scheduler's agent is+ * executing it), or the run was properly CLOSED (`ended_at` stamped by+ * `_finalize_cron_session`).+ *+ * A run with `ended_at` NULL that is not live never got its `end_session` —+ * the watchdog killed the process, the run crashed, or the connection+ * dropped. It is a ZOMBIE: the row still looks open while nothing owns it, and+ * resuming it as a desktop chat routes the user's messages into a dead+ * `source='cron'` session, where the cron agent executes unrelated desktop+ * work. Such a run opens READ-ONLY instead.+ *+ * `is_active` is computed by the runs endpoint (`hermes_cli/web_routers/+ * cron.py`) as `ended_at IS NULL` plus a recent-activity window, so an older+ * backend that omits the flag fails SAFE here: the run reads as a zombie and+ * opens read-only rather than writable.+ */+export function isResumableCronRun(run: Pick<SessionInfo, 'ended_at' | 'is_active'>): boolean {+ return run.is_active === true || run.ended_at != null+}++/**+ * The single door every Cron surface (the sidebar run peek and the Cron page+ * history) uses to open a run's session, so the policy above is applied in one+ * place and cannot drift between callers.+ *+ * A never-closed run is latched read-only before the route flips: the+ * transcript still paints, but `submit` refuses to route a send into the dead+ * session (see `store/read-only-transcript`).+ */+export function openCronRun<Run extends Pick<SessionInfo, 'ended_at' | 'id' | 'is_active'>>(+ run: Run,+ open: (sessionId: string, session: Run) => void+): void {+ if (!isResumableCronRun(run)) {+ markCronRunReadOnly(run.id)+ }++ // The ROW rides along so the open can pin its owning (connection, profile)+ // (#82527).+ open(run.id, run)+}diff --git a/apps/desktop/src/store/read-only-transcript.test.ts b/apps/desktop/src/store/read-only-transcript.test.tsindex 11acfd0f2e9..ee0fc053237 100644--- a/apps/desktop/src/store/read-only-transcript.test.ts+++ b/apps/desktop/src/store/read-only-transcript.test.ts@@ -3,10 +3,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { $connectionsRegistry } from './connections'import { $profiles } from './profile'import {+ $readOnlyCronRuns,$readOnlyStoredTranscripts,clearStoredTranscriptReadOnly,+ isCronRunReadOnly,isReadOnlyRuntimeId,isStoredTranscriptReadOnly,+ markCronRunReadOnly,markStoredTranscriptReadOnly,readOnlyRuntimeIdFor,resumeWithStoredTranscriptFallback@@ -25,6 +28,7 @@ beforeEach(() => {$connectionsRegistry.set(null)$profiles.set([])$readOnlyStoredTranscripts.set(new Set())+ $readOnlyCronRuns.set(new Set())})afterEach(() => {@@ -139,3 +143,38 @@ describe('read-only stored-transcript resume (#94724 no-owner recovery)', () =>expect(isStoredTranscriptReadOnly('stored-9')).toBe(false)})})++describe('read-only cron runs (#88443 zombie cron session)', () => {+ it('blocks writes on a cron run latched read-only', () => {+ markCronRunReadOnly('cron_job-1_1700000000')++ expect(isCronRunReadOnly('cron_job-1_1700000000')).toBe(true)+ // The submit path's gate: one answer for every write surface.+ expect(isStoredTranscriptReadOnly('cron_job-1_1700000000')).toBe(true)+ // Unrelated ids stay writable.+ expect(isStoredTranscriptReadOnly('cron_job-1_1800000000')).toBe(false)+ expect(isStoredTranscriptReadOnly(null)).toBe(false)+ })++ it('survives a live resume clearing the owner-recovery latch', () => {+ markCronRunReadOnly('cron-keep')+ markStoredTranscriptReadOnly('cron-keep')++ // Exactly what a successful resume does to the #94724 latch — the cron+ // latch must NOT be collateral damage, or the guard evaporates the moment+ // the transcript paints.+ clearStoredTranscriptReadOnly('cron-keep')++ expect(isStoredTranscriptReadOnly('cron-keep')).toBe(true)+ expect(isStoredTranscriptReadOnly('legacy-owner-recovery')).toBe(false)+ })++ it('ignores blank ids and is idempotent', () => {+ markCronRunReadOnly(' ')+ expect(isCronRunReadOnly('')).toBe(false)++ markCronRunReadOnly('cron-twice')+ markCronRunReadOnly('cron-twice')+ expect([...$readOnlyCronRuns.get()]).toEqual(['cron-twice'])+ })+})diff --git a/apps/desktop/src/store/read-only-transcript.ts b/apps/desktop/src/store/read-only-transcript.tsindex 8cf3ca9bd64..4bde30b5faa 100644--- a/apps/desktop/src/store/read-only-transcript.ts+++ b/apps/desktop/src/store/read-only-transcript.ts@@ -14,6 +14,12 @@* Every other failure keeps its existing semantics. Rows whose owner IS* resolvable never take this path, and a later successful live resume (e.g.* after the single-match owner backfill stamps the row) clears the flag.+ *+ * A second, unrelated reason a stored transcript is read-only lives here too:+ * a cron run the scheduler never closed (#88443). It uses its own latch so a+ * live resume cannot clear it — see `markCronRunReadOnly` below, which+ * `isStoredTranscriptReadOnly` also reports, so every write path gets one+ * answer.*/import { atom } from 'nanostores'@@ -49,7 +55,47 @@ export function clearStoredTranscriptReadOnly(storedSessionId: string): void {}export function isStoredTranscriptReadOnly(storedSessionId: null | string | undefined): boolean {- return Boolean(storedSessionId && $readOnlyStoredTranscripts.get().has(storedSessionId.trim()))+ if (!storedSessionId) {+ return false+ }++ const id = storedSessionId.trim()++ return $readOnlyStoredTranscripts.get().has(id) || $readOnlyCronRuns.get().has(id)+}++/**+ * Cron runs opened from the desktop's Cron surfaces (#88443).+ *+ * A cron run is an autonomous scheduled execution, never an interactive chat+ * target. A run whose `ended_at` is NULL while no agent owns it is a ZOMBIE:+ * the scheduler's `end_session` never ran (watchdog kill, crash, connection+ * drop), so the row still looks open. Resuming it as a normal desktop chat+ * routes the user's messages into a dead `source='cron'` session, and the+ * run's own agent then executes unrelated desktop work under the cron+ * identity.+ *+ * This latch is deliberately SEPARATE from the owner-recovery set above: a+ * successful live resume clears that one (the owner proved routable again),+ * but a never-closed cron run must stay non-writable for as long as this app+ * session remembers it. The transcript still opens — `submit` refuses the+ * send with the read-only explanation, and starting a fresh chat is the way+ * forward.+ */+export const $readOnlyCronRuns = atom<ReadonlySet<string>>(new Set())++export function markCronRunReadOnly(storedSessionId: string): void {+ const id = storedSessionId.trim()++ if (!id || $readOnlyCronRuns.get().has(id)) {+ return+ }++ $readOnlyCronRuns.set(new Set([...$readOnlyCronRuns.get(), id]))+}++export function isCronRunReadOnly(storedSessionId: null | string | undefined): boolean {+ return Boolean(storedSessionId && $readOnlyCronRuns.get().has(storedSessionId.trim()))}/** Synthetic runtime-id namespace for read-only tiles: a stored transcript