diff --git a/src/main/build-initial-state.ts b/src/main/build-initial-state.ts index 98a67e4a..254e37f4 100644 --- a/src/main/build-initial-state.ts +++ b/src/main/build-initial-state.ts @@ -27,6 +27,7 @@ import { initialPermissions } from '../shared/state/permissions' import { initialSubscriptions, type WorktreeSubscription } from '../shared/state/subscriptions' import { initialOrigins, type WorktreeOrigin } from '../shared/state/origins' import { initialNotifications } from '../shared/state/notifications' +import { initialInbox } from '../shared/state/inbox' import { initialReviews, type ReviewAuthor, @@ -272,6 +273,13 @@ export function buildInitialAppState( ? { byPath: sanitizeOrigins(config.worktreeOrigins) } : initialOrigins, notifications: initialNotifications, + inbox: config.inbox + ? { + turns: { ...config.inbox.turns }, + seenAt: { ...config.inbox.seenAt }, + prSeen: { ...config.inbox.prSeen } + } + : initialInbox, settings: { ...initialSettings, themeMode: diff --git a/src/main/hooks.ts b/src/main/hooks.ts index 32f383e4..6e27d41b 100644 --- a/src/main/hooks.ts +++ b/src/main/hooks.ts @@ -267,7 +267,8 @@ export function tailLog(terminalId: string, store: Store): void { payload: { id: terminalId, status: update.status, - pendingTool: update.pendingTool + pendingTool: update.pendingTool, + at: Date.now() } }) } diff --git a/src/main/inbox-deriver.test.ts b/src/main/inbox-deriver.test.ts new file mode 100644 index 00000000..cfddd025 --- /dev/null +++ b/src/main/inbox-deriver.test.ts @@ -0,0 +1,255 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { mkdtempSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' + +vi.mock('./debug', () => ({ log: () => {} })) + +type StopListener = (ev: { terminalId: string; sessionId: string; transcriptPath: string; ts: number }) => void +const stopListeners: StopListener[] = [] +vi.mock('./hooks', () => ({ + onStopEvent: (l: StopListener) => { + stopListeners.push(l) + return () => {} + } +})) + +import { Store } from './store' +import { InboxDeriver, lastAssistantTextFromJsonl } from './inbox-deriver' +import { initialState } from '../shared/state' +import type { PaneNode, TerminalTab } from '../shared/state/terminals' +import type { JsonClaudeSession } from '../shared/state/json-claude' + +const WT = '/wt/a' + +function paneWith(tabs: TerminalTab[]): PaneNode { + return { type: 'leaf', id: 'p1', tabs, activeTabId: tabs[0].id } +} + +function chatSession(id: string, text: string): JsonClaudeSession { + return { + sessionId: id, + worktreePath: WT, + state: 'running', + exitCode: null, + exitReason: null, + entries: [ + { entryId: '1', kind: 'user', text: 'go', timestamp: 1 }, + { entryId: '2', kind: 'assistant', blocks: [{ type: 'text', text }], timestamp: 2 }, + { + entryId: '3', + kind: 'assistant', + parentToolUseId: 'task1', + blocks: [{ type: 'text', text: 'sub-agent chatter?' }], + timestamp: 3 + } + ], + entriesHydrated: true, + busy: false, + permissionMode: 'default', + slashCommands: [], + autoApprovedDecisions: {}, + sessionToolApprovals: [], + sessionAllowedDecisions: {}, + backgroundAgents: {} + } +} + +function status(store: Store, id: string, s: 'processing' | 'waiting'): void { + store.dispatch({ type: 'terminals/statusChanged', payload: { id, status: s, pendingTool: null } }) +} + +beforeEach(() => { + stopListeners.length = 0 +}) + +describe('InboxDeriver', () => { + it('records a chat turn from its last top-level assistant message', () => { + const store = new Store({ + ...initialState, + terminals: { + ...initialState.terminals, + panes: { [WT]: paneWith([{ id: 'c1', type: 'json-claude', label: 'Chat' }]) } + }, + jsonClaude: { ...initialState.jsonClaude, sessions: { c1: chatSession('c1', 'Shall I push it?') } } + }) + new InboxDeriver(store).start() + status(store, 'c1', 'processing') + status(store, 'c1', 'waiting') + const turn = store.getSnapshot().state.inbox.turns.c1 + expect(turn).toMatchObject({ worktreePath: WT, kind: 'question', text: 'Shall I push it?' }) + }) + + it('does not treat a replayed boot status as a finished turn', () => { + const store = new Store({ + ...initialState, + terminals: { + ...initialState.terminals, + panes: { [WT]: paneWith([{ id: 'c1', type: 'json-claude', label: 'Chat' }]) } + }, + jsonClaude: { ...initialState.jsonClaude, sessions: { c1: chatSession('c1', 'Done.') } } + }) + new InboxDeriver(store).start() + status(store, 'c1', 'waiting') + expect(store.getSnapshot().state.inbox.turns.c1).toBeUndefined() + expect(store.getSnapshot().state.terminals.statuses.c1).toBe('waiting') + }) + + it('fills a terminal Claude turn in from the Stop hook transcript', async () => { + const dir = mkdtempSync(join(tmpdir(), 'inbox-deriver-')) + const transcript = join(dir, 's.jsonl') + writeFileSync( + transcript, + [ + JSON.stringify({ type: 'user', message: { content: 'hi' } }), + JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text: 'All tests pass.' }] } }), + '' + ].join('\n') + ) + const store = new Store({ + ...initialState, + terminals: { + ...initialState.terminals, + panes: { [WT]: paneWith([{ id: 'a1', type: 'agent', label: 'Claude' }]) } + } + }) + new InboxDeriver(store).start() + status(store, 'a1', 'processing') + for (const l of stopListeners) l({ terminalId: 'a1', sessionId: 's', transcriptPath: transcript, ts: 0 }) + status(store, 'a1', 'waiting') + expect(store.getSnapshot().state.inbox.turns.a1).toMatchObject({ kind: 'finished', text: '' }) + await vi.waitFor(() => { + expect(store.getSnapshot().state.inbox.turns.a1?.text).toBe('All tests pass.') + }) + }) + + it('records Codex terminal turns as finished with no text', () => { + const store = new Store({ + ...initialState, + terminals: { + ...initialState.terminals, + panes: { [WT]: paneWith([{ id: 'x1', type: 'agent', label: 'Codex', agentKind: 'codex' }]) } + } + }) + new InboxDeriver(store).start() + for (const l of stopListeners) l({ terminalId: 'x1', sessionId: 's', transcriptPath: '/nope', ts: 0 }) + status(store, 'x1', 'processing') + status(store, 'x1', 'waiting') + expect(store.getSnapshot().state.inbox.turns.x1).toMatchObject({ kind: 'finished', text: '' }) + }) + + it('forgets turns for tabs closed in a worktree', () => { + const store = new Store({ + ...initialState, + terminals: { + ...initialState.terminals, + panes: { [WT]: paneWith([{ id: 'c1', type: 'json-claude', label: 'Chat' }]) } + }, + jsonClaude: { ...initialState.jsonClaude, sessions: { c1: chatSession('c1', 'Done.') } } + }) + new InboxDeriver(store).start() + status(store, 'c1', 'processing') + status(store, 'c1', 'waiting') + store.dispatch({ + type: 'terminals/panesForWorktreeChanged', + payload: { worktreePath: WT, panes: paneWith([{ id: 's1', type: 'shell', label: 'Shell' }]) } + }) + expect(store.getSnapshot().state.inbox.turns.c1).toBeUndefined() + }) +}) + +describe('InboxDeriver edge cases', () => { + it('a slow transcript read never overwrites a newer turn', async () => { + const dir = mkdtempSync(join(tmpdir(), 'inbox-deriver-')) + const transcript = join(dir, 's.jsonl') + writeFileSync( + transcript, + JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text: 'Stale first turn' }] } }) + '\n' + ) + const store = new Store({ + ...initialState, + terminals: { + ...initialState.terminals, + panes: { [WT]: paneWith([{ id: 'a1', type: 'agent', label: 'Claude' }]) } + } + }) + new InboxDeriver(store).start() + vi.useFakeTimers({ toFake: ['Date'] }) + try { + vi.setSystemTime(1000) + status(store, 'a1', 'processing') + for (const l of stopListeners) l({ terminalId: 'a1', sessionId: 's', transcriptPath: transcript, ts: 0 }) + status(store, 'a1', 'waiting') // read #1 starts + vi.setSystemTime(2000) + status(store, 'a1', 'processing') + status(store, 'a1', 'waiting') // no Stop path this time → no read + } finally { + vi.useRealTimers() + } + await new Promise((r) => setTimeout(r, 50)) + const turn = store.getSnapshot().state.inbox.turns.a1 + expect(turn.endedAt).toBe(2000) + expect(turn.text).toBe('') + }) + + it('seeds a PR read mark on first sight, so existing events stay quiet', () => { + const store = new Store(initialState) + new InboxDeriver(store).start() + const pr = { + number: 3, state: 'open', headSha: 'a', checks: [], checksOverall: 'failure', + hasConflict: false, reviews: [], reviewDecision: 'none' + } as never + store.dispatch({ type: 'prs/statusChanged', payload: { path: WT, status: pr } }) + expect(store.getSnapshot().state.inbox.prSeen[WT]).toBe('ci:3:a') + // A later event on the same worktree is new, so it is NOT reseeded. + store.dispatch({ + type: 'prs/statusChanged', + payload: { path: WT, status: { ...(pr as object), headSha: 'b' } as never } + }) + expect(store.getSnapshot().state.inbox.prSeen[WT]).toBe('ci:3:a') + }) + + it('prunes records for worktrees gone from the list and from disk', () => { + const gonePath = '/definitely/not/here/wt' + const store = new Store({ + ...initialState, + inbox: { + turns: { t1: { worktreePath: gonePath, endedAt: 1, kind: 'finished', text: '' } }, + seenAt: { t1: 2 }, + prSeen: { [gonePath]: 'x', [tmpdir()]: 'y' } + } + }) + new InboxDeriver(store).start() + store.dispatch({ type: 'worktrees/listChanged', payload: [] }) + const inbox = store.getSnapshot().state.inbox + expect(inbox.turns).toEqual({}) + expect(inbox.seenAt).toEqual({}) + // Still on disk (e.g. a repo whose listing failed) — kept. + expect(inbox.prSeen).toEqual({ [tmpdir()]: 'y' }) + }) +}) + +describe('lastAssistantTextFromJsonl', () => { + it('skips sidechain lines and a truncated first line', () => { + const tail = [ + '{"type":"assistant","mess', + JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text: 'Main reply?' }] } }), + JSON.stringify({ + type: 'assistant', + isSidechain: true, + message: { content: [{ type: 'text', text: 'sub-agent' }] } + }), + JSON.stringify({ type: 'assistant', message: { content: [{ type: 'tool_use', name: 'Bash' }] } }) + ].join('\n') + expect(lastAssistantTextFromJsonl(tail)).toBe('Main reply?') + }) + + it('stops at the user prompt that started the turn', () => { + const tail = [ + JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text: 'Old turn' }] } }), + JSON.stringify({ type: 'user', message: { content: [{ type: 'text', text: 'next' }] } }), + JSON.stringify({ type: 'assistant', message: { content: [{ type: 'tool_use', name: 'Bash' }] } }) + ].join('\n') + expect(lastAssistantTextFromJsonl(tail)).toBe('') + }) +}) diff --git a/src/main/inbox-deriver.ts b/src/main/inbox-deriver.ts new file mode 100644 index 00000000..15c755ea --- /dev/null +++ b/src/main/inbox-deriver.ts @@ -0,0 +1,281 @@ +// Records how each agent tab's turn ended, for the sidebar inbox. +// +// A turn ends when a tab's status moves into 'waiting' from something +// that isn't already 'waiting'. That's the one signal every agent tab +// shares — Chat tabs get it from JsonClaudeStatusDeriver (busy → false), +// terminal tabs from the Stop hook. What we can say about the turn +// depends on the tab: +// +// - Chat tabs: main holds the full entries, so the last top-level +// assistant message is classified directly. +// - Terminal Claude tabs: the Stop hook payload carries +// `transcript_path`, and hooks.ts fires `onStopEvent` before it +// dispatches the 'waiting' status, so the path is known by the time +// the transition arrives. The jsonl tail is read off the hot path. +// - Terminal Codex / Cursor tabs: their transcripts are another format, +// so the turn is recorded as plain 'finished' with no text. +// +// Every dispatch is scoped to the one tab the event names, and status +// transitions are deduped against a per-tab cache, so a streaming chat +// costs nothing here (CLAUDE.md anti-patterns #1 and #2). + +import { existsSync } from 'fs' +import { open } from 'fs/promises' +import type { Store } from './store' +import type { AppState, StateEvent } from '../shared/state' +import { + findLeafByTabId, + getLeaves, + isClaudeBackedTab, + type PtyStatus, + type TerminalTab +} from '../shared/state/terminals' +import { classifyTurnText } from '../shared/inbox-turn' +import { prEventFor } from '../shared/inbox-pr' +import type { InboxTurn } from '../shared/state/inbox' +import { onStopEvent } from './hooks' +import { log } from './debug' + +/** Enough to hold the final assistant message of any realistic turn + * without reading a multi-megabyte transcript end to end. */ +const TRANSCRIPT_TAIL_BYTES = 256 * 1024 + +function isAgentTab(tab: TerminalTab): boolean { + return tab.type === 'agent' || tab.type === 'json-claude' +} + +/** Text of the last top-level assistant message in a Claude jsonl + * transcript tail. Sidechain (sub-agent) lines are skipped — their final + * words aren't addressed to the user. Exported for tests. */ +export function lastAssistantTextFromJsonl(tail: string): string { + const lines = tail.split('\n') + for (let i = lines.length - 1; i >= 0; i--) { + const line = lines[i].trim() + if (!line.startsWith('{')) continue + let rec: { + type?: string + isSidechain?: boolean + message?: { content?: unknown } + } + try { + rec = JSON.parse(line) + } catch { + continue // the first line of a tail is usually cut mid-record + } + if (rec.type === 'user' && !rec.isSidechain) { + // A real user prompt (not a tool result) bounds the turn: anything + // older belongs to an earlier one. + const content = rec.message?.content + if (typeof content === 'string') return '' + if (Array.isArray(content) && content.some((b) => b?.type === 'text')) return '' + continue + } + if (rec.type !== 'assistant' || rec.isSidechain) continue + const content = rec.message?.content + if (!Array.isArray(content)) continue + const text = content + .filter((b): b is { type: 'text'; text: string } => b?.type === 'text' && typeof b.text === 'string') + .map((b) => b.text) + .join('\n') + .trim() + if (text) return text + } + return '' +} + +async function readTail(path: string): Promise { + const fh = await open(path, 'r') + try { + const { size } = await fh.stat() + const len = Math.min(size, TRANSCRIPT_TAIL_BYTES) + const buf = Buffer.alloc(len) + await fh.read(buf, 0, len, size - len) + return buf.toString('utf-8') + } finally { + await fh.close() + } +} + +export class InboxDeriver { + private unsubscribe: (() => void) | null = null + private unsubscribeStop: (() => void) | null = null + private lastStatus = new Map() + private transcriptByTab = new Map() + + constructor(private store: Store) {} + + start(): void { + if (this.unsubscribe) return + this.unsubscribeStop = onStopEvent((ev) => { + this.transcriptByTab.set(ev.terminalId, ev.transcriptPath) + }) + this.unsubscribe = this.store.subscribe((event) => this.onEvent(event)) + } + + stop(): void { + this.unsubscribe?.() + this.unsubscribe = null + this.unsubscribeStop?.() + this.unsubscribeStop = null + } + + private onEvent(event: StateEvent): void { + switch (event.type) { + case 'terminals/statusChanged': + this.onStatus(event.payload.id, event.payload.status) + return + case 'terminals/removed': + this.lastStatus.delete(event.payload) + return + case 'terminals/panesForWorktreeChanged': + this.forgetClosedTabs(event.payload.worktreePath) + return + case 'terminals/panesForWorktreeCleared': + this.forgetClosedTabs(event.payload) + return + case 'worktrees/listChanged': + this.forgetRemovedWorktrees() + return + case 'prs/statusChanged': + this.seedPrSeen([event.payload.path]) + return + case 'prs/bulkStatusChanged': + case 'prs/mergedChanged': + this.seedPrSeen(Object.keys(event.payload)) + return + } + } + + private onStatus(tabId: string, status: PtyStatus): void { + const prev = this.lastStatus.get(tabId) + if (prev === status) return + this.lastStatus.set(tabId, status) + const now = Date.now() + // `prev === undefined` is a status replayed at boot or on respawn, not + // a turn that just ended — the persisted turn already covers it. + if (status !== 'waiting' || prev === undefined || prev === 'idle') return + const state = this.store.getSnapshot().state + const located = this.locate(state, tabId) + if (!located) return + const { worktreePath, tab } = located + if (!isAgentTab(tab)) return + + if (tab.type === 'json-claude') { + this.record(tabId, worktreePath, now, this.chatText(state, tabId)) + return + } + // Consumed once: a later Stop without a transcript path must not + // re-read this session's file for a different turn. + const transcript = this.transcriptByTab.get(tabId) + this.transcriptByTab.delete(tabId) + if (!transcript || !isClaudeBackedTab(tab)) { + this.record(tabId, worktreePath, now, '') + return + } + // Record right away so the row moves the instant the turn ends, then + // fill in the text once the transcript tail is read. + this.record(tabId, worktreePath, now, '') + readTail(transcript) + .then((tail) => { + const text = lastAssistantTextFromJsonl(tail) + if (!text) return + // A newer turn may have ended while we were reading. + if (this.store.getSnapshot().state.inbox.turns[tabId]?.endedAt !== now) return + this.record(tabId, worktreePath, now, text) + }) + .catch((err) => { + log('inbox', `transcript read failed for ${tabId}`, err instanceof Error ? err.message : err) + }) + } + + private chatText(state: AppState, tabId: string): string { + const entries = state.jsonClaude.sessions[tabId]?.entries ?? [] + for (let i = entries.length - 1; i >= 0; i--) { + const e = entries[i] + if (e.kind === 'user' && !e.isQueued) return '' + if (e.kind !== 'assistant' || e.parentToolUseId) continue + const text = (e.blocks ?? []) + .filter((b) => b.type === 'text' && b.text) + .map((b) => b.text) + .join('\n') + .trim() + if (text) return text + } + return '' + } + + private record(tabId: string, worktreePath: string, endedAt: number, rawText: string): void { + const { kind, text } = classifyTurnText(rawText) + const turn: InboxTurn = { worktreePath, endedAt, kind, text } + this.store.dispatch({ type: 'inbox/turnEnded', payload: { tabId, turn } }) + } + + private locate( + state: AppState, + tabId: string + ): { worktreePath: string; tab: TerminalTab } | null { + for (const [worktreePath, tree] of Object.entries(state.terminals.panes)) { + const leaf = findLeafByTabId(tree, tabId) + const tab = leaf?.tabs.find((t) => t.id === tabId) + if (tab) return { worktreePath, tab } + } + return null + } + + /** First sight of a worktree's PR state marks whatever it currently + * shows as already seen, so turning the inbox on (or adding a repo) + * doesn't light the bell for a backlog of old merges and red builds. + * Only events that arrive after this count. Scoped to the paths the + * event names; worktrees that already have a mark are left alone. */ + private seedPrSeen(paths: string[]): void { + const state = this.store.getSnapshot().state + for (const path of paths) { + if (path in state.inbox.prSeen) continue + const ev = prEventFor(state.prs.byPath[path], !!state.prs.mergedByPath[path]) + this.store.dispatch({ + type: 'inbox/prSeen', + payload: { worktreePath: path, fingerprint: ev?.fingerprint ?? '' } + }) + } + } + + /** Drop records for worktrees that are gone: missing from the list AND + * from disk. The disk check matters twice over — it catches worktrees + * removed while Ness wasn't running (no panes event ever fires for + * those), and it keeps a repo whose `git worktree list` failed + * transiently from losing its read marks. Runs on listChanged, which + * is deduped upstream and rare, so the pass over every record is fine. */ + private forgetRemovedWorktrees(): void { + const state = this.store.getSnapshot().state + const live = new Set(state.worktrees.list.map((w) => w.path)) + const gone = (path: string): boolean => !live.has(path) && !existsSync(path) + const tabIds = Object.entries(state.inbox.turns) + .filter(([, t]) => gone(t.worktreePath)) + .map(([id]) => id) + if (tabIds.length > 0) { + this.store.dispatch({ type: 'inbox/tabsForgotten', payload: { tabIds } }) + } + const paths = Object.keys(state.inbox.prSeen).filter(gone) + if (paths.length > 0) { + this.store.dispatch({ type: 'inbox/worktreesForgotten', payload: { paths } }) + } + } + + /** Drop inbox records for tabs closed in this one worktree. */ + private forgetClosedTabs(worktreePath: string): void { + const state = this.store.getSnapshot().state + const tree = state.terminals.panes[worktreePath] + const live = new Set() + if (tree) for (const leaf of getLeaves(tree)) for (const t of leaf.tabs) live.add(t.id) + const gone: string[] = [] + for (const [tabId, turn] of Object.entries(state.inbox.turns)) { + if (turn.worktreePath === worktreePath && !live.has(tabId)) gone.push(tabId) + } + if (gone.length === 0) return + for (const id of gone) { + this.lastStatus.delete(id) + this.transcriptByTab.delete(id) + } + this.store.dispatch({ type: 'inbox/tabsForgotten', payload: { tabIds: gone } }) + } +} diff --git a/src/main/index.ts b/src/main/index.ts index 67e45372..0aa7d1c8 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -103,6 +103,7 @@ import { WakeLockController } from './wake-lock-controller' import { WorktreeWatcher } from './worktree-watcher' import { FileContentWatcher } from './file-content-watcher' import { SnoozeTimer } from './snooze-timer' +import { InboxDeriver } from './inbox-deriver' import { getWeeklyStats } from './weekly-stats' import { discoverTools, runTool } from './tools' import type { TerminalTab, PaneNode, PaneLeaf } from '../shared/state/terminals' @@ -947,6 +948,19 @@ store.subscribe((event) => { const jsonClaudeStatusDeriver = new JsonClaudeStatusDeriver(store) jsonClaudeStatusDeriver.start() +// Turn-end summaries + read marks for the sidebar inbox. Subscribes after +// JsonClaudeStatusDeriver so a chat's busy→false has already become a +// 'waiting' status by the time it's seen here. +const inboxDeriver = new InboxDeriver(store) +inboxDeriver.start() + +store.subscribe((event) => { + if (!event.type.startsWith('inbox/')) return + const { turns, seenAt, prSeen } = store.getSnapshot().state.inbox + config.inbox = { turns, seenAt, prSeen } + saveConfig(config) +}) + /** Resolve the GitHub login of whoever owns the configured token, and * dispatch it so the sidebar can route PRs they didn't author into the * Reviewing group. Best-effort: any failure leaves the slice at null, @@ -5826,6 +5840,24 @@ function registerIpcHandlers(): void { return true }) + // Stamped here, not by the client, so two clients with skewed clocks + // agree on what's unread. + transport.onRequest('inbox:markSeen', (_ctx, worktreePath: string, tabId: string) => { + if (typeof worktreePath !== 'string' || typeof tabId !== 'string' || !tabId) return false + store.dispatch({ type: 'inbox/seen', payload: { tabId, ts: Date.now() } }) + return true + }) + + transport.onRequest( + 'inbox:markPrSeen', + (_ctx, worktreePath: string, fingerprint: string) => { + if (typeof worktreePath !== 'string' || !worktreePath) return false + if (typeof fingerprint !== 'string') return false + store.dispatch({ type: 'inbox/prSeen', payload: { worktreePath, fingerprint } }) + return true + } + ) + transport.onRequest('snooze:unsnooze', (_ctx, path: string) => { if (typeof path !== 'string' || !path) return false store.dispatch({ type: 'snooze/clear', payload: path }) diff --git a/src/main/json-claude-status-deriver.test.ts b/src/main/json-claude-status-deriver.test.ts index 049a0433..98bec75f 100644 --- a/src/main/json-claude-status-deriver.test.ts +++ b/src/main/json-claude-status-deriver.test.ts @@ -53,7 +53,10 @@ function startDeriverWithCapture( const events: CapturedEvents = { statusChanged: [], removed: [] } store.subscribe((event: StateEvent) => { if (event.type === 'terminals/statusChanged') { - events.statusChanged.push(event.payload) + // `at` is a wall-clock stamp; the assertions are about what changed. + const { at: _at, ...rest } = event.payload + void _at + events.statusChanged.push(rest) } else if (event.type === 'terminals/removed') { events.removed.push(event.payload) } diff --git a/src/main/json-claude-status-deriver.ts b/src/main/json-claude-status-deriver.ts index b95f5952..52eeaf8c 100644 --- a/src/main/json-claude-status-deriver.ts +++ b/src/main/json-claude-status-deriver.ts @@ -122,7 +122,7 @@ export class JsonClaudeStatusDeriver { this.lastStatus.set(sessionId, fingerprint) this.store.dispatch({ type: 'terminals/statusChanged', - payload: { id: sessionId, status, pendingTool } + payload: { id: sessionId, status, pendingTool, at: Date.now() } }) } } diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 5c506468..c2ab6041 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -21,6 +21,7 @@ import { } from './persistence-migrations' import type { CostsState } from '../shared/state/costs' import type { SnoozeEntry } from '../shared/state/snooze' +import type { InboxState } from '../shared/state/inbox' import type { WorktreeReview } from '../shared/state/reviews' import type { WorktreeSubscription } from '../shared/state/subscriptions' import type { WorktreeOrigin } from '../shared/state/origins' @@ -382,6 +383,8 @@ export interface Config { // Snoozed worktrees keyed by absolute path. Wakes when wakeAt is reached // or when the worktree's effective state transitions to 'processing'. snooze?: Record + /** Inbox turn summaries + read marks (see shared/state/inbox.ts). */ + inbox?: InboxState /** Worktree paths the user has pinned to the top of the sidebar. */ pinned?: Record // Default duration (days) for plain-click snooze. Min 1, default 7. diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.ts index ec3fddca..b29d31b2 100644 --- a/src/main/pty-manager.ts +++ b/src/main/pty-manager.ts @@ -187,7 +187,7 @@ export class PtyManager { this.sendSignal?.('terminal:data', id, msg) this.store?.dispatch({ type: 'terminals/statusChanged', - payload: { id, status: 'idle', pendingTool: null } + payload: { id, status: 'idle', pendingTool: null, at: Date.now() } }) return } @@ -208,7 +208,7 @@ export class PtyManager { this.sendSignal?.('terminal:data', id, msg) this.store?.dispatch({ type: 'terminals/statusChanged', - payload: { id, status: 'idle', pendingTool: null } + payload: { id, status: 'idle', pendingTool: null, at: Date.now() } }) return } @@ -231,7 +231,7 @@ export class PtyManager { this.sendSignal?.('terminal:data', id, msg) this.store?.dispatch({ type: 'terminals/statusChanged', - payload: { id, status: 'idle', pendingTool: null } + payload: { id, status: 'idle', pendingTool: null, at: Date.now() } }) return } @@ -277,7 +277,7 @@ export class PtyManager { log('pty', `exit id=${id} code=${exitCode}`) this.store?.dispatch({ type: 'terminals/statusChanged', - payload: { id, status: 'idle', pendingTool: null } + payload: { id, status: 'idle', pendingTool: null, at: Date.now() } }) this.store?.dispatch({ type: 'terminals/removed', payload: id }) this.sendSignal?.('terminal:exit', id, exitCode) diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index d3ab4ac1..3b6053a5 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -20,7 +20,9 @@ import { useHoldToQuit } from './hooks/useHoldToQuit' import { applyTheme, effectiveAppBg } from './theme-apply' import { getBackend } from './backend' import { HotkeysProvider, Tooltip } from './components/Tooltip' -import { Sidebar } from './components/Sidebar' +import { Sidebar, type SidebarView } from './components/Sidebar' +import { buildInboxModel, nextInboxItem, prEventFor, type InboxItem } from './inbox-model' +import { showToast } from './toast' import { ResizeHandle } from './components/ResizeHandle' import { AppTitleSegment } from './components/AppTitleSegment' import { NewWorktreeScreen, onOpenForkIntoWorktree } from './components/NewWorktreeScreen' @@ -1023,6 +1025,91 @@ function DesktopApp(): JSX.Element { const handleEndAliasEdit = useCallback(() => setEditingAliasPath(null), []) + // Sidebar inbox. Which view is showing is per-client; what's read and + // how each turn ended live in the inbox slice (main derives the turns). + const [sidebarView, setSidebarView] = useState(() => + localStorage.getItem('harness:sidebarView') === 'inbox' ? 'inbox' : 'projects' + ) + useEffect(() => { + localStorage.setItem('harness:sidebarView', sidebarView) + }, [sidebarView]) + const inboxModel = useMemo( + () => + buildInboxModel({ + worktrees: mergedData.flatWorktrees, + panes: mergedData.panes, + statuses: mergedData.statuses, + statusSince: mergedData.statusSince, + pendingTools: mergedData.pendingTools, + prStatuses: mergedData.prStatuses, + mergedPaths: mergedData.mergedPaths, + aliases: mergedData.aliases, + inbox: { + turns: mergedData.inboxTurns, + seenAt: mergedData.inboxSeenAt, + prSeen: mergedData.inboxPrSeen + } + }), + [mergedData] + ) + const handleOpenInboxItem = useCallback( + (item: InboxItem) => { + if (item.tabId && item.paneId) handleSidebarSelectTab(item.worktreePath, item.paneId, item.tabId) + else handleSidebarSelectWorktree(item.worktreePath) + if (item.prFingerprint) { + void backendFor(item.worktreePath).markInboxPrSeen(item.worktreePath, item.prFingerprint) + } + }, + [handleSidebarSelectTab, handleSidebarSelectWorktree, backendFor] + ) + const jumpToNextInboxItem = useCallback(() => { + const next = nextInboxItem(inboxModel, focusedTabId) + if (next) handleOpenInboxItem(next) + else if (inboxModel.needsYou.length > 0) showToast("You're on the only thing that needs you", undefined, 'inbox-jump') + else showToast('Nothing needs you right now', undefined, 'inbox-jump') + }, [inboxModel, focusedTabId, handleOpenInboxItem]) + // Looking at a tab reads it. Only while this window has focus: a turn + // that finishes in a backgrounded window is exactly what the inbox is + // for. Re-runs when the focused tab's turn ends while you watch it. + // Known gap: keyboard focus inside an embedded browser tab + // (WebContentsView) makes document.hasFocus() false, so a turn that + // ends beside a focused browser split stays unread until the window + // next fires 'focus'. Don't drop the early return below — it's also + // what keeps this from calling an older remote that lacks the method. + const focusedTurnEndedAt = activeWorktreeId && focusedTabId + ? (mergedData.inboxTurns[focusedTabId]?.endedAt ?? 0) + : 0 + const focusedSeenAt = focusedTabId ? (mergedData.inboxSeenAt[focusedTabId] ?? 0) : 0 + useEffect(() => { + if (!activeWorktreeId || !focusedTabId) return + if (focusedTurnEndedAt <= focusedSeenAt) return + const mark = (): void => { + if (document.visibilityState !== 'visible' || !document.hasFocus()) return + void backendFor(activeWorktreeId).markInboxSeen(activeWorktreeId, focusedTabId) + } + mark() + window.addEventListener('focus', mark) + return () => window.removeEventListener('focus', mark) + }, [activeWorktreeId, focusedTabId, focusedTurnEndedAt, focusedSeenAt, backendFor]) + // Opening a worktree by any route — sidebar, palette, PR badge, Cmd+N — + // reads its current PR event, same focus rule as tabs. + const activePrFingerprint = activeWorktreeId + ? (prEventFor(mergedData.prStatuses[activeWorktreeId], !!mergedData.mergedPaths[activeWorktreeId]) + ?.fingerprint ?? null) + : null + const activePrSeen = activeWorktreeId ? mergedData.inboxPrSeen[activeWorktreeId] : undefined + useEffect(() => { + if (!activeWorktreeId || !activePrFingerprint || activePrSeen === activePrFingerprint) return + const mark = (): void => { + if (document.visibilityState !== 'visible' || !document.hasFocus()) return + void backendFor(activeWorktreeId).markInboxPrSeen(activeWorktreeId, activePrFingerprint) + } + mark() + window.addEventListener('focus', mark) + return () => window.removeEventListener('focus', mark) + }, [activeWorktreeId, activePrFingerprint, activePrSeen, backendFor]) + + const handleOpenSubscriptionGraph = useCallback( (repoRoot?: string) => { const repo = @@ -1198,7 +1285,8 @@ function DesktopApp(): JSX.Element { historyBack: showNewWorktree ? undefined : goBack, historyForward: showNewWorktree ? undefined : goForward, setShowSettings, - onStartAliasEdit: setEditingAliasPath + onStartAliasEdit: setEditingAliasPath, + onJumpToInbox: jumpToNextInboxItem }) // File → Close Tab (Cmd+W). The accelerator lives on the menu item @@ -2042,6 +2130,10 @@ function DesktopApp(): JSX.Element { editingAliasPath={editingAliasPath} onStartAliasEdit={setEditingAliasPath} onEndAliasEdit={handleEndAliasEdit} + view={sidebarView} + onViewChange={setSidebarView} + inboxModel={inboxModel} + onOpenInboxItem={handleOpenInboxItem} /> )} {!singleScreenMode && !sidebarVisible && ( diff --git a/src/renderer/backend-routing.ts b/src/renderer/backend-routing.ts index 403f75e8..b7228185 100644 --- a/src/renderer/backend-routing.ts +++ b/src/renderer/backend-routing.ts @@ -51,6 +51,8 @@ export type WorktreeScopedMethod = | 'deleteReviewComment' | 'dismissPendingDeletion' | 'getBranchCommits' + | 'markInboxPrSeen' + | 'markInboxSeen' | 'getChangedFiles' | 'getCommitChangedFiles' | 'getCommitDiff' diff --git a/src/renderer/build-backend.ts b/src/renderer/build-backend.ts index f4fd3ca4..26364cd6 100644 --- a/src/renderer/build-backend.ts +++ b/src/renderer/build-backend.ts @@ -502,6 +502,10 @@ export function buildBackend( pinWorktree: (path: string) => req('pinned:pin', path), unpinWorktree: (path: string) => req('pinned:unpin', path), unsnooze: (path: string) => req('snooze:unsnooze', path), + markInboxSeen: (worktreePath: string, tabId: string) => + req('inbox:markSeen', worktreePath, tabId), + markInboxPrSeen: (worktreePath: string, fingerprint: string) => + req('inbox:markPrSeen', worktreePath, fingerprint), setSnoozeDefaultDays: (days: number) => reqConfig('config:setSnoozeDefaultDays', days), setCiNotifyOverride: (path: string, enabled: boolean | null) => req('ciNotify:setOverride', path, enabled), diff --git a/src/renderer/components/HotkeyCheatsheet.tsx b/src/renderer/components/HotkeyCheatsheet.tsx index acbabcd3..570e4bab 100644 --- a/src/renderer/components/HotkeyCheatsheet.tsx +++ b/src/renderer/components/HotkeyCheatsheet.tsx @@ -52,6 +52,7 @@ function buildGroups(hotkeys: Record): ShortcutGroup[] { rows: [ { label: 'New worktree', binding: b('newWorktree') }, { label: 'Refresh worktrees', binding: b('refreshWorktrees') }, + { label: 'Jump to next thing that needs you', binding: b('jumpToInbox') }, { label: 'Open PR in browser', binding: b('openPR') }, { label: 'Open in editor', binding: b('openInEditor') }, { label: 'Find in terminal or chat', binding: 'Cmd+F' }, diff --git a/src/renderer/components/InboxView.tsx b/src/renderer/components/InboxView.tsx new file mode 100644 index 00000000..730c7168 --- /dev/null +++ b/src/renderer/components/InboxView.tsx @@ -0,0 +1,139 @@ +import { useEffect, useState } from 'react' +import { ChevronDown, ChevronRight, GitPullRequest, Inbox } from 'lucide-react' +import type { InboxItem, InboxModel, InboxSectionKey } from '../inbox-model' + +/** The sidebar's Inbox view: one row per agent tab, bucketed by what it + * needs from you. Display only — the bucketing lives in inbox-model.ts + * and the read marks in the inbox slice. */ + +const DOT: Record = { + approval: 'bg-danger animate-pulse', + question: 'bg-accent', + done: 'bg-warning', + pr: '', + prInfo: '', + working: 'bg-success animate-pulse', + seen: 'bg-faint' +} + +const PR_COLOR: Record, string> = { + 'ci-failed': 'text-danger', + conflict: 'text-danger', + 'changes-requested': 'text-warning', + ready: 'text-success', + merged: 'text-accent' +} + +function ago(ts: number, now: number): string { + if (!ts) return '' + const s = Math.max(0, Math.round((now - ts) / 1000)) + if (s < 60) return 'now' + const m = Math.round(s / 60) + if (m < 60) return `${m}m` + const h = Math.round(m / 60) + if (h < 24) return `${h}h` + return `${Math.round(h / 24)}d` +} + +export function InboxView({ + model, + activeWorktreeId, + activeTabId, + onOpen +}: { + model: InboxModel + activeWorktreeId: string | null + activeTabId: string | null + onOpen: (item: InboxItem) => void +}): JSX.Element { + // Per-client UI fold state, like the Projects view's group collapse. + const [open, setOpen] = useState>>({}) + // Ages are minute-granular; re-render on a slow clock so they don't + // freeze between store events. + const [now, setNow] = useState(() => Date.now()) + useEffect(() => { + const t = setInterval(() => setNow(Date.now()), 30_000) + return () => clearInterval(t) + }, []) + const nonEmpty = model.sections.filter((s) => s.items.length > 0) + + return ( +
+ {model.needsYou.length === 0 && ( +
+ + Nothing needs you right now. +
+ )} + {nonEmpty.map((section) => { + const expanded = open[section.key] ?? !section.collapsedByDefault + return ( +
+ + {expanded && + section.items.map((item) => { + const active = + item.worktreePath === activeWorktreeId && + item.prFingerprint === undefined && + item.tabId === activeTabId + return ( + + ) + })} +
+ ) + })} +
+ ) +} diff --git a/src/renderer/components/Sidebar.tsx b/src/renderer/components/Sidebar.tsx index 9dd5f373..6e9f76c8 100644 --- a/src/renderer/components/Sidebar.tsx +++ b/src/renderer/components/Sidebar.tsx @@ -1,10 +1,14 @@ -import { Trash2, Layers, Plus, Rows3, PanelLeftClose, RefreshCw } from 'lucide-react' +import { Trash2, Layers, Plus, Rows3, PanelLeftClose, RefreshCw, Inbox, BellDot } from 'lucide-react' import { Tooltip } from './Tooltip' import type { GroupKey } from '../../shared/worktree-sort' import type { SectionRepoRoot, WorktreeListModel } from '../worktree-list-model' import { WorktreeList } from './WorktreeList' import { BackendChipStrip } from './BackendChipStrip' import { BottomIconStrip } from './BottomIconStrip' +import { InboxView } from './InboxView' +import type { InboxItem, InboxModel } from '../inbox-model' + +export type SidebarView = 'projects' | 'inbox' /** The desktop shell around the shared worktree list: fixed-width panel, * header controls, backend chip strip and bottom icon strip. The list @@ -54,6 +58,10 @@ interface SidebarProps { editingAliasPath: string | null onStartAliasEdit: (path: string) => void onEndAliasEdit: () => void + view: SidebarView + onViewChange: (view: SidebarView) => void + inboxModel: InboxModel + onOpenInboxItem: (item: InboxItem) => void } export function Sidebar({ @@ -97,8 +105,13 @@ export function Sidebar({ onCollapseSidebar, editingAliasPath, onStartAliasEdit, - onEndAliasEdit + onEndAliasEdit, + view, + onViewChange, + inboxModel, + onOpenInboxItem }: SidebarProps): JSX.Element { + const needsYouCount = inboxModel.needsYou.length return (
{/* Sidebar header */} @@ -124,6 +137,29 @@ export function Sidebar({ + {/* Swaps the list below for the Inbox. Kept as a quiet icon: + a bell only when something actually needs you. */} + 0 + ? `Inbox: ${needsYouCount} need${needsYouCount === 1 ? 's' : ''} you` + : 'Inbox' + } + side="bottom" + > + +