diff --git a/apps/api/src/operation-ports.ts b/apps/api/src/operation-ports.ts index 294d025bae..ac370e9f9a 100644 --- a/apps/api/src/operation-ports.ts +++ b/apps/api/src/operation-ports.ts @@ -121,6 +121,7 @@ export function createOperationPorts(env: Env): OperationPorts { resolveTranscriptOwner: (...a) => projectData.resolveTranscriptOwner(env, ...a), getMailboxMessage: (...a) => projectData.getMailboxMessage(env, ...a), listActiveAttentionMarkers: (...a) => projectData.listActiveAttentionMarkers(env, ...a), + listWorkingChatSessionIds: (...a) => projectData.listWorkingChatSessionIds(env, ...a), getRunReceiptFacts: (...a) => projectData.getRunReceiptFacts(env, ...a), countRunNudges: (...a) => projectData.countRunNudges(env, ...a), searchKnowledgeObservations: (...a) => projectData.searchKnowledgeObservations(env, ...a), diff --git a/apps/api/src/services/project-brief/refresh.ts b/apps/api/src/services/project-brief/refresh.ts index c50a757fc2..93fba3113f 100644 --- a/apps/api/src/services/project-brief/refresh.ts +++ b/apps/api/src/services/project-brief/refresh.ts @@ -36,6 +36,7 @@ import type { Env } from '../../env'; import { log } from '../../lib/logger'; import { fetchWorkersAIChatCompletion, WorkersAIGatewayError } from '../ai-proxy-shared'; import { LlmUnavailableError } from '../llm-chat-target'; +import { listWorkingChatSessionIds } from '../project-data'; import { getTaskTitleModelControls } from '../task-title'; import { parseBriefReply } from './parse'; import { buildBriefPrompt } from './prompt'; @@ -181,7 +182,10 @@ async function refresh(input: BriefRefreshInput): Promise { const [stateRaw, facts] = await Promise.all([ db.prepare(READ_STATE_SQL).bind(projectId).first>(), - readBriefFacts(db, projectId, now), + // Running now's mid-turn chats come from the ProjectData activity mirror, as on the page. + listWorkingChatSessionIds(env, projectId).then((working) => + readBriefFacts(db, projectId, now, working) + ), ]); const state = v.safeParse(StateRow, stateRaw); if (!state.success) throw new Error('project_briefs row unreadable after check claim'); diff --git a/apps/api/tests/unit/operations/project-brief-facts.test.ts b/apps/api/tests/unit/operations/project-brief-facts.test.ts index bcbc888e00..0f8a96395b 100644 --- a/apps/api/tests/unit/operations/project-brief-facts.test.ts +++ b/apps/api/tests/unit/operations/project-brief-facts.test.ts @@ -31,6 +31,8 @@ const ISO_NOW = new Date(NOW).toISOString(); describe('project brief facts and read', () => { let sqlite: Database.Database; let db: D1Database; + /** What the ProjectData activity mirror reports as mid-turn (`listWorkingChatSessionIds`). */ + let working: string[] = []; function insert(table: string, row: Record): void { const columns = Object.keys(row); @@ -57,7 +59,9 @@ describe('project brief facts and read', () => { }); } + /** A chat whose agent is mid-turn. A foreign chat is reported too, so the D1 scope must hold. */ function runningChat(id: string, projectId = 'p'): void { + working.push(id); insert('tasks', { id: `task-${id}`, project_id: projectId, @@ -139,6 +143,7 @@ describe('project brief facts and read', () => { } beforeEach(() => { + working = []; sqlite = new Database(':memory:'); createAllSchemaTables(sqlite, schema); sqlite.exec(` @@ -165,7 +170,7 @@ describe('project brief facts and read', () => { ask('answered', { status: 'answered' }); ask('expired', { expires_at: NOW - 1 }); ask('foreign-ask', { project_id: 'foreign', assignee_user_id: 'outsider' }); - const facts = await readBriefFacts(db, 'p', NOW); + const facts = await readBriefFacts(db, 'p', NOW, working); expect(facts.asks.map((a) => a.id)).toEqual(['mine']); }); @@ -178,7 +183,7 @@ describe('project brief facts and read', () => { claimed_by_user_id: 'owner', }); ask('team', { assignee_kind: 'team', assignee_user_id: null }); - const facts = await readBriefFacts(db, 'p', NOW); + const facts = await readBriefFacts(db, 'p', NOW, working); expect(facts.asks.map((a) => a.id)).toEqual(['team']); }); @@ -190,7 +195,7 @@ describe('project brief facts and read', () => { status: 'removed', }); ask('mine'); - expect((await readBriefFacts(db, 'p', NOW)).asks.map((a) => a.id)).toEqual(['mine']); + expect((await readBriefFacts(db, 'p', NOW, working)).asks.map((a) => a.id)).toEqual(['mine']); }); it('cleans and caps titles, blocking first, and gives ages in words', async () => { @@ -199,7 +204,7 @@ describe('project brief facts and read', () => { title: `Line one\nline two\u0007 ${'x'.repeat(300)}`, created_at: NOW - 30 * 60_000, }); - const facts = await readBriefFacts(db, 'p', NOW); + const facts = await readBriefFacts(db, 'p', NOW, working); expect(facts.asks.map((a) => [a.id, a.blocking, a.age])).toEqual([ ['long', true, 'just now'], ['later', false, 'this week'], @@ -226,7 +231,7 @@ describe('project brief facts and read', () => { window('reset-cred', 'platform', 'rejected', { resets_at: NOW - 1 }); window('calm-cred', 'project', 'ok'); - const facts = await readBriefFacts(db, 'p', NOW); + const facts = await readBriefFacts(db, 'p', NOW, working); expect(facts.runningChats.map((c) => c.id)).toEqual(['live']); expect(facts.failingAutomations.map((a) => a.id)).toEqual(['broken']); expect(facts.accounts.map((a) => [a.id, a.level])).toEqual([ @@ -237,12 +242,12 @@ describe('project brief facts and read', () => { }); it('is quiet with nothing open and nothing running, and the fingerprint follows only material changes', async () => { - const empty = await readBriefFacts(db, 'p', NOW); + const empty = await readBriefFacts(db, 'p', NOW, working); expect(briefFactsAreQuiet(empty)).toBe(true); ask('a'); runningChat('live'); - const before = await briefFactsFingerprint(await readBriefFacts(db, 'p', NOW)); + const before = await briefFactsFingerprint(await readBriefFacts(db, 'p', NOW, working)); // A new idea is an input but not a reason to regenerate. insert('tasks', { id: 'idea-1', @@ -254,19 +259,21 @@ describe('project brief facts and read', () => { created_at: ISO_NOW, updated_at: ISO_NOW, }); - const withIdea = await readBriefFacts(db, 'p', NOW); + const withIdea = await readBriefFacts(db, 'p', NOW, working); expect(withIdea.newIdeas.map((i) => i.id)).toEqual(['idea-1']); expect(await briefFactsFingerprint(withIdea)).toBe(before); // Answering the ask is. sqlite.prepare(`UPDATE asks SET status = 'answered' WHERE id = 'a'`).run(); - expect(await briefFactsFingerprint(await readBriefFacts(db, 'p', NOW))).not.toBe(before); + expect(await briefFactsFingerprint(await readBriefFacts(db, 'p', NOW, working))).not.toBe( + before + ); }); it('ranks accounts by urgency before the cap, so an account out of usage is never dropped', async () => { for (let i = 0; i < 9; i += 1) window(`a-warning-${i}`, 'project', 'warning'); window('z-rejected', 'platform', 'rejected'); window('y-critical', 'project', 'critical'); - const facts = await readBriefFacts(db, 'p', NOW); + const facts = await readBriefFacts(db, 'p', NOW, working); expect(facts.accounts.map((a) => a.id).slice(0, 2)).toEqual(['z-rejected', 'y-critical']); expect(facts.accounts).toHaveLength(8); expect(facts.moreNotShown).toContain('accounts'); @@ -275,12 +282,12 @@ describe('project brief facts and read', () => { it('says which lists were capped, and only those (rule 65)', async () => { for (let i = 0; i < 9; i += 1) ask(`ask-${i}`, { created_at: NOW - (i + 1) * 60_000 }); trigger('broken', ['failed', 'failed', 'failed']); - const facts = await readBriefFacts(db, 'p', NOW); + const facts = await readBriefFacts(db, 'p', NOW, working); expect(facts.asks).toHaveLength(8); expect(facts.moreNotShown).toEqual(['asks']); // Control: at the cap exactly, nothing is said to be missing. sqlite.prepare(`DELETE FROM asks WHERE id = 'ask-0'`).run(); - expect((await readBriefFacts(db, 'p', NOW)).moreNotShown).toEqual([]); + expect((await readBriefFacts(db, 'p', NOW, working)).moreNotShown).toEqual([]); }); describe('readProjectBrief', () => { @@ -315,7 +322,7 @@ describe('project brief facts and read', () => { [about('ask', 'open-ask'), about('ask', 'answered-ask'), about('ask', 'foreign-open')], { asks: ['open-ask', 'answered-ask', 'foreign-open'] } ); - const brief = await readProjectBrief(db, 'p', NOW); + const brief = await readProjectBrief(db, 'p', NOW, working); expect( brief?.sentences.map((s) => ('ref' in s.parts[0]! ? s.parts[0].ref.id : null)) ).toEqual(['open-ask']); @@ -325,11 +332,9 @@ describe('project brief facts and read', () => { it('drops a running-chat claim when the agent finished its turn (Running now no longer lists it), keeps it while paused on a question', async () => { runningChat('finished-turn'); runningChat('paused'); - sqlite - .prepare( - `UPDATE session_summaries SET agent_completed_at = ? WHERE id IN ('finished-turn', 'paused')` - ) - .run(NOW - 1_000); + // Both turns ended: the activity mirror reports neither as working. The latched + // execution step is not evidence either way. + working = []; sqlite .prepare( `UPDATE tasks SET execution_step = 'awaiting_followup' WHERE id = 'task-finished-turn'` @@ -340,7 +345,7 @@ describe('project brief facts and read', () => { chats: ['finished-turn', 'paused'], asks: [], }); - const brief = await readProjectBrief(db, 'p', NOW); + const brief = await readProjectBrief(db, 'p', NOW, working); expect( brief?.sentences.map((x) => ('ref' in x.parts[0]! ? x.parts[0].ref.id : null)) ).toEqual(['paused']); @@ -352,7 +357,7 @@ describe('project brief facts and read', () => { storeBrief([about('automation', 'broken'), about('automation', 'fixed')], { automations: ['broken', 'fixed'], }); - const brief = await readProjectBrief(db, 'p', NOW); + const brief = await readProjectBrief(db, 'p', NOW, working); expect( brief?.sentences.map((x) => ('ref' in x.parts[0]! ? x.parts[0].ref.id : null)) ).toEqual(['broken']); @@ -366,7 +371,7 @@ describe('project brief facts and read', () => { storeBrief([about('chat', 'live'), about('chat', 'ended'), about('chat', 'failed-earlier')], { chats: ['live', 'ended'], }); - const brief = await readProjectBrief(db, 'p', NOW); + const brief = await readProjectBrief(db, 'p', NOW, working); expect( brief?.sentences.map((s) => ('ref' in s.parts[0]! ? s.parts[0].ref.id : null)) ).toEqual(['live', 'failed-earlier']); @@ -377,7 +382,7 @@ describe('project brief facts and read', () => { JSON.stringify({ sentences: [about('chat', 'foreign-live'), about('chat', 'live')] }), JSON.stringify(['foreign-live', 'live']) ); - const scoped = await readProjectBrief(db, 'p', NOW); + const scoped = await readProjectBrief(db, 'p', NOW, working); expect( scoped?.sentences.map((s) => ('ref' in s.parts[0]! ? s.parts[0].ref.id : null)) ).toEqual(['live']); @@ -386,14 +391,14 @@ describe('project brief facts and read', () => { it('is fresh when every claim still holds, and null when none does', async () => { ask('open-ask'); storeBrief([about('ask', 'open-ask')], { asks: ['open-ask'] }); - expect(await readProjectBrief(db, 'p', NOW)).toEqual({ + expect(await readProjectBrief(db, 'p', NOW, working)).toEqual({ sentences: [about('ask', 'open-ask')], generatedAt: new Date(NOW - 60_000).toISOString(), stale: false, refreshing: false, }); sqlite.prepare(`UPDATE asks SET status = 'archived'`).run(); - expect(await readProjectBrief(db, 'p', NOW)).toBeNull(); + expect(await readProjectBrief(db, 'p', NOW, working)).toBeNull(); }); it('says refreshing while a generation is in flight, and not after it is abandoned', async () => { @@ -403,8 +408,11 @@ describe('project brief facts and read', () => { { asks: ['open-ask'] }, { pending_since: NOW - 10_000 } ); - expect(await readProjectBrief(db, 'p', NOW)).toMatchObject({ stale: true, refreshing: true }); - expect(await readProjectBrief(db, 'p', NOW + 10 * 60_000)).toMatchObject({ + expect(await readProjectBrief(db, 'p', NOW, working)).toMatchObject({ + stale: true, + refreshing: true, + }); + expect(await readProjectBrief(db, 'p', NOW + 10 * 60_000, working)).toMatchObject({ refreshing: false, }); }); @@ -416,34 +424,34 @@ describe('project brief facts and read', () => { { asks: ['open-ask'] }, { stale: 1, last_error_at: NOW - 1_000 } ); - expect(await readProjectBrief(db, 'p', NOW)).toBeNull(); + expect(await readProjectBrief(db, 'p', NOW, working)).toBeNull(); sqlite .prepare( `UPDATE project_briefs SET stale = 0, last_error_at = NULL, brief_json = '{"sentences":[{"parts":[{"ref":{"kind":"evil","id":"x","label":"x"}}]}]}'` ) .run(); - expect(await readProjectBrief(db, 'p', NOW)).toBeNull(); + expect(await readProjectBrief(db, 'p', NOW, working)).toBeNull(); sqlite .prepare( `UPDATE project_briefs SET brief_json = '{"sentences":[{"parts":[{"ref":{"kind":"pullRequest","id":"1","label":"x","url":"javascript:alert(1)"}}]}]}'` ) .run(); - expect(await readProjectBrief(db, 'p', NOW)).toBeNull(); + expect(await readProjectBrief(db, 'p', NOW, working)).toBeNull(); }); it('drops an ask claim once a second member joins: they must not see, through the brief, an ask their inbox hides (owner control first)', async () => { ask('mine'); storeBrief([about('ask', 'mine')], { asks: ['mine'] }); - expect(await readProjectBrief(db, 'p', NOW)).not.toBeNull(); + expect(await readProjectBrief(db, 'p', NOW, working)).not.toBeNull(); addTeammate(); - expect(await readProjectBrief(db, 'p', NOW)).toBeNull(); + expect(await readProjectBrief(db, 'p', NOW, working)).toBeNull(); }); it('drops a claim about an expired ask the sweep has not closed yet', async () => { ask('expiring', { expires_at: NOW + 1_000 }); storeBrief([about('ask', 'expiring')], { asks: ['expiring'] }); - expect(await readProjectBrief(db, 'p', NOW)).not.toBeNull(); - expect(await readProjectBrief(db, 'p', NOW + 2_000)).toBeNull(); + expect(await readProjectBrief(db, 'p', NOW, working)).not.toBeNull(); + expect(await readProjectBrief(db, 'p', NOW + 2_000, working)).toBeNull(); }); it('re-checks a named account, and never sends its credential reference to the page', async () => { @@ -465,20 +473,20 @@ describe('project brief facts and read', () => { ], { accounts: ['cc_credentials:shared-anthropic'] } ); - const brief = await readProjectBrief(db, 'p', NOW); + const brief = await readProjectBrief(db, 'p', NOW, working); expect(brief?.sentences[0]?.parts[0]).toEqual({ ref: { kind: 'account', id: 'account', label: "the project's anthropic account" }, }); expect(JSON.stringify(brief)).not.toContain('cc_credentials:'); // Back to calm: the claim is no longer true. sqlite.prepare(`UPDATE credential_limit_windows SET last_event_level = 'ok'`).run(); - expect(await readProjectBrief(db, 'p', NOW)).toBeNull(); + expect(await readProjectBrief(db, 'p', NOW, working)).toBeNull(); }); it('reads a malformed ref list as empty instead of failing the read', async () => { ask('open-ask'); storeBrief([about('chat', 'failed-earlier')], {}, { ref_asks_json: 'not json' }); - expect(await readProjectBrief(db, 'p', NOW)).not.toBeNull(); + expect(await readProjectBrief(db, 'p', NOW, working)).not.toBeNull(); }); }); diff --git a/apps/api/tests/unit/operations/project-overview.test.ts b/apps/api/tests/unit/operations/project-overview.test.ts index fb303676aa..6af12706ce 100644 --- a/apps/api/tests/unit/operations/project-overview.test.ts +++ b/apps/api/tests/unit/operations/project-overview.test.ts @@ -2,7 +2,8 @@ * projectOverviewGet against a real SQL engine. "Running" is a SQL predicate over the D1 chat * index and the task table, and the project scope is a join condition, so a foreign project's * rows are seeded beside the owner's and must never appear (rule 11, rule 28 section 5). The - * ProjectData idea snapshot is an external boundary and is mocked. + * ProjectData object is an external boundary and is mocked: its idea snapshot, and which chats + * its activity mirror reports as mid-turn (`listWorkingChatSessionIds`). */ import type { OperationContext } from '@simple-agent-manager/operations'; import { projectOverviewGet } from '@simple-agent-manager/operations'; @@ -18,10 +19,11 @@ import { createSqliteD1, } from '../../helpers/sqlite-d1'; -const mocks = vi.hoisted(() => ({ snapshots: vi.fn() })); +const mocks = vi.hoisted(() => ({ snapshots: vi.fn(), working: vi.fn() })); vi.mock('../../../src/services/project-data', async (importOriginal) => ({ ...(await importOriginal()), getIdeaWorkSnapshots: mocks.snapshots, + listWorkingChatSessionIds: mocks.working, })); const NOW = 1_794_000_000_000; @@ -30,6 +32,8 @@ const HOUR = 3_600_000; describe('projectOverviewGet', () => { let sqlite: Database.Database; let env: Env; + /** Chats the ProjectData activity mirror reports as mid-turn. */ + let working: Set; function ctx(userId = 'owner'): OperationContext { return { @@ -84,18 +88,26 @@ describe('projectOverviewGet', () => { }); } - /** A chat and its task, the way every chat is task-backed. */ + /** + * A chat and its task, the way every chat is task-backed. Its agent is mid-turn unless + * `agent: 'idle'` (the activity mirror then does not report it). + */ function running( id: string, chatFields: Record = {}, - taskFields: Record = {} + taskFields: Record = {}, + { agent = 'working' }: { agent?: 'working' | 'idle' } = {} ): void { task(`task-${id}`, { chat_session_id: id, ...taskFields }); chat(id, chatFields); + if (agent === 'working') working.add(id); } + const IDLE = { agent: 'idle' } as const; beforeEach(() => { vi.clearAllMocks(); + working = new Set(); + mocks.working.mockImplementation(async () => [...working]); sqlite = new Database(':memory:'); createAllSchemaTables(sqlite, schema); sqlite.exec(` @@ -131,23 +143,30 @@ describe('projectOverviewGet', () => { it('lists working, starting and waiting chats and leaves idle, sleeping and finished ones out', async () => { running('working'); - running('starting', { agent_completed_at: null }, { status: 'queued', execution_step: null }); - running('waiting', { - agent_completed_at: NOW - 120_000, - attention_json: JSON.stringify({ markerId: 'm1', kind: 'needs_input' }), - }); - running('idle', { agent_completed_at: NOW - 120_000 }); + running('starting', {}, { status: 'queued', execution_step: null }, IDLE); + running( + 'waiting', + { attention_json: JSON.stringify({ markerId: 'm1', kind: 'needs_input' }) }, + {}, + IDLE + ); + running('idle', {}, {}, IDLE); + // The activity mirror says working, but the chat or task is asleep: not running. running('sleeping-chat', { status: 'sleeping' }); running('sleeping-task', {}, { status: 'sleeping' }); // The chat index still says active, but its task finished: not running. running('finished', {}, { status: 'completed', execution_step: null }); - running('awaiting', {}, { execution_step: 'awaiting_followup' }); + // The incident (2026-11-20): every chat past its first turn has its task's step latched at + // `awaiting_followup`. Mid-turn is the activity mirror's call, not the step's. + running('later-turn', {}, { execution_step: 'awaiting_followup' }); + running('later-turn-idle', {}, { execution_step: 'awaiting_followup' }, IDLE); const result = await projectOverviewGet(ctx(), { projectId: 'p' }); const byId = new Map(result.running.items.map((item) => [item.sessionId, item])); - expect([...byId.keys()].sort()).toEqual(['starting', 'waiting', 'working']); - expect(result.running.total).toBe(3); + expect([...byId.keys()].sort()).toEqual(['later-turn', 'starting', 'waiting', 'working']); + expect(result.running.total).toBe(4); + expect(byId.get('later-turn')?.state).toBe('working'); expect(byId.get('working')).toMatchObject({ state: 'working', topic: 'Chat working', @@ -162,10 +181,7 @@ describe('projectOverviewGet', () => { }); it('says a question is the viewer’s only when the viewer started the chat', async () => { - running('waiting', { - agent_completed_at: NOW - 1, - attention_json: JSON.stringify({ markerId: 'm1' }), - }); + running('waiting', { attention_json: JSON.stringify({ markerId: 'm1' }) }, {}, IDLE); const result = await projectOverviewGet(ctx('teammate'), { projectId: 'p' }); expect(result.running.items).toEqual([ expect.objectContaining({ sessionId: 'waiting', state: 'waiting', waitingOnViewer: false }), @@ -182,9 +198,12 @@ describe('projectOverviewGet', () => { user_id: 'outsider', task_id: 'task-foreign-chat', }); + // Both attack chats are reported mid-turn, so only the project predicates can keep them out. + working.add('foreign-chat'); // Attack 2: our chat row pointing at a foreign project's running task. task('task-borrowed', { project_id: 'foreign', user_id: 'outsider' }); chat('borrowed', { task_id: 'task-borrowed' }); + working.add('borrowed'); // Attack 3: our task naming a foreign project's profile. running('foreign-profile', {}, { agent_profile_hint: 'profile-foreign' }); // Attack 4: a task naming another member's private global profile. @@ -232,23 +251,35 @@ describe('projectOverviewGet', () => { for (let i = 0; i < 8; i++) running(`busy-${i}`, { last_message_at: NOW - i * 1000 }); // Older than every busy chat: by recency alone it would fall behind the cap of five. const question = JSON.stringify({ markerId: 'm1' }); - running('old-question', { - last_message_at: NOW - HOUR, - agent_completed_at: NOW - HOUR, - attention_json: question, - }); - running('older-question', { - last_message_at: NOW - 2 * HOUR, - agent_completed_at: NOW - 2 * HOUR, - attention_json: question, - }); + running( + 'old-question', + { + last_message_at: NOW - HOUR, + attention_json: question, + }, + {}, + IDLE + ); + running( + 'older-question', + { + last_message_at: NOW - 2 * HOUR, + attention_json: question, + }, + {}, + IDLE + ); // Control: a teammate's waiting chat is not the owner's to answer and is not lifted. - running('mates-question', { - last_message_at: NOW - 3 * HOUR, - agent_completed_at: NOW - 3 * HOUR, - attention_json: question, - created_by_user_id: 'teammate', - }); + running( + 'mates-question', + { + last_message_at: NOW - 3 * HOUR, + attention_json: question, + created_by_user_id: 'teammate', + }, + {}, + IDLE + ); const result = await projectOverviewGet(ctx(), { projectId: 'p' }); @@ -293,20 +324,20 @@ describe('projectOverviewGet', () => { it('reads a chat paused on an open question ask as waiting, ranked first and counted', async () => { // Idle chats with no attention marker: only the ask can make them show. - const idle = { agent_completed_at: NOW - 120_000, last_message_at: NOW - 10 * HOUR }; - running('asked', idle); + const idle = { last_message_at: NOW - 10 * HOUR }; + running('asked', idle, {}, IDLE); question('ask-1', 'asked'); running('fresh', {}, {}); // Controls: an expired and an answered question leave the chat idle (not shown). - running('expired-q', idle); + running('expired-q', idle, {}, IDLE); question('ask-expired', 'expired-q', { expires_at: Date.now() - 1 }); - running('answered-q', idle); + running('answered-q', idle, {}, IDLE); question('ask-answered', 'answered-q', { status: 'answered' }); // Attack: another project's open question naming this project's chat id. - running('foreign-q', idle); + running('foreign-q', idle, {}, IDLE); question('ask-foreign', 'foreign-q', { project_id: 'foreign' }); // A non-blocking ask (inbox slice D) does not pause its chat: it stays idle (not shown). - running('nonblocking-q', idle); + running('nonblocking-q', idle, {}, IDLE); question('ask-nonblocking', 'nonblocking-q', { blocking: 0, expires_at: null }); const result = await projectOverviewGet(ctx(), { projectId: 'p', runningLimit: 1 }); @@ -345,16 +376,16 @@ describe('projectOverviewGet', () => { it('keeps a chat paused on a pending secret request in Running now, as waiting (slice F2)', async () => { // The agent ended its turn after asking: without the request the chat is idle and hidden, // while the inbox still calls it "paused on this". - const idle = { agent_completed_at: NOW - 120_000, last_message_at: NOW - 10 * HOUR }; - running('secret-wait', idle); + const idle = { last_message_at: NOW - 10 * HOUR }; + running('secret-wait', idle, {}, IDLE); secretRequest('sr-1', 'secret-wait'); // Controls: expired and fulfilled requests leave the chat idle (not shown). - running('secret-expired', idle); + running('secret-expired', idle, {}, IDLE); secretRequest('sr-expired', 'secret-expired', { expires_at: Date.now() - 1 }); - running('secret-done', idle); + running('secret-done', idle, {}, IDLE); secretRequest('sr-done', 'secret-done', { status: 'fulfilled' }); // Attack: another project's pending request naming this project's chat id. - running('secret-foreign', idle); + running('secret-foreign', idle, {}, IDLE); secretRequest('sr-foreign', 'secret-foreign', { project_id: 'foreign' }); const result = await projectOverviewGet(ctx(), { projectId: 'p' }); @@ -371,7 +402,11 @@ describe('projectOverviewGet', () => { // A teammate sees the chat as paused too, but not on them: it is the creator's to answer. const mate = await projectOverviewGet(ctx('teammate'), { projectId: 'p' }); expect(mate.running.items).toEqual([ - expect.objectContaining({ sessionId: 'secret-wait', state: 'waiting', waitingOnViewer: false }), + expect.objectContaining({ + sessionId: 'secret-wait', + state: 'waiting', + waitingOnViewer: false, + }), ]); expect(mate.running.waitingOnViewerTotal).toBe(0); }); @@ -465,6 +500,16 @@ describe('projectOverviewGet', () => { expect(result.running.items.map((item) => item.sessionId)).toEqual(['working']); }); + it('says Running now is unavailable when the activity read fails, instead of calling every chat idle', async () => { + running('working'); + mocks.working.mockRejectedValue(new Error('ProjectData unavailable')); + const result = await projectOverviewGet(ctx(), { projectId: 'p' }); + expect(result.unavailable).toContain('running'); + expect(result.running).toEqual({ items: [], total: 0, waitingOnViewerTotal: 0 }); + // Control: the other sections still load. + expect(result.unavailable).not.toContain('pullRequests'); + }); + it('stays within the dashboard round-trip budget with ideas that have linked work', async () => { running('working'); for (let i = 0; i < 3; i++) { @@ -527,10 +572,12 @@ describe('projectOverviewGet', () => { expect(result.unavailable).toEqual([]); expect(result.recent.ideas).toHaveLength(3); - const doCalls = mocks.snapshots.mock.calls.length; + const doCalls = mocks.snapshots.mock.calls.length + mocks.working.mock.calls.length; // .claude/rules/60: a dashboard read spends at most 20 D1 + DO round trips. expect(d1Reads + doCalls).toBeLessThanOrEqual(20); - expect(doCalls).toBe(1); + // One idea snapshot and one activity read, shared by Running now and the brief. + expect(mocks.snapshots).toHaveBeenCalledTimes(1); + expect(mocks.working).toHaveBeenCalledTimes(1); }); it('reads the newest merged pull requests from an index, without sorting the project history', async () => { diff --git a/apps/api/tests/workers/overview-brief-capability.test.ts b/apps/api/tests/workers/overview-brief-capability.test.ts index a51c5d903f..4d2026d752 100644 --- a/apps/api/tests/workers/overview-brief-capability.test.ts +++ b/apps/api/tests/workers/overview-brief-capability.test.ts @@ -215,8 +215,10 @@ describe('Overview brief through the real entry points', () => { ); expect(gatewayCalls()).toHaveLength(1); - // The person answers through the real inbox route. + // The person answers through the real inbox route, and the agent takes the answer up: its + // activity mirror reports a turn in flight, so the chat is still running (no longer paused). await answer(s, `ask:${askId}`, 'Staging first'); + await s.project.reportActivity(s.chatSessionId, 'prompting'); await syncSummaries(s.project); await allowNextCheck(s); const after = await viewOverview(s); @@ -282,6 +284,8 @@ describe('Overview brief through the real entry points', () => { await viewOverview(s); expect(gatewayCalls()).toHaveLength(1); await answer(s, `ask:${askId}`, 'Staging first'); + // The agent takes the answer up, so the chat is still running. + await s.project.reportActivity(s.chatSessionId, 'prompting'); await syncSummaries(s.project); // Past the minimum interval, but not past the day. await testEnv.DATABASE.prepare( diff --git a/apps/api/tests/workers/overview-running-now-activity.test.ts b/apps/api/tests/workers/overview-running-now-activity.test.ts new file mode 100644 index 0000000000..731182a189 --- /dev/null +++ b/apps/api/tests/workers/overview-running-now-activity.test.ts @@ -0,0 +1,160 @@ +/** + * Running now reads "is the agent mid-turn" from the ProjectData activity mirror, through the + * real Overview route, the real ProjectData object and the real D1 index (rule 62, rule 74). + * + * Incident (2026-11-20): Running now said "Nothing is running" while ten SAM chats were awake and + * streaming. Its predicate keyed on `tasks.execution_step <> 'awaiting_followup'` and + * `agent_completed_at IS NULL`; the step latches at `awaiting_followup` after a chat's first turn + * and nothing writes `agent_completed_at`, so only first-turn chats were ever listed. + */ +import type { ProjectData } from '@simple-agent-manager/project-data/internal/do/index'; +import type { ProjectOverviewResponse } from '@simple-agent-manager/shared'; +import { runInDurableObject } from 'cloudflare:test'; +import { Hono } from 'hono'; +import { describe, expect, it } from 'vitest'; + +import type { Env } from '../../src/env'; +import { handleAppError } from '../../src/middleware/app-error-handler'; +import { requireApproved, requireAuth } from '../../src/middleware/auth'; +import { projectOverviewRoutes } from '../../src/routes/project-overview'; +import { seed, type Seeded, testEnv } from './helpers/inbox-harness'; + +const executionCtx = { + waitUntil: () => undefined, + passThroughOnException: () => undefined, + props: {}, +} as unknown as ExecutionContext; + +function app() { + const hono = new Hono<{ Bindings: Env }>(); + hono.onError(handleAppError); + hono.use('/api/*', requireAuth(), requireApproved()); + hono.route('/api/projects/:projectId/overview', projectOverviewRoutes); + return hono; +} + +async function runningIds(s: Seeded): Promise { + // The D1 index is written on a debounce; flush it the way the timer would. + await runInDurableObject(s.project, async (instance) => { + await (instance as unknown as { runSummarySyncLocked(): Promise }).runSummarySyncLocked(); + }); + const response = await app().request( + `/api/projects/${s.projectId}/overview`, + { headers: { Cookie: s.ownerCookie } }, + testEnv, + executionCtx + ); + expect(response.status).toBe(200); + const body = (await response.json()) as ProjectOverviewResponse; + expect(body.unavailable).not.toContain('running'); + return body.running.items.map((chat) => chat.sessionId); +} + +/** The task as every chat past its first turn has it: the step latched at awaiting_followup. */ +async function latchFollowupStep(s: Seeded) { + await testEnv.DATABASE.prepare( + `UPDATE tasks SET execution_step = 'awaiting_followup' WHERE id = ?` + ) + .bind(s.taskId) + .run(); +} + +async function newAgentSession(project: DurableObjectStub, chatSessionId: string) { + const acp = await project.createAcpSession({ + chatSessionId, + initialPrompt: null, + agentType: 'claude-code', + }); + // ACP sessions order by creation time; keep a later one strictly later. + await new Promise((resolve) => setTimeout(resolve, 5)); + return acp.id; +} + +describe('Running now follows the agent activity mirror', () => { + it('lists a later-turn chat while its agent is prompting and drops it when the turn ends', async () => { + const s = await seed(); + await latchFollowupStep(s); + const acpId = await newAgentSession(s.project, s.chatSessionId); + + await s.project.reportActivity(acpId, 'prompting'); + expect(await runningIds(s)).toEqual([s.chatSessionId]); + + // Control: the same chat, turn over. It is awake and its task is in progress, but idle. + await s.project.reportActivity(acpId, 'idle'); + expect(await runningIds(s)).toEqual([]); + + // A recovering agent is still working. + await s.project.reportActivity(acpId, 'recovering'); + expect(await runningIds(s)).toEqual([s.chatSessionId]); + }); + + it('reads the newest agent session, as the chat view does: an older stuck row does not count', async () => { + const s = await seed(); + const older = await newAgentSession(s.project, s.chatSessionId); + await s.project.reportActivity(older, 'prompting'); + const newer = await newAgentSession(s.project, s.chatSessionId); + await s.project.reportActivity(newer, 'idle'); + expect(await runningIds(s)).toEqual([]); + + // Control: the newest session working lists the chat. + await s.project.reportActivity(newer, 'prompting'); + expect(await runningIds(s)).toEqual([s.chatSessionId]); + }); + + it('breaks a same-millisecond tie the way the chat view does, so both read the same session', async () => { + const s = await seed(); + for (const id of ['acp-tie-a', 'acp-tie-b']) { + await s.project.createAcpSession({ + chatSessionId: s.chatSessionId, + initialPrompt: null, + agentType: 'claude-code', + id, + }); + } + await runInDurableObject(s.project, async (_instance, state) => { + state.storage.sql.exec( + `UPDATE acp_sessions SET created_at = ? WHERE chat_session_id = ?`, + Date.now(), + s.chatSessionId + ); + }); + // The chat view's newest session (`resolveChatAgentState` reads `listAcpSessions`, limit 1). + const { sessions } = await s.project.listAcpSessions({ + chatSessionId: s.chatSessionId, + limit: 1, + }); + expect(sessions[0]?.id).toBe('acp-tie-b'); + + await s.project.reportActivity('acp-tie-a', 'prompting'); + await s.project.reportActivity('acp-tie-b', 'idle'); + expect(await runningIds(s)).toEqual([]); + // Control: the session both readers call newest is working. + await s.project.reportActivity('acp-tie-b', 'prompting'); + expect(await runningIds(s)).toEqual([s.chatSessionId]); + }); + + it('falls back to the chat-keyed row when the chat has no agent session yet', async () => { + const s = await seed(); + await s.project.reportActivity(s.chatSessionId, 'prompting'); + expect(await runningIds(s)).toEqual([s.chatSessionId]); + await s.project.reportActivity(s.chatSessionId, 'stopped'); + expect(await runningIds(s)).toEqual([]); + }); + + it('never lists a sleeping chat, whatever its last activity row says', async () => { + const s = await seed(); + const acpId = await newAgentSession(s.project, s.chatSessionId); + await s.project.reportActivity(acpId, 'prompting'); + expect(await runningIds(s)).toEqual([s.chatSessionId]); + + await runInDurableObject(s.project, async (_instance, state) => { + state.storage.sql.exec( + `UPDATE chat_sessions SET status = 'sleeping', updated_at = ? WHERE id = ?`, + Date.now(), + s.chatSessionId + ); + }); + expect(await s.project.listWorkingChatSessionIds()).toEqual([]); + expect(await runningIds(s)).toEqual([]); + }); +}); diff --git a/apps/web/src/pages/project-overview/BudgetsSection.tsx b/apps/web/src/pages/project-overview/BudgetsSection.tsx index 11f6a50d74..49ac505654 100644 --- a/apps/web/src/pages/project-overview/BudgetsSection.tsx +++ b/apps/web/src/pages/project-overview/BudgetsSection.tsx @@ -1,8 +1,11 @@ /** * Budgets: one usage ring per account the project's profiles run on (the approved ring, - * `ProfileUsageAvatar`). Calm accounts are just the ring; words appear only for exceptions, and - * they name the window in full ("5-hour window · 38% left") because this page is read out of - * the composer's context. + * `ProfileUsageAvatar`). Calm accounts are just the ring and the account's name; an account that + * needs attention carries one short status under its name ("6% left", "Out · 2d 4h", "Paused"), + * in the window's colour. The full words, which name the window ("Weekly window · 6% left · + * resets 2d 4h"), are the tile's tooltip and accessible name, because this page is read out of + * the composer's context. Raphaël (2026-11-20) found the earlier list of sentences under the + * rings too busy: it repeated every account's name a second time. * * The usage comes from `useProfileUsages`, the same model and cached reads the task box's own * ring uses, so this section adds no request and cannot disagree with the composer. @@ -16,8 +19,21 @@ import { usageSpoken, usageWords, } from '../../components/project-chat/profile-picker'; +import { + healthColor, + USAGE_HEALTH, +} from '../../components/project-chat/profile-picker/usage-windows'; import { Section, SectionHead, SectionNote } from './sections'; +export interface BudgetStatus { + /** What the tile shows: "6% left", "Out · 2d 4h", "Paused". */ + text: string; + /** Null: neutral text. A colour: the window's health. */ + color: string | null; + /** The same in full words, naming the window: the tooltip and the accessible name. */ + detail: string; +} + export interface BudgetAccount { key: string; label: string; @@ -25,31 +41,61 @@ export interface BudgetAccount { first: AgentProfile; profiles: AgentProfile[]; usage: ProfileUsage; + /** Null while the account is calm. */ + status: BudgetStatus | null; } -export interface BudgetException { - key: string; - text: string; - /** Null: neutral text. A colour: the window's health. */ - color: string | null; +/** The one short status a tile shows, or null for a calm account. */ +export function budgetStatus(usage: ProfileUsage): BudgetStatus | null { + if (usage.state === 'paused') { + return { text: 'Paused', color: null, detail: 'Paused' }; + } + const words = usageWords(usage, { namedWindows: true }); + if (words.length === 0) return null; + const detail = words.map((word) => word.text).join(' · '); + if (usage.state === 'out') { + return { text: usage.resetIn ? `Out · ${usage.resetIn}` : 'Out', color: usage.color, detail }; + } + // The number and its colour come from one window: the tightest of those the words show (the + // same "half left" bar, `USAGE_HEALTH.calm`). A low session alone stays neutral, as in the + // composer; the week carries its health colour. + const shown = [ + { reading: usage.session, color: null }, + { reading: usage.week, color: usage.week ? healthColor(usage.week.left) : null }, + ].flatMap(({ reading, color }) => + reading && reading.left !== null && reading.left <= USAGE_HEALTH.calm + ? [{ left: reading.left, color }] + : [] + ); + const tightest = shown.reduce<(typeof shown)[number] | undefined>( + (best, next) => (!best || next.left <= best.left ? next : best), + undefined + ); + if (tightest) return { text: `${tightest.left}% left`, color: tightest.color, detail }; + // No session or week window explains it: the words name the account's own reading. + return { + text: usage.left === null ? 'Low' : `${usage.left}% left`, + color: words[0]?.color ?? null, + detail, + }; } /** * Group profiles by the account they run on. The platform is one account; profiles whose usage - * is unknown (still loading, or a provider without readings) and those with no account are - * left out of the rings, and a profile with no account becomes an exception instead. + * is unknown (still loading, or a provider without readings) are left out of the rings, and the + * names of profiles with no account connected are returned for one line under them. */ export function budgetAccounts( profiles: readonly AgentProfile[], usages: ReadonlyMap -): { accounts: BudgetAccount[]; exceptions: BudgetException[] } { +): { accounts: BudgetAccount[]; noAccount: string[] } { const byKey = new Map(); - const noAccount: AgentProfile[] = []; + const noAccount: string[] = []; for (const profile of profiles) { const usage = usages.get(profile.id); if (!usage) continue; if (usage.state === 'none') { - noAccount.push(profile); + noAccount.push(profile.name); continue; } const key = @@ -70,37 +116,27 @@ export function budgetAccounts( first: profile, profiles: [profile], usage, + status: budgetStatus(usage), }); } const accounts = [...byKey.values()].sort((a, b) => a.label.localeCompare(b.label)); - const exceptions: BudgetException[] = []; - for (const account of accounts) { - if (account.usage.state === 'paused') { - exceptions.push({ key: account.key, text: `${account.label} is paused`, color: null }); - continue; - } - for (const [index, word] of usageWords(account.usage, { namedWindows: true }).entries()) { - exceptions.push({ - key: `${account.key}:${index}`, - text: `${account.label}: ${word.text}`, - color: word.color, - }); - } - } - if (noAccount.length > 0) { - const names = noAccount.map((profile) => profile.name).join(', '); - exceptions.push({ - key: 'no-account', - text: `No account connected for ${names}`, - color: null, - }); - } - return { accounts, exceptions }; + return { accounts, noAccount }; } -/** What a screen reader hears for a tile: the account, what is left, and who uses it. */ +/** + * What a screen reader hears for a tile: the account, the status it shows, the full words when + * they say more, and who uses it. The visible status is always part of the name (WCAG 2.5.3), so + * "Out · 2d 4h" can be spoken to select the tile. + */ export function budgetTileLabel(account: BudgetAccount): string { - const left = account.usage.state === 'platform' ? null : usageSpoken(account.usage); + const status = account.status; + const left = status + ? status.detail.includes(status.text) + ? status.detail + : `${status.text}, ${status.detail}` + : account.usage.state === 'platform' + ? null + : usageSpoken(account.usage); const users = account.profiles.map((profile) => profile.name).join(', '); return [account.label, left, `used by ${users}`].filter(Boolean).join(', '); } @@ -118,34 +154,41 @@ export function BudgetsSection({ className?: string; }) { const accountsPage = `/projects/${projectId}/settings/accounts`; - const { accounts, exceptions } = usages + const { accounts, noAccount } = usages ? budgetAccounts(profiles, usages) - : { accounts: [], exceptions: [] }; + : { accounts: [], noAccount: [] }; return (
{accounts.length > 0 ? (
    {accounts.map((account) => (
  • - - + + {/* One line, ellipsised: the full name is the tile's tooltip and accessible name. */} + {account.label} - - {account.profiles.length === 1 - ? account.first.name - : `${account.profiles.length} profiles`} - + {account.status && ( + + {account.status.text} + + )}
  • ))} @@ -159,21 +202,13 @@ export function BudgetsSection({ : 'No account usage to show.'} )} - {exceptions.length > 0 && ( -
      0 && ( +

      - {exceptions.map((exception) => ( -

    • - {exception.text} -
    • - ))} -
    + No account connected for {noAccount.join(', ')} +

    )}
); diff --git a/apps/web/src/pages/project-overview/sections.tsx b/apps/web/src/pages/project-overview/sections.tsx index 6152ccf14b..f14ea77696 100644 --- a/apps/web/src/pages/project-overview/sections.tsx +++ b/apps/web/src/pages/project-overview/sections.tsx @@ -92,6 +92,16 @@ export function Section({ ); } +/** + * One row of a rail list (Running now, Recently): an icon, a one-line title and a muted line + * under it. One line each keeps six running chats and six recent items to a glance; the full + * title is the row's tooltip and opens with the row. + */ +const ROW_CLASS = + 'flex min-h-11 min-w-0 items-start gap-2.5 rounded-lg px-2 py-1.5 no-underline hover:bg-surface-hover'; +const ROW_TITLE_CLASS = + 'line-clamp-1 text-[14px] font-medium leading-snug text-fg-primary [overflow-wrap:anywhere]'; + /** Muted one-liner for an empty or unavailable section. */ export function SectionNote({ children }: { children: ReactNode }) { return

{children}

; @@ -181,16 +191,15 @@ export function RunningRow({
  • - - {title} - + {title} @@ -284,16 +293,15 @@ function RecentIdeaRow({ item, projectId }: { item: IdeaListItem; projectId: str
  • - - {item.title} - + {item.title} {IDEA_STATE_LABELS[item.derived.state]}. {item.derived.state === 'working' && ( @@ -317,14 +325,15 @@ function MergedPullRequestRow({ pr }: { pr: OverviewMergedPullRequest }) { href={pr.url} target="_blank" rel="noreferrer" - className="flex min-h-12 min-w-0 items-start gap-3 rounded-lg px-2 py-2 no-underline hover:bg-surface-hover" + className={ROW_CLASS} + title={pr.title?.trim() || undefined} data-testid="overview-merged-pr" > - + {pr.title?.trim() || `Pull request #${pr.number}`} diff --git a/apps/web/tests/playwright/project-overview-audit.spec.ts b/apps/web/tests/playwright/project-overview-audit.spec.ts index 30147494cb..a9db43bc62 100644 --- a/apps/web/tests/playwright/project-overview-audit.spec.ts +++ b/apps/web/tests/playwright/project-overview-audit.spec.ts @@ -24,12 +24,7 @@ import type { import { accountRows, mergeRows } from '../unit/components/accounts/fixtures'; import { acmeBillingProject, acmeBillingUser } from './acme-billing-fixtures'; -import { - assertNoClippedOverflow, - assertNoOverflow, - screenshot, - seedTheme, -} from './audit-helpers'; +import { assertNoClippedOverflow, assertNoOverflow, screenshot, seedTheme } from './audit-helpers'; import { RUNS, SCHEDULES, TRIGGERS } from './automation-fixtures'; import { docsShot } from './docs-shot'; import { KIND_ITEMS, MANY_ITEMS } from './inbox-fixtures'; @@ -146,9 +141,65 @@ function usage( }; } -type Budget = 'healthy' | 'normal' | 'stressed'; +type Budget = 'healthy' | 'normal' | 'stressed' | 'many'; + +/** + * Eight accounts, each with its own profile pinned to it, at the spread Raphaël's own project had + * on 2026-11-20: three calm, the rest low on a 5-hour or weekly window, one with a long name. + * Each entry: [id, name, 5-hour used %, week used %]. + */ +const MANY_ACCOUNTS: Array<[string, string, number, number]> = [ + ['agy', 'AGY Prod', 10, 20], + ['ec', 'EC Claude', 15, 30], + ['billing', 'OpenAI Codex account for the billing team', 20, 35], + ['opencode', 'OpenCode API key', 30, 98], + ['samc', 'SAM Claude', 40, 69], + ['samsam', 'Sam Sam', 20, 87], + ['social', 'Sam Social', 30, 92], + ['support', 'Sam Support', 55, 82], +]; +const MANY_PROFILES = MANY_ACCOUNTS.map(([id, name]) => + profile(`p-${id}`, `${name} profile`, 'claude-code', 'claude-opus-5-5') +); +const MANY_ROWS = mergeRows( + ...MANY_ACCOUNTS.map(([id, name]) => + accountRows({ + id, + name, + kind: 'agent', + target: 'claude-code', + credentialKind: 'oauth-token', + }) + ) +); +const MANY_PINS = MANY_ACCOUNTS.map(([id, name]) => ({ + id: `pin-${id}`, + configurationId: `cfg-${id}`, + agentProfileId: `p-${id}`, + profileName: `${name} profile`, + projectId: PROJECT_ID, + projectName: 'Acme billing', + consumerKind: 'agent', + consumerTarget: 'claude-code', + isActive: true, + createdAt: '2026-10-01T00:00:00Z', + updatedAt: '2026-10-01T00:00:00Z', +})); +const levelFor = (used: number): CredentialLimitLevel => + used >= 90 ? 'critical' : used >= 75 ? 'warning' : 'ok'; function limits(kind: Budget, now: number) { + if (kind === 'many') { + return [ + ...limits('normal', now), + ...MANY_ACCOUNTS.map(([id, , session, week]) => + usage(`cred-${id}`, 'claude-code', [ + limitWindow('claude.five_hour', session, levelFor(session), 2 * HOUR, now), + limitWindow('claude.seven_day', week, levelFor(week), (50 + session) * HOUR, now), + ]) + ), + ]; + } const claude = kind === 'stressed' ? [ @@ -382,12 +433,15 @@ async function setupScene(page: Page, options: SceneOptions) { route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) }); if (path.includes('/api/auth/')) return respond(200, MOCK_USER); + const many = options.budget === 'many'; + const rows = many ? mergeRows(ROWS, MANY_ROWS) : ROWS; if (path === '/api/cc/credentials') - return respond(200, { credentials: options.brandNew ? [] : ROWS.credentials }); + return respond(200, { credentials: options.brandNew ? [] : rows.credentials }); if (path === '/api/cc/configurations') - return respond(200, { configurations: ROWS.configurations }); - if (path === '/api/cc/attachments') return respond(200, { attachments: ROWS.attachments }); - if (path === '/api/cc/profile-attachments') return respond(200, { attachments: [] }); + return respond(200, { configurations: rows.configurations }); + if (path === '/api/cc/attachments') return respond(200, { attachments: rows.attachments }); + if (path === '/api/cc/profile-attachments') + return respond(200, { attachments: many ? MANY_PINS : [] }); if (path === '/api/credentials/resolution-status') return respond(200, { consumers: [] }); if (path === '/api/credentials/limits') return respond(200, { @@ -484,7 +538,13 @@ async function setupScene(page: Page, options: SceneOptions) { ) ); if (sub === '/agent-profiles') - return respond(200, { items: options.brandNew ? [] : PROFILES }); + return respond(200, { + items: options.brandNew + ? [] + : options.budget === 'many' + ? [...PROFILES, ...MANY_PROFILES] + : PROFILES, + }); if (sub === '/agent-profiles/picker') return respond(200, { usageWindowDays: 30, usage: [], hiddenProfileIds: [] }); if (sub === '/skills') return respond(200, { items: [] }); @@ -589,7 +649,10 @@ test.describe('Project Overview', () => { // The inbox's own phrase: its item is in Needs you. await expect(running.getByText('Paused on this')).toBeVisible(); await expect(page.getByTestId('overview-budgets')).toBeVisible(); - await expect(page.getByTestId('overview-budget-exceptions')).toContainText('5-hour window'); + // The low 5-hour window is the tile's own short status; the full words are its name. + const personal = page.getByTestId('overview-budget-tile').filter({ hasText: 'Personal Max' }); + await expect(personal.getByTestId('overview-budget-status')).toHaveText('38% left'); + await expect(personal).toHaveAttribute('aria-label', /5-hour window · 38% left/); await expect(page.getByTestId('overview-automation-failing')).toBeVisible(); await expect(page.getByTestId('overview-recent-ideas')).toBeVisible(); const week = page.getByRole('region', { name: 'This week' }); @@ -623,9 +686,9 @@ test.describe('Project Overview', () => { await expect( running.getByRole('link', { name: /7 more running\s?· 2 waiting on you/ }) ).toBeVisible(); - await expect(page.getByTestId('overview-budget-exceptions')).toContainText( - 'Weekly window · 6% left' - ); + const personal = page.getByTestId('overview-budget-tile').filter({ hasText: 'Personal Max' }); + await expect(personal.getByTestId('overview-budget-status')).toHaveText('6% left'); + await expect(personal).toHaveAttribute('aria-label', /Weekly window · 6% left/); await expect( page.getByTestId('overview-automation-failing').getByTestId('automation-attention-line') ).toHaveCount(2); @@ -644,10 +707,52 @@ test.describe('Project Overview', () => { ); // Healthy accounts get rings and no words. await expect(page.getByTestId('overview-budgets')).toBeVisible(); - await expect(page.getByTestId('overview-budget-exceptions')).toHaveCount(0); + await expect(page.getByTestId('overview-budget-tile')).toHaveCount(2); + await expect(page.getByTestId('overview-budget-status')).toHaveCount(0); await capture(page, 'overview-quiet'); }); + test('many accounts: one short status per tile, no sentence list under the rings', async ({ + page, + }) => { + await setupScene(page, { scene: 'normal', budget: 'many', automations: 'normal' }); + await page.goto(BASE); + const budgets = page.getByRole('region', { name: 'Budgets' }); + // Two default accounts plus the eight pinned ones. + await expect(budgets.getByTestId('overview-budget-tile')).toHaveCount(10); + const tile = (name: string) => + budgets.getByTestId('overview-budget-tile').filter({ hasText: name }); + await expect(tile('OpenCode API key').getByTestId('overview-budget-status')).toHaveText( + '2% left' + ); + await expect(tile('AGY Prod').getByTestId('overview-budget-status')).toHaveCount(0); + // The account's name appears once in the pane: no second line of sentences naming it again. + await expect(budgets.getByText('Sam Social')).toHaveCount(1); + // Every tile is inside the pane, and the pane holds ten accounts in at most three rows. + const pane = await budgets.boundingBox(); + const tiles = await budgets + .getByTestId('overview-budget-tile') + .evaluateAll((nodes) => nodes.map((node) => node.getBoundingClientRect().top)); + expect(new Set(tiles.map((top) => Math.round(top))).size).toBeLessThanOrEqual(3); + for (const box of await budgets.getByTestId('overview-budget-tile').all()) { + const b = await box.boundingBox(); + expect(b!.x).toBeGreaterThanOrEqual(pane!.x); + expect(b!.x + b!.width).toBeLessThanOrEqual(pane!.x + pane!.width + 1); + } + await budgets.scrollIntoViewIfNeeded(); + await capture(page, 'overview-many-accounts'); + }); + + test('many accounts, light theme: the status colours stay readable', async ({ page }) => { + await seedTheme(page, 'light'); + await setupScene(page, { scene: 'normal', budget: 'many', automations: 'normal' }); + await page.goto(BASE); + const budgets = page.getByRole('region', { name: 'Budgets' }); + await expect(budgets.getByTestId('overview-budget-status').first()).toBeVisible(); + await budgets.scrollIntoViewIfNeeded(); + await capture(page, 'overview-many-accounts-light'); + }); + test('sending a task keeps you on the page', async ({ page }, testInfo) => { await setupScene(page, { scene: 'normal', diff --git a/apps/web/tests/unit/pages/project-overview-budgets.test.ts b/apps/web/tests/unit/pages/project-overview-budgets.test.ts index 999737c7bd..f1a2d02706 100644 --- a/apps/web/tests/unit/pages/project-overview-budgets.test.ts +++ b/apps/web/tests/unit/pages/project-overview-budgets.test.ts @@ -7,7 +7,10 @@ import { usageWords, } from '../../../src/components/project-chat/profile-picker/usage'; import type { UsageWindowReading } from '../../../src/components/project-chat/profile-picker/usage-windows'; -import { budgetAccounts } from '../../../src/pages/project-overview/BudgetsSection'; +import { + budgetAccounts, + budgetTileLabel, +} from '../../../src/pages/project-overview/BudgetsSection'; function reading( label: string, @@ -86,29 +89,34 @@ describe('budgetAccounts', () => { ['b', usage({})], ['c', usage({ accountLabel: 'Work Pro', accountKey: 'cc:work', accountId: 'cfg-work' })], ]); - const { accounts, exceptions } = budgetAccounts(profiles, usages); + const { accounts, noAccount } = budgetAccounts(profiles, usages); expect(accounts.map((a) => [a.label, a.profiles.map((p) => p.name)])).toEqual([ ['Personal Max', ['Opus Build', 'Sonnet Chat']], ['Work Pro', ['Codex']], ]); - expect(exceptions).toEqual([]); + // Calm accounts carry no status: just the ring and the name. + expect(accounts.map((a) => a.status)).toEqual([null, null]); + expect(noAccount).toEqual([]); }); - it('puts words only on exceptions: a low window named in full, a paused account, no account', () => { + it('gives each exception one short status on its own tile, with the full words as its detail', () => { const profiles = [ profile('a', 'Opus Build'), profile('b', 'Codex'), profile('c', 'Kimi'), profile('d', 'Gemma'), + profile('e', 'Sonnet'), ]; const usages = new Map([ [ 'a', usage({ state: 'out', - left: 6, + left: 0, + color: 'red', + resetIn: '2d 4h', session: reading('5h', 60), - week: reading('Week', 6, '2d 4h'), + week: reading('Week', 0, '2d 4h'), urgent: true, }), ], @@ -123,14 +131,81 @@ describe('budgetAccounts', () => { ], ['c', usage({ state: 'none', accountLabel: null, accountKey: null, accountId: null })], ['d', usage({ state: 'platform', accountLabel: null, accountKey: null, accountId: null })], + [ + 'e', + usage({ + state: 'low', + left: 13, + accountLabel: 'Team Max', + accountKey: 'cc:team', + accountId: 'cfg-team', + session: reading('5h', 70), + week: reading('Week', 13, '2d 5h'), + }), + ], ]); - const { accounts, exceptions } = budgetAccounts(profiles, usages); - expect(accounts.map((a) => a.label)).toEqual(['Personal Max', 'SAM platform', 'Work Pro']); - expect(exceptions.map((e) => e.text)).toEqual([ - 'Personal Max: Weekly window · 6% left · resets 2d 4h', - 'Work Pro is paused', - 'No account connected for Kimi', + const { accounts, noAccount } = budgetAccounts(profiles, usages); + expect(accounts.map((a) => [a.label, a.status?.text ?? null])).toEqual([ + ['Personal Max', 'Out · 2d 4h'], + ['SAM platform', null], + ['Team Max', '13% left'], + ['Work Pro', 'Paused'], ]); + const team = accounts.find((a) => a.label === 'Team Max')!; + // The week's health colours the short status; the detail names the window in full. + expect(team.status?.color).not.toBeNull(); + expect(team.status?.detail).toBe('Weekly window · 13% left · resets 2d 5h'); + expect(budgetTileLabel(team)).toBe( + 'Team Max, Weekly window · 13% left · resets 2d 5h, used by Sonnet' + ); + const personal = accounts.find((a) => a.label === 'Personal Max')!; + expect(personal.status?.detail).toBe('Weekly window used up · back in 2d 4h'); + // The visible status is part of the accessible name (WCAG 2.5.3, label in name). + expect(budgetTileLabel(personal)).toBe( + 'Personal Max, Out · 2d 4h, Weekly window used up · back in 2d 4h, used by Opus Build' + ); + for (const account of accounts) { + if (account.status) expect(budgetTileLabel(account)).toContain(account.status.text); + } + expect(noAccount).toEqual(['Kimi']); + }); + + it('takes the number and its colour from the same window: a tighter session stays neutral', () => { + const { accounts } = budgetAccounts( + [profile('a', 'Opus Build')], + new Map([ + [ + 'a', + usage({ + state: 'low', + left: 4, + color: 'amber', + session: reading('5h', 4), + week: reading('Week', 40), + }), + ], + ]) + ); + // 4% is the session's; the week's amber must not paint it. + expect(accounts[0]?.status?.text).toBe('4% left'); + expect(accounts[0]?.status?.color).toBeNull(); + }); + + it('keeps a low session alone neutral: only the week carries a colour', () => { + const { accounts } = budgetAccounts( + [profile('a', 'Opus Build')], + new Map([ + [ + 'a', + usage({ state: 'low', left: 38, session: reading('5h', 38), week: reading('Week', 70) }), + ], + ]) + ); + expect(accounts[0]?.status).toEqual({ + text: '38% left', + color: null, + detail: '5-hour window · 38% left · resets 1h 20m', + }); }); it('leaves out profiles whose usage has not loaded', () => { diff --git a/apps/www/public/images/docs/project-overview-mobile.png b/apps/www/public/images/docs/project-overview-mobile.png index eb0844c24a..7f0f0c0417 100644 Binary files a/apps/www/public/images/docs/project-overview-mobile.png and b/apps/www/public/images/docs/project-overview-mobile.png differ diff --git a/apps/www/public/images/docs/project-overview.png b/apps/www/public/images/docs/project-overview.png index 9ebbdfb828..3b63fe927b 100644 Binary files a/apps/www/public/images/docs/project-overview.png and b/apps/www/public/images/docs/project-overview.png differ diff --git a/apps/www/src/content/docs/docs/guides/project-overview.md b/apps/www/src/content/docs/docs/guides/project-overview.md index 53a382d26c..11ced58d4f 100644 --- a/apps/www/src/content/docs/docs/guides/project-overview.md +++ b/apps/www/src/content/docs/docs/guides/project-overview.md @@ -69,8 +69,10 @@ waiting, the section is a single line, **Nothing needs you.** ### Running now -Chats in this project that an agent is working on now. Each row shows the chat's topic, then how -long it has been running and the profile it runs with, for example **1h 20m · Opus 5.5 Build**. +Chats in this project that an agent is working on now: the agent is in the middle of a turn, as +the chat itself shows it. Each row shows the chat's topic on one line (hover it for the whole +topic), then how long it has been running and the profile it runs with, for example +**1h 20m · Opus 5.5 Build**. - **Starting** means SAM is still finding or preparing a machine for it. - **Paused on this** (amber) means the agent is stopped on something you need to answer, which is @@ -97,12 +99,14 @@ work. **Insights** opens the full ### Budgets -One ring per account your project's profiles run on: the ring is the usage left on that account, -the same ring the profile picker shows. Calm accounts are just a ring. Words appear only when -something needs your attention, and they name the window, for example -**Personal Max: Weekly window · 6% left · resets 2d 3h**, an account that is paused, or a profile -with no account connected. **Accounts** opens the project's **Settings → Accounts**, where you connect and switch them. See -[Usage limits](/docs/guides/agents/#usage-limits). +One ring per account your project's profiles run on, with the account's name under it: the ring is +the usage left on that account, the same ring the profile picker shows. Calm accounts are just a +ring and a name. An account that needs your attention adds one short line under its name, in the +window's colour: how much is left (**6% left**), **Out** with when it is back, or **Paused**. Hover +a ring, or listen to it with a screen reader, for the full words, which name the window, for +example **Weekly window · 6% left · resets 2d 3h**. A profile with no account connected is named on +one line under the rings. **Accounts** opens the project's **Settings → Accounts**, where you +connect and switch them. See [Usage limits](/docs/guides/agents/#usage-limits). ### Automations diff --git a/packages/operations/src/project-brief-facts.ts b/packages/operations/src/project-brief-facts.ts index d19d0f3682..0d771298a9 100644 --- a/packages/operations/src/project-brief-facts.ts +++ b/packages/operations/src/project-brief-facts.ts @@ -224,7 +224,9 @@ function accountLabel(source: 'project' | 'platform', provider: string): string export async function readBriefFacts( db: D1Database, projectId: string, - now: number + now: number, + /** Chats whose agent is mid-turn (ProjectData `listWorkingChatSessionIds`). */ + workingSessionIds: readonly string[] ): Promise { const limit = BRIEF_FACT_ROWS_MAX; const recentCutoff = new Date(now - BRIEF_RECENT_WINDOW_MS).toISOString(); @@ -240,7 +242,7 @@ export async function readBriefFacts( const [asks, running, failed, automations, accounts, pulls, ideas] = await Promise.all([ all(BRIEF_ASKS_SQL, projectId, now, over), // A viewer id that matches nobody: the facts are the same for every member. - readRunningChats(db, projectId, '', limit), + readRunningChats(db, projectId, '', limit, workingSessionIds), all(BRIEF_FAILED_CHATS_SQL, projectId, datePrefix(failedCutoff), failedCutoff, over), all(BRIEF_FAILING_AUTOMATIONS_SQL, projectId, over), all(BRIEF_ACCOUNTS_SQL, projectId, now), diff --git a/packages/operations/src/project-brief-read.ts b/packages/operations/src/project-brief-read.ts index fb95739f84..ccf9be8125 100644 --- a/packages/operations/src/project-brief-read.ts +++ b/packages/operations/src/project-brief-read.ts @@ -21,7 +21,11 @@ import { BRIEF_ASK_VISIBLE_SQL, BRIEF_AUTOMATION_FAILING_SQL, } from './project-brief-sql'; -import { overviewChatRunningSql, overviewPausedSessionsSql } from './project-overview-statuses'; +import { + OVERVIEW_WORKING_SESSIONS_SQL, + overviewChatRunningSql, + overviewPausedSessionsSql, +} from './project-overview-statuses'; /** At most this many sentences are stored, and so shown (three on desktop, two on a phone). */ export const BRIEF_MAX_SENTENCES = 3; @@ -59,8 +63,9 @@ const refs = (column: string) => * a shared account near its limit (`BRIEF_ACCOUNT_LIVE_SQL`). Every subquery binds the row's own * `project_id`, so a ref can never resolve another project's item (rule 11). A chat named as * running must still pass Running now's own rule (`overviewChatRunningSql`), and an automation - * named as failing must still be failing (`BRIEF_AUTOMATION_FAILING_SQL`). Binds `now` four times - * (asks; the paused-chat sets twice; accounts), then the project. + * named as failing must still be failing (`BRIEF_AUTOMATION_FAILING_SQL`). Binds, in order: `now` + * three times (asks; the paused-chat sets twice), the mid-turn chat ids as JSON, `now` (accounts), + * then the project. */ const BRIEF_SQL = ` SELECT b.brief_json, b.generated_at, b.stale, b.pending_since, b.last_error_at, @@ -70,7 +75,10 @@ const BRIEF_SQL = ` (SELECT json_group_array(ss.id) FROM session_summaries ss JOIN tasks t ON t.id = ss.task_id AND t.project_id = ss.project_id WHERE ss.project_id = b.project_id - AND ${overviewChatRunningSql(overviewPausedSessionsSql('b.project_id'))} + AND ${overviewChatRunningSql( + overviewPausedSessionsSql('b.project_id'), + OVERVIEW_WORKING_SESSIONS_SQL + )} AND ss.id IN (SELECT value FROM ${refs('ref_chats_json')})) AS running_chats, (SELECT json_group_array(t.id) FROM triggers t WHERE t.project_id = b.project_id AND ${BRIEF_AUTOMATION_FAILING_SQL} @@ -128,11 +136,13 @@ function withOpaqueAccountIds(sentence: OverviewBriefSentence): OverviewBriefSen export async function readProjectBrief( db: D1Database, projectId: string, - now: number + now: number, + /** Chats whose agent is mid-turn (`listWorkingChatSessionIds`), for Running now's rule. */ + workingSessionIds: readonly string[] ): Promise { const raw = await db .prepare(BRIEF_SQL) - .bind(now, now, now, now, projectId) + .bind(now, now, now, JSON.stringify(workingSessionIds), now, projectId) .first>(); if (!raw) return null; const row = v.safeParse(RowSchema, raw); diff --git a/packages/operations/src/project-data-port.ts b/packages/operations/src/project-data-port.ts index b6eb4599c2..dcc91bc20c 100644 --- a/packages/operations/src/project-data-port.ts +++ b/packages/operations/src/project-data-port.ts @@ -161,6 +161,8 @@ export interface OperationProjectDataPort { resolveTranscriptOwner(projectId: string, sessionId: string): Promise; getMailboxMessage(projectId: string, messageId: string): Promise; listActiveAttentionMarkers(projectId: string, sessionId: string): Promise; + /** Awake chats whose agent is mid-turn (`project-data/do/session-state-read.ts`). */ + listWorkingChatSessionIds(projectId: string): Promise; /** One chat's run-receipt facts for a window (`project-data/do/run-receipt-facts.ts`). */ getRunReceiptFacts(projectId: string, input: RunReceiptFactsInput): Promise; /** Human follow-ups per run window (`project-data/do/run-nudges.ts`). */ diff --git a/packages/operations/src/project-overview-statuses.ts b/packages/operations/src/project-overview-statuses.ts index 7f396cc201..5029f1aa5d 100644 --- a/packages/operations/src/project-overview-statuses.ts +++ b/packages/operations/src/project-overview-statuses.ts @@ -31,21 +31,35 @@ export function overviewPausedSessionsSql(projectSql: string): string { AND requesting_chat_session_id IS NOT NULL`; } +/** + * The chats whose agent is mid-turn, bound as one JSON array parameter (the ids come from the + * ProjectData object, `listWorkingChatSessionIds`). One bind whatever the count, so a busy + * project cannot reach D1's bound-parameter limit. + */ +export const OVERVIEW_WORKING_SESSIONS_SQL = 'SELECT value AS session_id FROM json_each(?)'; + /** * A chat is running (Running now's own rule, over `ss` = session_summaries and `t` = its task): * awake, its task in a running status, and either still being placed, paused on a person - * (`pausedSessionsSql` selects those chats' ids), or mid-turn (`agent_completed_at IS NULL`, - * not awaiting a follow-up). The Overview read and the brief's re-check share it, so a chat the - * page no longer lists can never be called running by the brief. + * (`pausedSessionsSql` selects those chats' ids), or mid-turn (`workingSessionsSql` selects the + * chats whose agent the ProjectData activity mirror says is working). The Overview read and the + * brief's re-check share it, so a chat the page no longer lists can never be called running by + * the brief. + * + * Mid-turn is read from the activity mirror, not from D1: `tasks.execution_step` latches at + * `awaiting_followup` after a chat's first turn and `agent_completed_at` is never written, so a + * predicate on those columns listed only chats still on their first turn (rule 74). */ -export function overviewChatRunningSql(pausedSessionsSql: string): string { +export function overviewChatRunningSql( + pausedSessionsSql: string, + workingSessionsSql: string +): string { return `(ss.status = 'active' AND t.status IN (${sqlList(OVERVIEW_RUNNING_TASK_STATUSES)}) AND ( t.status IN (${sqlList(OVERVIEW_STARTING_TASK_STATUSES)}) OR ss.attention_json IS NOT NULL OR ss.id IN (${pausedSessionsSql}) - OR (ss.agent_completed_at IS NULL - AND (t.execution_step IS NULL OR t.execution_step <> 'awaiting_followup')) + OR ss.id IN (${workingSessionsSql}) ))`; } diff --git a/packages/operations/src/project-overview.ts b/packages/operations/src/project-overview.ts index 52d79b217d..e4d2a1f412 100644 --- a/packages/operations/src/project-overview.ts +++ b/packages/operations/src/project-overview.ts @@ -7,10 +7,11 @@ * those models and their cached reads rather than restating the rules on the server. * * Round trips: authorization (1, the access port's membership read), then in parallel the - * running query (1), the merged pull requests (1) and the recent ideas - * (`listRecentIdeasWithDerivedStatus`: rows, repository, the ProjectData snapshot, and up to four - * evidence reads, so at most 7), and the brief (1: its stored row and which of the items it names - * are still open, one statement; settings are cached per isolate). About 11, within the 20 a + * running query (2: the ProjectData read of which chats are mid-turn, then one statement), the + * merged pull requests (1) and the recent ideas (`listRecentIdeasWithDerivedStatus`: rows, + * repository, the ProjectData snapshot, and up to four evidence reads, so at most 7), and the + * brief (1: its stored row and which of the items it names are still open, one statement; it + * shares the running query's ProjectData read; settings are cached per isolate). About 12, within the 20 a * dashboard read may spend (`.claude/rules/60`). The brief is only read here: making one runs * after the response, in the background (`refreshProjectBriefIfDue`, apps/api). */ @@ -34,6 +35,7 @@ import { getProjectBriefSettings } from './project-brief-settings'; import { OVERVIEW_RUNNING_TASK_STATUSES, OVERVIEW_STARTING_TASK_STATUSES, + OVERVIEW_WORKING_SESSIONS_SQL, overviewChatRunningSql, overviewPausedSessionsSql, } from './project-overview-statuses'; @@ -65,21 +67,24 @@ const WAITING_ON_VIEWER_SQL = `(CASE WHEN ${PAUSED_ON_PERSON_SQL} AND ss.created /** * Awake chats (`session_summaries.status = 'active'`, the D1 index the DO keeps in sync) whose - * task is in a running status, and that are either still being placed, mid-turn - * (`agent_completed_at IS NULL`, the same rule the chat list uses for "idle"), or paused on an - * open question. The task join carries `project_id` so a task id cannot reach across projects - * (rule 11), and a profile name is shown only for this project's profiles or the task creator's - * own global ones, so a hint naming someone else's global profile reveals nothing. `COUNT(*) OVER ()` gives the total without a second round trip. - * `paused_sessions` reads this project's open, unexpired question asks (`idx_asks_open_question`) - * and its pending, unexpired secret requests (`idx_runtime_secret_requests_status_expires`; few are - * ever pending) once, both bound to the project like every other predicate here. + * task is in a running status, and that are either still being placed, mid-turn (the ids in + * `working_sessions`, read from the ProjectData activity mirror), or paused on an open question. + * The task join carries `project_id` so a task id cannot reach across projects (rule 11), and a + * profile name is shown only for this project's profiles or the task creator's own global ones, + * so a hint naming someone else's global profile reveals nothing. `COUNT(*) OVER ()` gives the + * total without a second round trip. `paused_sessions` reads this project's open, unexpired + * question asks (`idx_asks_open_question`) and its pending, unexpired secret requests + * (`idx_runtime_secret_requests_status_expires`; few are ever pending) once, both bound to the + * project like every other predicate here. */ const RUNNING_SQL = ` WITH paused_sessions AS ( ${overviewPausedSessionsSql('?')} + ), working_sessions AS ( + ${OVERVIEW_WORKING_SESSIONS_SQL} ) SELECT ss.id, ss.task_id, ss.topic, ss.started_at, ss.created_at, ss.last_message_at, - ss.agent_completed_at, ss.created_by_user_id, + ss.created_by_user_id, CASE WHEN ${PAUSED_ON_PERSON_SQL} THEN 1 ELSE 0 END AS has_attention, t.status AS task_status, t.agent_profile_hint, ap.name AS profile_name, @@ -91,7 +96,10 @@ const RUNNING_SQL = ` ON ap.id = t.agent_profile_hint AND (ap.project_id = ss.project_id OR (ap.project_id IS NULL AND ap.user_id = t.user_id)) WHERE ss.project_id = ? - AND ${overviewChatRunningSql('SELECT session_id FROM paused_sessions')} + AND ${overviewChatRunningSql( + 'SELECT session_id FROM paused_sessions', + 'SELECT session_id FROM working_sessions' + )} ORDER BY ${WAITING_ON_VIEWER_SQL} DESC, COALESCE(ss.last_message_at, ss.created_at, ss.started_at) DESC, ss.id DESC LIMIT ?`; @@ -112,7 +120,6 @@ const RunningRowSchema = v.object({ started_at: v.number(), created_at: v.nullable(v.number()), last_message_at: v.nullable(v.number()), - agent_completed_at: v.nullable(v.number()), created_by_user_id: v.nullable(v.string()), has_attention: v.number(), task_status: v.picklist(OVERVIEW_RUNNING_TASK_STATUSES), @@ -168,20 +175,32 @@ function toRunningChat( /** * Running now for one viewer. `viewerId` only decides which rows are "waiting on the viewer" (and * ranks them first); pass an id that matches nobody for a viewer-neutral read, as the brief's - * facts do (`project-brief-facts.ts`). + * facts do (`project-brief-facts.ts`). `workingSessionIds` are the chats whose agent is mid-turn, + * from the ProjectData object (`listWorkingChatSessionIds`). */ export async function readRunningChats( db: D1Database, projectId: string, viewerId: string, - limit: number + limit: number, + workingSessionIds: readonly string[] ): Promise { const now = Date.now(); const result = await db .prepare(RUNNING_SQL) // Placeholders in order: project and clock (open questions), project and clock (pending - // secret requests), viewer (sum), project, viewer (ranking), limit. - .bind(projectId, now, projectId, now, viewerId, projectId, viewerId, limit) + // secret requests), working chat ids (JSON), viewer (sum), project, viewer (ranking), limit. + .bind( + projectId, + now, + projectId, + now, + JSON.stringify(workingSessionIds), + viewerId, + projectId, + viewerId, + limit + ) .all>(); const rows = result.results ?? []; const items: OverviewRunningChat[] = []; @@ -280,6 +299,17 @@ async function section( } } +/** + * Run a read once the mid-turn ids are known, so its clock is taken after that wait, the same + * side of an ask's expiry as Running now's own clock (`readRunningChats`). + */ +async function readBriefAfter( + working: Promise, + read: (ids: string[]) => Promise +): Promise { + return read(await working); +} + export async function projectOverviewGet( ctx: OperationContext, input: ProjectOverviewInput @@ -290,12 +320,26 @@ export async function projectOverviewGet( const recentLimit = clampLimit(input.recentLimit, DEFAULT_PROJECT_OVERVIEW_RECENT_LIMIT); const unavailable: ProjectOverviewSection[] = []; + // Read once, used by Running now and by the brief's re-check of the chats it names. If it + // fails, both sections are unavailable rather than reporting every chat as idle. + // `then`: a port that throws synchronously still becomes a rejection the sections catch. + const working = Promise.resolve().then(() => + ctx.ports.projectData.listWorkingChatSessionIds(projectId) + ); + working.catch(() => undefined); // Each section reports its own failure. const [running, ideas, mergedPullRequests, brief] = await Promise.all([ section( 'running', projectId, { items: [], total: 0, waitingOnViewerTotal: 0 }, - () => readRunningChats(ctx.env.DATABASE, projectId, ctx.actor.userId, runningLimit), + async () => + readRunningChats( + ctx.env.DATABASE, + projectId, + ctx.actor.userId, + runningLimit, + await working + ), unavailable ), section( @@ -320,7 +364,9 @@ export async function projectOverviewGet( null, async () => (await getProjectBriefSettings(ctx)).enabled - ? readProjectBrief(ctx.env.DATABASE, projectId, Date.now()) + ? await readBriefAfter(working, (ids) => + readProjectBrief(ctx.env.DATABASE, projectId, Date.now(), ids) + ) : null, unavailable ), diff --git a/packages/project-data/src/client/project-data.ts b/packages/project-data/src/client/project-data.ts index 41cec0102e..a7969ac83c 100644 --- a/packages/project-data/src/client/project-data.ts +++ b/packages/project-data/src/client/project-data.ts @@ -2869,6 +2869,17 @@ export async function getSessionState(env: Env, projectId: string, sessionId: st ); } +/** Awake chats whose agent is mid-turn (`do/session-state-read.ts`). */ +export async function listWorkingChatSessionIds(env: Env, projectId: string): Promise { + return callProjectDataWithRetry( + env, + projectId, + 'listWorkingChatSessionIds', + (stub) => stub.listWorkingChatSessionIds(), + 'idempotent_read' + ); +} + export async function registerTaskWait(env: Env, projectId: string, input: RegisterTaskWaitInput) { return callProjectDataWithRetry(env, projectId, 'registerTaskWait', (stub) => stub.registerTaskWait(input) diff --git a/packages/project-data/src/do/acp-sessions.ts b/packages/project-data/src/do/acp-sessions.ts index cbc5eee971..747beb13fc 100644 --- a/packages/project-data/src/do/acp-sessions.ts +++ b/packages/project-data/src/do/acp-sessions.ts @@ -109,7 +109,9 @@ export function listAcpSessions( const rows = sql .exec( - `SELECT * FROM acp_sessions ${where} ORDER BY created_at DESC LIMIT ? OFFSET ?`, + // `id DESC` breaks same-millisecond ties: the chat view's "newest session" and + // Running now's (`session-state-read.ts`, CHAT_ACTIVITY_SQL) must pick the same row. + `SELECT * FROM acp_sessions ${where} ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`, ...params, limit, offset diff --git a/packages/project-data/src/do/index.ts b/packages/project-data/src/do/index.ts index 27712f1792..e7af53efbd 100644 --- a/packages/project-data/src/do/index.ts +++ b/packages/project-data/src/do/index.ts @@ -3390,6 +3390,11 @@ export class ProjectData extends DurableObject { return sessionState.getSessionState(this.sql, sessionId); } + /** Awake chats whose agent is mid-turn (the Project Overview's Running now). */ + listWorkingChatSessionIds(): string[] { + return sessionState.listWorkingChatSessionIds(this.sql); + } + /** * Record a control-plane-observed turn ending (cancel, force-stop, dead * target). Idempotent and compare-and-set: a working state that began after diff --git a/packages/project-data/src/do/session-state-read.ts b/packages/project-data/src/do/session-state-read.ts index 8bbfce87fa..db3eea98ba 100644 --- a/packages/project-data/src/do/session-state-read.ts +++ b/packages/project-data/src/do/session-state-read.ts @@ -9,6 +9,47 @@ import type { SessionStateSnapshot, } from '@simple-agent-manager/shared'; +import { WORKING_ACTIVITIES } from './session-state-prompt'; + +/** + * A chat's activity, resolved the way the chat view resolves it (`resolveChatAgentState` in + * apps/api `routes/chat-agent-state.ts`): the newest ACP session's state row, else the row + * keyed by the chat itself. Over `cs` = chat_sessions. "Newest" is `created_at DESC, id DESC`, + * the same order `listAcpSessions` (`acp-sessions.ts`) uses, so a same-millisecond tie resolves + * to the same session in both. + */ +const CHAT_ACTIVITY_SQL = `COALESCE( + (SELECT s.activity FROM session_state s + WHERE s.session_id = (SELECT a.id FROM acp_sessions a + WHERE a.chat_session_id = cs.id + ORDER BY a.created_at DESC, a.id DESC LIMIT 1)), + (SELECT s.activity FROM session_state s WHERE s.session_id = cs.id))`; + +/** + * Awake chats whose agent is mid-turn: the activity mirror says a prompt is in flight + * (`WORKING_ACTIVITIES`). This is the Project Overview's "Running now" signal. It replaced a + * predicate on `tasks.execution_step` and `chat_sessions.agent_completed_at`: the step latches + * at `awaiting_followup` after the first turn and nothing writes `agent_completed_at`, so that + * predicate meant "still on its first turn" (rule 74). + * + * Bounded by `status = 'active'`: each awake chat holds a live runtime, so the set is the + * project's running agents, not its history (`idx_chat_sessions_status`). + */ +export function listWorkingChatSessionIds(sql: SqlStorage): string[] { + // Assembled only from module constants; every value is bound. Named `whereClause` because + // `scripts/quality/ast-checks.ts` allowlists that identifier for exactly this shape. + const whereClause = `cs.status = 'active' AND ${CHAT_ACTIVITY_SQL} IN (${WORKING_ACTIVITIES.map(() => '?').join(', ')})`; + const rows = sql + .exec( + `SELECT cs.id FROM chat_sessions cs WHERE ${whereClause} ORDER BY cs.id`, + ...WORKING_ACTIVITIES + ) + .toArray(); + return rows + .map((row) => row.id) + .filter((id): id is string => typeof id === 'string' && id.length > 0); +} + export function getSessionState(sql: SqlStorage, sessionId: string): SessionStateSnapshot | null { const rows = sql .exec( diff --git a/packages/project-data/src/do/session-state.ts b/packages/project-data/src/do/session-state.ts index 0328a1af87..52401dc3e9 100644 --- a/packages/project-data/src/do/session-state.ts +++ b/packages/project-data/src/do/session-state.ts @@ -390,5 +390,6 @@ export { export { getLatestPersistedPlan, getSessionState, + listWorkingChatSessionIds, type PersistedPlanSnapshot, } from './session-state-read'; diff --git a/tasks/archive/2026-11-20-overview-running-now-accuracy-and-rail-tightening.md b/tasks/archive/2026-11-20-overview-running-now-accuracy-and-rail-tightening.md new file mode 100644 index 0000000000..fe826e0efd --- /dev/null +++ b/tasks/archive/2026-11-20-overview-running-now-accuracy-and-rail-tightening.md @@ -0,0 +1,89 @@ +# Overview: accurate "Running now", tighter rail and Budgets + +## Problem + +Raphaël (2026-11-20): "Not sure how we decide what shows up in 'running now' in the overview... it's +not accurate. I also feel like the budgets are a bit busy. Dunno if we need all the text at the +bottom. I feel like that whole left column could be 'tighter' somehow." + +His screenshots show Running now = "Nothing is running." while the chat list shows 10 awake chats, +several with messages "Just now". Budgets shows 8 account rings and five lines of exception text +under them that repeat each account's name. + +## Research findings + +- Running now's rule is `overviewChatRunningSql` (`packages/operations/src/project-overview-statuses.ts`): + awake + task running status + (starting | paused on a person | `agent_completed_at IS NULL AND + execution_step <> 'awaiting_followup'`). +- Production D1 (2026-11-20 00:40Z, project SAM): all 10 `session_summaries.status='active'` chats + have tasks `in_progress` with `execution_step='awaiting_followup'` and `agent_completed_at` NULL. + So all fail the mid-turn disjunct. +- `tasks.execution_step` is written `running` only by the first transition to in_progress + (`apps/api/src/durable-objects/task-runner/in-progress-transition.ts`); `awaiting_followup` is + written when a turn ends and never cleared by a follow-up turn. It is latched after the first turn, + so the predicate really means "still on its first turn" (rule 74: proxy, not the condition). +- `chat_sessions.agent_completed_at` is set only by `markAgentCompleted`, which has no callers. It is + cleared on wake. It is never evidence of anything. +- The authority for "is the agent mid-turn" is the ProjectData DO `session_state.activity` + (`prompting`/`recovering` = `WORKING_ACTIVITIES`), written by VM agent activity callbacks and + control-plane turn ends, reconciled by `session-activity-reconciliation.ts` (rule 57). The chat view + resolves a chat's activity as the newest ACP session's row, falling back to the chat-keyed row + (`resolveChatAgentState`, `apps/api/src/routes/chat-agent-state.ts`). +- The same rule feeds the brief's re-check (`project-brief-read.ts`) and the brief facts + (`project-brief-facts.ts` -> `readRunningChats`), so all three consumers must change together. +- The Overview page already refetches on `session.activity` socket events (`useProjectOverview`), so + a DO-backed read is fresh within one refetch burst. +- Budgets (`apps/web/src/pages/project-overview/BudgetsSection.tsx`): tiles show ring + account name + + profile count/name, then a separate list of exception sentences naming each account again. + +## Design + +- New DO read `listWorkingChatSessionIds()`: awake chats whose resolved activity is working (same + resolution as `resolveChatAgentState`). One RPC per Overview read, shared by Running now and the + brief; one per brief refresh. +- `overviewChatRunningSql` takes the working ids (bound once as JSON, `json_each`) instead of the + `agent_completed_at`/`execution_step` disjunct. +- Budgets: fold the exception text into each tile's second line ("13% left" in the window's colour, + "Out", "Paused"); full words stay in the tile's accessible name and tooltip. Drop the profile-count + line and the sentence list. Smaller ring and tighter grid. +- Rail tightening: one-line titles and less padding for Running now and Recently rows. + +## Checklist + +- [x] DO: `listWorkingChatSessionIds` (project-data `do/`), DO method, client wrapper, operations port, api operation-ports wiring +- [x] operations: `overviewChatRunningSql(paused, working)`; `readRunningChats` + `readProjectBrief` + `readBriefFacts` take working ids; overview get fetches once and shares; failure -> sections unavailable +- [x] apps/api brief refresh passes working ids +- [x] Tests: DO read against real DO SQLite (workers test) incl. newest-ACP precedence, chat-keyed fallback, sleeping chat excluded; overview SQL against real SQLite: latched `awaiting_followup` + working -> listed (fails pre-fix), idle -> not listed (control), starting/paused still listed +- [x] Budgets tile status line + remove exception list; unit tests updated +- [x] Rail rows tightened (Running now, Recently) +- [x] Playwright audit (project-overview-audit.spec.ts) mobile + desktop, screenshots checked +- [x] Docs: any doc describing Running now's rule updated + +## Implementation notes + +- Commits on PR #2921. Discrimination: restoring the old predicate turns the `later-turn` overview + unit test (plus two idle-paused cases) red. +- Review: task-completion-validator PASS; cloudflare-specialist PASS (MEDIUM: a wedged `prompting` + row lists a chat, same as the chat view, healed by rule-57 reconciliation; kept); ui-ux-specialist + PASS, its two MEDIUMs fixed (visible status in the accessible name; number and colour from one window). +- Staging (sammy.party, deploy of e5133b500, project Potato, Claude Code conversation profile): + turn 1 listed as starting during provisioning, then working, then dropped at turn end; the + follow-up turn was listed as working while `tasks.execution_step` read `awaiting_followup` + (the incident shape), then dropped at turn end; no console errors. A first run with the default + OpenCode profile hit "Agent request failed" on staging (unrelated); Running now still dropped it. +- CodeRabbit: two minor findings fixed in 093fa6d3d (brief clock after the activity wait; the + cross-project test reports its attack chats as mid-turn, proven red without the join). +- Deferred: `markAgentCompleted` has no callers -> `tasks/backlog/2026-11-20-agent-completed-at-has-no-writer.md`. + +## Acceptance criteria + +- A chat whose task is latched at `awaiting_followup` but whose agent is mid-turn appears in Running now. +- An awake chat whose agent is idle (and not starting/paused) does not appear. +- The brief cannot name a chat as running that Running now does not list. +- Budgets shows no separate sentence list; each tile carries its own short status; screen readers still hear the full usage. +- Staging: start a chat, see it in Running now while the agent works; it leaves when the turn ends. + +## References + +- `.claude/rules/74-proxy-signals-must-match-the-condition.md`, `57`, `62`, `65` +- Idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9 (Inbox + Overview spec, section 4.2) diff --git a/tasks/backlog/2026-11-20-agent-completed-at-has-no-writer.md b/tasks/backlog/2026-11-20-agent-completed-at-has-no-writer.md new file mode 100644 index 0000000000..d530c8b105 --- /dev/null +++ b/tasks/backlog/2026-11-20-agent-completed-at-has-no-writer.md @@ -0,0 +1,23 @@ +# `chat_sessions.agent_completed_at` has no writer + +## Problem + +`ProjectData.markAgentCompleted` (`packages/project-data/src/do/index.ts`, `do/sessions.ts:markAgentCompleted`) +is the only writer of `chat_sessions.agent_completed_at`, and nothing calls it outside tests. The column +is cleared on wake and mirrored to D1 `session_summaries`, and the web app still reads +`agentCompletedAt` / `isIdle` to label a chat idle (`apps/web/src/lib/chat-session-utils.ts`). +So the "idle" label in the chat list can only come from `isIdle` or a live +`session.agent_completed` event, and the stored column is never evidence of anything. + +## Context + +Found 2026-11-20 while fixing the Project Overview's Running now (PR #2921), which had keyed on this +column and on the latched `tasks.execution_step`. Running now now reads the ProjectData activity +mirror (`listWorkingChatSessionIds`) instead. + +## Acceptance Criteria + +- [ ] Decide: derive the chat list's idle label from the activity mirror (as Running now does), or + wire a real writer at turn end (`recordTurnEnd` / idle activity report). +- [ ] Remove the dead writer and column readers, or the dead label path, whichever is not chosen. +- [ ] A test drives a real turn end and asserts the chat list's idle label.