From a917bed9fe1097cd46107285a2d0e72db5110323 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 12 Nov 2026 12:29:17 +0000 Subject: [PATCH 001/215] task: track owner force-resume for saved provider waits --- ...11-12-provider-limit-owner-force-resume.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 tasks/active/2026-11-12-provider-limit-owner-force-resume.md diff --git a/tasks/active/2026-11-12-provider-limit-owner-force-resume.md b/tasks/active/2026-11-12-provider-limit-owner-force-resume.md new file mode 100644 index 0000000000..fec69d0b84 --- /dev/null +++ b/tasks/active/2026-11-12-provider-limit-owner-force-resume.md @@ -0,0 +1,35 @@ +# Owner force-resume of saved provider-limited sessions + +## Problem + +Raphaël reports externally resetting his selected Claude account and cannot find the previous force control to deliver his latest message in the existing sleeping session. SAM still records the earlier rejection. The callback-origin waiting hold has neither admission-only Start anyway nor blocked-only Resume task. Canonical idea: 01M73WJGGD2TZP6XDFHJJWHD33, note 01M77SJS07XVH3MD6NVWCQNNNB. + +## Research + +- `provider-limit-recovery.ts`: existing admission override is credential scoped; keep admission/blocked semantics and add saved waiting eligibility separately. +- `session-recovery.ts`: existing waking claims must remain intact; nudge their stable TaskRunner. Unclaimed snapshots use normal recovery, preserving bounded attempts and snapshot degradation. +- `provider-limit-admission.ts`: released override bypasses live rejected window; must bind profile/current credential and deadline, preserve changed-account review. +- `project-event-schedules-delivery.ts`: scheduled callback continuation validates scheduleKey before submit; changing the key invalidates obsolete pending notices. Reconcile must still inspect already-issued receipts. +- Existing restored-session prompt machinery retains original accepted inbox messages. Do not repost/fork/replay. +- Sol owns shared catalog/placement and committed-active/readiness fixes. Coordinate imports and staging, do not duplicate. No migration expected; 0237 reserved elsewhere. + +## Implementation checklist + +- [ ] Add one owner operation for waiting callback parked sessions using existing override/recovery mechanisms. +- [ ] Fence task/wait, snapshot/claim, credential/profile and deadline; retain claim across ambiguous runner response. +- [ ] Keep original inbox/delivery identities and reconcile already-issued receipts; invalidate obsolete scheduled continuation. +- [ ] Add thin HTTP adapter and owner-only session notice action with pending/error state. +- [ ] Exercise public action in Workers through live rejected windows, claimed/unclaimed recovery and original delivery once. +- [ ] Cover double click, non-owner/access revocation, expired/degraded snapshot, cancellation, mutation/races and fresh rejection. +- [ ] Run API/UI quality checks and desktop/mobile screenshot audit. +- [ ] Update API/user docs; specialist reviews and task-completion review. +- [ ] Coordinate bounded real staging validation and cleanup. +- [ ] Draft PR, CI, CodeRabbit, full-head evidence to coordinator. + +## Acceptance criteria + +Owner can request Resume anyway on an eligible callback waiting saved session before reset. Existing task/snapshot/profile/account and original accepted delivery remain authoritative. Claimed recovery advances without claim replacement. Unclaimed recovery uses normal restoration. A changed account/profile cannot inherit consent; terminal/expired/cancelled work cannot advance. An actual rejection re-parks and clears override; repeated clicks do not duplicate work. UI is usable on mobile/desktop. Tests, review and real staging evidence precede release. + +## Release gate + +Keep PR draft until coordinator 01M77NV1B621TKTV79272F7YX3 independently approves full 40-character head. Every new commit invalidates approval. No production DB bypass, reset or replay. Automatic overage parsing remains separate in canonical idea. From aa7b98a858e7948ff69c3100f9809e516286aa22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Thu, 12 Nov 2026 12:52:42 +0000 Subject: [PATCH 002/215] fix: let owners resume saved provider-limited sessions --- .claude/skills/api-reference/SKILL.md | 1 + .../project-event-schedules-delivery.ts | 13 +- .../task-runner/provider-limit-admission.ts | 23 +- .../task-runner/recovery-authority.ts | 21 + apps/api/src/routes/chat-session-detail.ts | 8 + .../agent-credential-attribution.ts | 4 +- .../services/provider-limit-credential-pin.ts | 34 +- .../services/provider-limit-force-resume.ts | 245 +++++++++ .../api/src/services/provider-limit-policy.ts | 9 +- .../src/services/provider-limit-recovery.ts | 6 + .../services/vm-prompt-delivery-adapter.ts | 15 +- .../provider-limit-admission.test.ts | 102 ++++ ...rovider-limit-credential-injection.test.ts | 105 ++++ .../provider-limit-force-resume.test.ts | 485 ++++++++++++++++++ .../vm-prompt-delivery-adapter.test.ts | 25 + .../provider-limit-full-restore.test.ts | 178 +++++++ .../src/components/ProviderLimitResume.tsx | 11 +- .../SessionStatusBanners.tsx | 19 +- apps/web/src/lib/api/sessions.ts | 1 + apps/web/src/lib/api/tasks.ts | 4 +- .../provider-limit-hold-actions-audit.spec.ts | 74 ++- .../components/ProviderLimitResume.test.tsx | 49 ++ .../docs/guides/session-troubleshooting.md | 7 + packages/shared/src/types/session.ts | 1 + specs/001-mvp/contracts/api.md | 4 + ...11-12-provider-limit-owner-force-resume.md | 16 +- 26 files changed, 1414 insertions(+), 46 deletions(-) create mode 100644 apps/api/src/services/provider-limit-force-resume.ts create mode 100644 apps/api/tests/integration/provider-limit-force-resume.test.ts diff --git a/.claude/skills/api-reference/SKILL.md b/.claude/skills/api-reference/SKILL.md index 13fb846b90..9d68f6db14 100644 --- a/.claude/skills/api-reference/SKILL.md +++ b/.claude/skills/api-reference/SKILL.md @@ -111,6 +111,7 @@ Comment threads are scoped to the ProjectData Durable Object addressed by `proje - `GET /api/projects/:projectId/tasks/:taskId` — Get task detail (includes dependencies + blocked state) - `PATCH /api/projects/:projectId/tasks/:taskId` — Update task fields (`title`, `description`, `priority`, `parentTaskId`) - `DELETE /api/projects/:projectId/tasks/:taskId` — Delete task +- `POST /api/projects/:projectId/tasks/:taskId/provider-limit/start-anyway` — Owner-only `task:write` override of a waiting admission hold (`202 starting`) or saved callback hold (`202 waking`, same account/profile and retained claim). The saved-session notice calls this **Resume anyway**. Snapshot/generation/authority/expiry are rechecked; changed waits return `409`. - `POST /api/projects/:projectId/tasks/:taskId/provider-limit/resume` — Owner approves a blocked provider wait and resumes its retained snapshot or first-dispatch admission. Requires `task:write`; `202` waking, `409` if no longer blocked or snapshot unavailable. - `POST /api/projects/:projectId/tasks/:taskId/status` — Transition task status - `POST /api/projects/:projectId/tasks/:taskId/status/callback` — Trusted callback status update for delegated tasks diff --git a/apps/api/src/durable-objects/project-data/project-event-schedules-delivery.ts b/apps/api/src/durable-objects/project-data/project-event-schedules-delivery.ts index ce640680ac..9dd98acf76 100644 --- a/apps/api/src/durable-objects/project-data/project-event-schedules-delivery.ts +++ b/apps/api/src/durable-objects/project-data/project-event-schedules-delivery.ts @@ -57,7 +57,9 @@ export async function invalidScheduledDeliveryTarget( projectId: string | null, claim: PromptDeliveryClaim ): Promise { - if (claim.message.sourceKind !== 'scheduled_action') return null; + if (claim.message.sourceKind !== 'scheduled_action' || claim.mode === 'reconcile') return null; + // Reconciliation only reads the prior runtime receipt. Current schedule, task + // or membership changes revoke future submits, never erase an issued prompt. const scheduleId = claim.message.metadata?.scheduleId; const invalid = (): PromptDeliveryResult => ({ kind: 'failed', @@ -113,15 +115,6 @@ export async function invalidScheduledDeliveryTarget( return local() ? accessEnded() : invalid(); } catch (error) { if (error instanceof ProjectEventValidationError) return invalid(); - if (claim.mode === 'reconcile') - return { - kind: 'ambiguous', - reason: 'receipt_unavailable', - error: 'Scheduled action authority check unavailable during reconciliation', - receipt: null, - runtimeIdentity: claim.message.runtimeIdentity, - capabilities: null, - }; return { kind: 'retry', reason: 'not_ready', diff --git a/apps/api/src/durable-objects/task-runner/provider-limit-admission.ts b/apps/api/src/durable-objects/task-runner/provider-limit-admission.ts index b5cd04b37e..7a18f3c0ae 100644 --- a/apps/api/src/durable-objects/task-runner/provider-limit-admission.ts +++ b/apps/api/src/durable-objects/task-runner/provider-limit-admission.ts @@ -108,19 +108,36 @@ export async function holdTaskForProviderLimit( // 01M73WJGGD2TZP6XDFHJJWHD33). It covers only the exact, non-null credential it was granted // for: any other selection falls through to the checks below and blocks for review. A real // provider rejection later builds a fresh wait without the override and parks as usual. + const approval = previous?.ownerOverride; + const approvalScopeChanged = + approval?.expiresAt !== undefined && + (approval.expiresAt <= now || + approval.profileId !== (row?.agent_profile_hint ?? null) || + approval.skillId !== (row?.skill_id ?? null) || + approval.agentType !== + (state.config.agentType || rc.env.DEFAULT_TASK_AGENT_TYPE || 'opencode') || + (approval.profileId !== null && profile?.profileId !== approval.profileId) || + (profile !== null && profile.agentType !== approval.agentType)); if ( key !== null && previous?.phase === 'released' && - previous.ownerOverride?.credentialKey === key + approval?.credentialKey === key && + !approvalScopeChanged ) return false; const window = await rejectedProviderWindow(rc.env, reference, now); let wait = previous; - if (!ownerResumed && previous?.credentialKey && previous.credentialKey !== key) { + if ( + previous && + (approvalScopeChanged || + (!ownerResumed && previous.credentialKey && previous.credentialKey !== key)) + ) { wait = { ...previous, phase: 'blocked', - reason: 'Blocked: selected provider credential changed; review before resuming.', // A blocked wait needs fresh review; an earlier start-anyway must not carry over. + reason: approvalScopeChanged + ? 'Blocked: provider resume approval expired or the selected profile changed; review before resuming.' + : 'Blocked: selected provider credential changed; review before resuming.', // A blocked wait needs fresh review; an earlier start-anyway must not carry over. ownerOverride: undefined, }; } else if (previous?.phase === 'blocked') { diff --git a/apps/api/src/durable-objects/task-runner/recovery-authority.ts b/apps/api/src/durable-objects/task-runner/recovery-authority.ts index 13731badfd..50f130cc83 100644 --- a/apps/api/src/durable-objects/task-runner/recovery-authority.ts +++ b/apps/api/src/durable-objects/task-runner/recovery-authority.ts @@ -8,6 +8,7 @@ * the check that failed and logs it with the snapshot claim (`recovery-revocation.ts`). */ import type { Env } from '../../env'; +import { parseProviderLimitWait } from '../../services/provider-limit-policy'; import { assertReplacementDeletionConfirmed } from '../../services/replacement-deletion-fence'; import { findSessionRecoveryTaskAndEventAuthorityFailure, @@ -85,6 +86,26 @@ export async function findRecoveryAuthorityFailure( ): Promise { const attemptFailure = await findRecoveryAttemptFailure(env, ctx, input); if (attemptFailure) return attemptFailure; + // Owner force-resume can approve a previously unguarded human-message wake. + // Keep its existing claim, while making that approval revocable at every + // external runner boundary rather than only when the owner clicked. + const ownerApproval = await env.DATABASE.prepare( + `SELECT t.provider_limit_wait_json, + EXISTS (SELECT 1 FROM project_members m JOIN users u ON u.id=m.user_id + WHERE m.project_id=t.project_id AND m.user_id=t.user_id AND m.status='active' + AND m.role IN ('owner','admin','maintainer') AND u.status='active') AS member_active + FROM tasks t WHERE t.id=? AND t.project_id=? AND t.user_id=? + AND json_valid(t.provider_limit_wait_json) + AND json_type(t.provider_limit_wait_json,'$.ownerOverride.expiresAt')='integer'` + ) + .bind(input.taskId, input.projectId, input.userId) + .first<{ provider_limit_wait_json: string; member_active: number }>(); + if ( + ownerApproval && + !ownerApproval.member_active && + parseProviderLimitWait(ownerApproval.provider_limit_wait_json)?.ownerOverride + ) + return 'recovery_task_authority'; const sourceTaskId = input.config.recoverySourceTaskId ?? null; const chatSessionId = input.config.resumeSnapshotChatSessionId ?? null; // A human follow-up may recover a completed conversation without a live diff --git a/apps/api/src/routes/chat-session-detail.ts b/apps/api/src/routes/chat-session-detail.ts index ad6451646c..a92284b35c 100644 --- a/apps/api/src/routes/chat-session-detail.ts +++ b/apps/api/src/routes/chat-session-detail.ts @@ -22,6 +22,7 @@ import { getPullRequestStates } from '../operations/pull-request-core'; import type { OperationContext } from '../operations/types'; import { resolveTaskAgentProfileHint } from '../services/agent-profile-display'; import * as projectDataService from '../services/project-data'; +import { canResumeProviderLimitTaskAnyway } from '../services/provider-limit-force-resume'; import { parseProviderLimitWait } from '../services/provider-limit-policy'; import { canStartProviderLimitTaskAnyway } from '../services/provider-limit-recovery'; import { publicPlacementExplanationJson } from '../services/public-placement-explanation'; @@ -183,6 +184,13 @@ export function registerChatSessionDetailRoute(chatRoutes: Hono<{ Bindings: Env taskRow, parseProviderLimitWait(taskRow.providerLimitWaitJson) ), + providerLimitCanResumeAnyway: + taskRow.userId === userId && + sessionRecord.status === 'sleeping' && + canResumeProviderLimitTaskAnyway( + taskRow, + parseProviderLimitWait(taskRow.providerLimitWaitJson) + ), status: isTaskStatus(taskRow.status) ? taskRow.status : 'draft', executionStep: isTaskExecutionStep(taskRow.executionStep) ? taskRow.executionStep diff --git a/apps/api/src/routes/workspaces/agent-credential-attribution.ts b/apps/api/src/routes/workspaces/agent-credential-attribution.ts index a577483dfe..b26353f71c 100644 --- a/apps/api/src/routes/workspaces/agent-credential-attribution.ts +++ b/apps/api/src/routes/workspaces/agent-credential-attribution.ts @@ -44,7 +44,9 @@ export async function persistAgentCredentialAttribution( await assertProviderLimitCredentialPin( env, input.workspaceId, - input.attribution.credentialReference + input.attribution.credentialReference, + workspace, + input.agentType ); const now = new Date().toISOString(); diff --git a/apps/api/src/services/provider-limit-credential-pin.ts b/apps/api/src/services/provider-limit-credential-pin.ts index 6db73b44f4..79339a2c9c 100644 --- a/apps/api/src/services/provider-limit-credential-pin.ts +++ b/apps/api/src/services/provider-limit-credential-pin.ts @@ -1,5 +1,9 @@ +import { drizzle } from 'drizzle-orm/d1'; + +import * as schema from '../db/schema'; import type { Env } from '../env'; import { errors } from '../middleware/error'; +import { resolveSessionProfileCredentialContext } from './composable-credentials/profile-context'; import { credentialLimitReferenceKey } from './credential-limit-events/values'; import { parseProviderLimitWait } from './provider-limit-policy'; import { @@ -13,11 +17,12 @@ export async function assertProviderLimitCredentialPin( env: Env, workspaceId: string, reference: string, - expectedWorkspace?: WorkspaceCallbackIdentitySnapshot + expectedWorkspace?: WorkspaceCallbackIdentitySnapshot, + requestedAgentType?: string ): Promise { const key = await credentialLimitReferenceKey(reference); const tasks = await env.DATABASE.prepare( - `SELECT t.id, t.admission_state, t.provider_limit_wait_json, + `SELECT t.id, t.admission_state, t.provider_limit_wait_json,t.agent_profile_hint,t.skill_id, w.id AS workspaceId, w.user_id AS userId, w.project_id AS projectId, w.chat_session_id AS chatSessionId, w.status, w.node_id AS nodeId, n.status AS nodeStatus, w.callback_generation AS callbackGeneration @@ -30,6 +35,8 @@ export async function assertProviderLimitCredentialPin( .all< WorkspaceCallbackIdentitySnapshot & { id: string | null; + agent_profile_hint: string | null; + skill_id: string | null; admission_state: string | null; provider_limit_wait_json: string | null; } @@ -47,7 +54,28 @@ export async function assertProviderLimitCredentialPin( (!task.provider_limit_wait_json && !task.admission_state?.startsWith('provider_limit_')) ) continue; - if (wait?.credentialKey && key === wait.credentialKey && wait.phase !== 'blocked') continue; + const approval = wait?.ownerOverride; + const profile = + approval?.expiresAt !== undefined + ? await resolveSessionProfileCredentialContext(drizzle(env.DATABASE, { schema }), { + workspaceId, + }) + : null; + const approvalInvalid = + approval?.expiresAt !== undefined && + (approval.expiresAt <= Date.now() || + (requestedAgentType !== undefined && requestedAgentType !== approval.agentType) || + task.agent_profile_hint !== approval.profileId || + task.skill_id !== approval.skillId || + (profile?.profileId ?? null) !== approval.profileId || + (profile !== null && profile.agentType !== approval.agentType)); + if ( + wait?.credentialKey && + key === wait.credentialKey && + wait.phase !== 'blocked' && + !approvalInvalid + ) + continue; const reason = wait?.phase === 'blocked' ? wait.reason diff --git a/apps/api/src/services/provider-limit-force-resume.ts b/apps/api/src/services/provider-limit-force-resume.ts new file mode 100644 index 0000000000..614821f494 --- /dev/null +++ b/apps/api/src/services/provider-limit-force-resume.ts @@ -0,0 +1,245 @@ +/** Owner recovery of a saved callback hold. Reuses the existing claim and runner. */ +import { drizzle } from 'drizzle-orm/d1'; + +import * as schema from '../db/schema'; +import type { Env } from '../env'; +import { log } from '../lib/logger'; +import { getCredentialEncryptionKey } from '../lib/secrets'; +import { errors } from '../middleware/error'; +import { getSelectedAgentCredentialReference } from '../routes/credentials'; +import { resolveProfileCredentialContext } from './composable-credentials/profile-context'; +import { credentialLimitReferenceKey } from './credential-limit-events/values'; +import * as projectData from './project-data'; +import type { ProviderLimitWait } from './provider-limit-policy'; +import { requireSessionWriter } from './session-access'; +import { ensureSessionRecovery } from './session-recovery'; +import { nudgeTaskRunnerDO } from './task-runner-do'; + +export function canResumeProviderLimitTaskAnyway( + task: Pick, + wait: ProviderLimitWait | null, + now = Date.now() +): boolean { + return ( + task.admissionState === 'provider_limit_waiting' && + ['sleeping', 'queued', 'delegated'].includes(task.status) && + wait?.origin === 'callback' && + wait.phase === 'waiting' && + wait.credentialKey !== null && + wait.deadlineAt > now + ); +} + +export async function forceResumeSavedProviderLimitTask( + env: Env, + task: schema.Task, + ownerUserId: string, + wait: ProviderLimitWait +) { + if (task.userId !== ownerUserId) throw errors.forbidden('Only the task owner can resume anyway'); + if (!task.chatSessionId || !canResumeProviderLimitTaskAnyway(task, wait)) + throw errors.conflict('This saved task is not waiting on a provider limit'); + const writer = await requireSessionWriter(env, task.projectId, task.chatSessionId, ownerUserId, { + action: 'resume despite the provider limit', + }); + if ( + writer.role !== 'owner' || + writer.ownerUserId !== ownerUserId || + writer.session.taskId !== task.id || + writer.session.status !== 'sleeping' + ) + throw errors.conflict('The saved session authority changed; refresh before resuming'); + + const now = Date.now(); + const nowIso = new Date(now).toISOString(); + const snapshot = await env.DATABASE.prepare( + `SELECT s.id,s.recovery_status,s.recovery_task_id,s.recovery_attempt_id,s.updated_at, + a.agent_type,a.agent_profile_id,a.agent_credential_reference,a.agent_credential_generation + FROM session_snapshots s JOIN workspaces w ON w.id=s.workspace_id + JOIN agent_sessions a ON a.id=? AND a.workspace_id=s.workspace_id AND a.user_id=s.user_id + WHERE s.project_id=? AND s.chat_session_id=? AND s.user_id=? + AND s.runtime='vm' AND s.sleeping_at IS NOT NULL AND s.sleep_status='sleeping' + AND s.expires_at>? AND julianday(s.expires_at) IS NOT NULL + AND ((s.status='available' AND s.degradation='none') OR + (s.status='degraded' AND s.degradation IS NOT NULL AND s.degradation!='none')) + AND w.project_id=s.project_id AND w.user_id=s.user_id AND w.status IN ('sleeping','deleted','stopped') + AND (? IS NULL OR ?=s.workspace_id) + AND (s.recovery_status IS NULL OR s.recovery_status='failed' OR + (s.recovery_status='waking' AND s.recovery_task_id=? AND s.recovery_attempt_id IS NOT NULL AND ? IS NULL))` + ) + .bind( + wait.sourceAgentSessionId ?? null, + task.projectId, + task.chatSessionId, + ownerUserId, + nowIso, + task.workspaceId, + task.workspaceId, + task.id, + task.workspaceId + ) + .first<{ + id: string; + recovery_status: string | null; + recovery_task_id: string | null; + recovery_attempt_id: string | null; + updated_at: string; + agent_type: string; + agent_profile_id: string | null; + agent_credential_reference: string | null; + agent_credential_generation: number; + }>(); + if (!snapshot) + throw errors.conflict('The saved snapshot is unavailable, expired, or already restoring'); + const db = drizzle(env.DATABASE, { schema }); + const profile = await resolveProfileCredentialContext(db, { + userId: ownerUserId, + projectId: task.projectId, + profileId: task.agentProfileHint, + skillId: task.skillId, + }); + const reference = await getSelectedAgentCredentialReference( + db, + ownerUserId, + snapshot.agent_type, + getCredentialEncryptionKey(env), + task.projectId, + profile + ); + if ( + snapshot.agent_credential_generation !== wait.sourceCredentialGeneration || + snapshot.agent_profile_id !== task.agentProfileHint || + (task.agentProfileHint !== null && !profile) || + (profile && profile.agentType !== snapshot.agent_type) || + (await credentialLimitReferenceKey(snapshot.agent_credential_reference)) !== + wait.credentialKey || + (await credentialLimitReferenceKey(reference)) !== wait.credentialKey + ) + throw errors.conflict( + 'The selected account or profile changed; review the provider hold before resuming' + ); + + const grantNow = Date.now(); + if (wait.deadlineAt <= grantNow) + throw errors.conflict('Provider wait expired while resuming; refresh and review'); + const grantIso = new Date(grantNow).toISOString(); + const retainedSnapshot = snapshot; + const overridden = JSON.stringify({ + ...wait, + phase: 'released', + ownerOverride: { + credentialKey: wait.credentialKey, + grantedAt: grantNow, + profileId: task.agentProfileHint, + skillId: task.skillId, + agentType: snapshot.agent_type, + expiresAt: wait.deadlineAt, + }, + // Existing scheduled deliveries are fenced by this key immediately before submit. + scheduleKey: `provider-limit:${task.id}:override:${crypto.randomUUID()}`, + } satisfies ProviderLimitWait); + const changed = await env.DATABASE.prepare( + `UPDATE tasks SET provider_limit_wait_json=?,admission_state=NULL,admission_reason=NULL, + admission_next_retry_at=NULL,updated_at=? + WHERE id=? AND project_id=? AND user_id=? AND chat_session_id=? + AND status=? AND workspace_id IS ? AND agent_profile_hint IS ? AND skill_id IS ? + AND admission_state='provider_limit_waiting' AND provider_limit_wait_json IS ? + AND EXISTS (SELECT 1 FROM project_members m JOIN users u ON u.id=m.user_id + WHERE m.project_id=tasks.project_id AND m.user_id=tasks.user_id AND m.status='active' + AND m.role IN ('owner','admin','maintainer') AND u.status='active') + AND EXISTS (SELECT 1 FROM session_snapshots s JOIN agent_sessions a ON a.id=? AND a.workspace_id=s.workspace_id AND a.user_id=s.user_id + WHERE s.id=? AND s.updated_at=? AND s.recovery_status IS ? AND s.recovery_task_id IS ? AND s.recovery_attempt_id IS ? + AND s.expires_at>? AND s.sleeping_at IS NOT NULL AND s.sleep_status='sleeping' + AND ((s.status='available' AND s.degradation='none') OR + (s.status='degraded' AND s.degradation IS NOT NULL AND s.degradation!='none')) + AND EXISTS (SELECT 1 FROM workspaces w WHERE w.id=s.workspace_id AND w.user_id=s.user_id + AND w.project_id=s.project_id AND w.status IN ('sleeping','deleted','stopped')) + AND a.agent_credential_generation=? AND a.agent_credential_reference IS ? + AND a.agent_type=? AND a.agent_profile_id IS ?)` + ) + .bind( + overridden, + nowIso, + task.id, + task.projectId, + ownerUserId, + task.chatSessionId, + task.status, + task.workspaceId, + task.agentProfileHint, + task.skillId, + task.providerLimitWaitJson, + wait.sourceAgentSessionId, + snapshot.id, + snapshot.updated_at, + snapshot.recovery_status, + snapshot.recovery_task_id, + snapshot.recovery_attempt_id, + grantIso, + wait.sourceCredentialGeneration, + snapshot.agent_credential_reference, + snapshot.agent_type, + task.agentProfileHint + ) + .run(); + if (!changed.meta.changes) + throw errors.conflict('Task changed while resuming; refresh and try again'); + + // Never clear a claim, even when an RPC response is lost. The normal runner's + // authority checks and alarms own restoration and receipt reconciliation. + if (snapshot.recovery_status === 'waking') { + let nudged: boolean; + try { + nudged = await nudgeTaskRunnerDO(env, task.id, 'Owner resumed despite provider limit'); + } catch { + throw errors.conflict('Resume accepted, but the runner did not confirm; refresh shortly'); + } + if (!nudged) { + await restoreHold(); + throw errors.conflict('The existing recovery runner is unavailable; try again shortly'); + } + } else { + const result = await ensureSessionRecovery(env, task.projectId, task.chatSessionId, { + taskId: task.id, + projectId: task.projectId, + chatSessionId: task.chatSessionId, + requiredProjectMemberId: ownerUserId, + }); + if (result.status !== 'waking') { + await restoreHold(); + throw errors.conflict(`Unable to resume the saved task: ${result.reason}`); + } + } + await projectData + .syncProviderLimitAttention(env, task.projectId, task.id, task.chatSessionId) + .catch(() => + log.warn('provider_limit.force_resume_attention_sync_failed', { taskId: task.id }) + ); + return { status: 'waking' as const, taskId: task.id }; + + async function restoreHold() { + // A definitive failure restores only our receipt. A concurrent recovery or + // fresh rejection must never be overwritten, nor its claim released. + await env.DATABASE.prepare( + `UPDATE tasks SET provider_limit_wait_json=?,admission_state='provider_limit_waiting', + admission_reason=?,admission_next_retry_at=? + WHERE id=? AND provider_limit_wait_json IS ? AND (workspace_id IS ? OR (status='sleeping' AND workspace_id IS NULL)) + AND status IN ('sleeping','queued','delegated') + AND EXISTS (SELECT 1 FROM session_snapshots s WHERE s.id=? + AND ((s.recovery_attempt_id IS ? AND s.recovery_status IS ?) + OR (s.recovery_status='failed' AND s.recovery_task_id=tasks.id AND tasks.status='sleeping' AND tasks.workspace_id IS NULL)))` + ) + .bind( + task.providerLimitWaitJson, + wait.reason, + new Date(wait.nextRetryAt).toISOString(), + task.id, + overridden, + task.workspaceId, + retainedSnapshot.id, + retainedSnapshot.recovery_attempt_id, + retainedSnapshot.recovery_status + ) + .run(); + } +} diff --git a/apps/api/src/services/provider-limit-policy.ts b/apps/api/src/services/provider-limit-policy.ts index 32ac390d5d..3b2d827e61 100644 --- a/apps/api/src/services/provider-limit-policy.ts +++ b/apps/api/src/services/provider-limit-policy.ts @@ -39,7 +39,14 @@ export const ProviderLimitWaitSchema = v.object({ /** The owner chose to start despite this hold (for example to spend extra credits the * subscription window does not reflect). Honoured only for the credential it names. */ ownerOverride: v.optional( - v.object({ credentialKey: v.nullable(v.string()), grantedAt: timestamp }) + v.object({ + credentialKey: v.nullable(v.string()), + grantedAt: timestamp, + profileId: v.optional(v.nullable(v.string())), + skillId: v.optional(v.nullable(v.string())), + agentType: v.optional(v.string()), + expiresAt: v.optional(timestamp), + }) ), }); export type ProviderLimitWait = v.InferOutput; diff --git a/apps/api/src/services/provider-limit-recovery.ts b/apps/api/src/services/provider-limit-recovery.ts index 3a900a9155..e7039ebe32 100644 --- a/apps/api/src/services/provider-limit-recovery.ts +++ b/apps/api/src/services/provider-limit-recovery.ts @@ -4,6 +4,10 @@ import type { Env } from '../env'; import { log } from '../lib/logger'; import { errors } from '../middleware/error'; import * as projectData from './project-data'; +import { + canResumeProviderLimitTaskAnyway, + forceResumeSavedProviderLimitTask, +} from './provider-limit-force-resume'; import { parseProviderLimitWait, type ProviderLimitWait } from './provider-limit-policy'; import { ensureSessionRecovery } from './session-recovery'; import { nudgeTaskRunnerDO } from './task-runner-do'; @@ -216,6 +220,8 @@ export async function startProviderLimitTaskAnyway( throw errors.forbidden('Only the task owner can start this task anyway'); } const wait = parseProviderLimitWait(task.providerLimitWaitJson); + if (wait && canResumeProviderLimitTaskAnyway(task, wait)) + return forceResumeSavedProviderLimitTask(env, task, ownerUserId, wait); const observed = wait; // un-narrowed copy for the rejection log if (!canStartProviderLimitTaskAnyway(task, wait)) { log.warn('provider_limit.start_anyway_rejected', { diff --git a/apps/api/src/services/vm-prompt-delivery-adapter.ts b/apps/api/src/services/vm-prompt-delivery-adapter.ts index 73ff00cd95..de38f149b0 100644 --- a/apps/api/src/services/vm-prompt-delivery-adapter.ts +++ b/apps/api/src/services/vm-prompt-delivery-adapter.ts @@ -30,6 +30,7 @@ import { } from './vm-prompt-delivery-runtime-queries'; import { resolveVmPromptDeliveryTarget, + type ResolveTargetOptions, type TargetResolution, type VmPromptDeliverySourceTaskGuard, type VmPromptDeliveryTarget, @@ -147,9 +148,7 @@ export class DefaultVmPromptDeliveryAdapter implements VmPromptDeliveryAdapter { }; } if (target.runtime === 'cf-container') { - const guarded = await commitContainerWake(this.env, target, () => - runSideEffectGuard(input) - ); + const guarded = await commitContainerWake(this.env, target, () => runSideEffectGuard(input)); if (guarded) return guarded; } if (!capabilities.promptReceipts.supported && !input.allowLegacyVm) { @@ -344,7 +343,9 @@ export class DefaultVmPromptDeliveryAdapter implements VmPromptDeliveryAdapter { async reconcile(input: VmPromptDeliveryAdapterInput): Promise { const resolution: TargetResolution = input.resolvedTarget ? { kind: 'ready', target: input.resolvedTarget } - : await this.resolveTarget(input.projectId, input.claim.message.targetSessionId, input); + : await this.resolveTarget(input.projectId, input.claim.message.targetSessionId, input, { + allowWake: false, + }); if (resolution.kind === 'guarded') return resolution.result; if (resolution.kind === 'failed') { return { @@ -423,14 +424,16 @@ export class DefaultVmPromptDeliveryAdapter implements VmPromptDeliveryAdapter { private async resolveTarget( projectId: string, chatSessionId: string, - input: VmPromptDeliveryAdapterInput + input: VmPromptDeliveryAdapterInput, + options: ResolveTargetOptions = {} ): Promise { return resolveVmPromptDeliveryTarget( this.env, projectId, chatSessionId, input.sourceTaskGuard, - () => runSideEffectGuard(input) + () => runSideEffectGuard(input), + options ); } diff --git a/apps/api/tests/integration/provider-limit-admission.test.ts b/apps/api/tests/integration/provider-limit-admission.test.ts index ae50288516..3f8dd34fb8 100644 --- a/apps/api/tests/integration/provider-limit-admission.test.ts +++ b/apps/api/tests/integration/provider-limit-admission.test.ts @@ -446,6 +446,108 @@ describe('provider admission through the TaskRunner alarm', () => { fixture.sqlite.prepare("SELECT admission_state FROM tasks WHERE id='task-1'").get() ).toEqual({ admission_state: 'provider_limit_blocked' }); }); + describe('saved callback owner approval scope', () => { + function approveCallback() { + fixture.sqlite.exec(`UPDATE users SET status='active' WHERE id='user-1'; + UPDATE project_members SET role='owner',status='active' WHERE project_id='project-1' AND user_id='user-1'; + INSERT INTO agent_profiles(id,user_id,project_id,name,agent_type) VALUES ('approved-profile','user-1','project-1','Approved','opencode'); + INSERT INTO skills(id,user_id,project_id,name,agent_type) VALUES ('approved-skill','user-1','project-1','Approved',NULL); + UPDATE tasks SET agent_profile_hint='approved-profile',skill_id='approved-skill' WHERE id='task-1'`); + fixture.state.config.agentProfileHint = 'approved-profile'; + fixture.state.config.agentType = 'opencode'; + const now = Date.now(); + const approved = { + ...newProviderLimitWait({ + taskId: 'task-1', + origin: 'callback', + incidentId: 'saved-rejection', + credentialKey: 'cc_credentials:quota-key', + previous: null, + now, + resetsAt: now + 8 * 60 * 60_000, + }), + phase: 'released', + scheduleKey: 'provider-limit:task-1:override:approved', + ownerOverride: { + credentialKey: 'cc_credentials:quota-key', + grantedAt: now, + profileId: 'approved-profile', + skillId: 'approved-skill', + agentType: 'opencode', + expiresAt: now + 60_000, + }, + }; + fixture.sqlite + .prepare( + "UPDATE tasks SET provider_limit_wait_json=?,admission_state=NULL WHERE id='task-1'" + ) + .run(JSON.stringify(approved)); + rejected(now + 8 * 60 * 60_000); + return JSON.stringify(approved); + } + function savedApproval() { + return fixture.sqlite + .prepare("SELECT admission_state,provider_limit_wait_json FROM tasks WHERE id='task-1'") + .get() as { admission_state: string | null; provider_limit_wait_json: string }; + } + + it.each(['node_selection', 'agent_session'] as const)( + 'honours a scoped callback override at %s without changing live rejection evidence', + async (step) => { + const approved = approveCallback(); + const before = fixture.sqlite.prepare('SELECT * FROM credential_limit_windows').all(); + const run = runner(step); + await run.runner.alarm(); + expect(savedApproval()).toEqual({ + admission_state: null, + provider_limit_wait_json: approved, + }); + expect(fixture.sqlite.prepare('SELECT * FROM credential_limit_windows').all()).toEqual( + before + ); + expect(run.state().currentStep).not.toBe(step); + if (step === 'agent_session') expect(startSamAwareAgentSession).toHaveBeenCalledOnce(); + } + ); + + it.each([ + ['expired', null], + ['changed profile', "UPDATE tasks SET agent_profile_hint=NULL WHERE id='task-1'"], + ['changed skill', "UPDATE tasks SET skill_id=NULL WHERE id='task-1'"], + ['changed profile agent', "UPDATE agent_profiles SET agent_type='claude-code'"], + ['changed skill agent', "UPDATE skills SET agent_type='claude-code'"], + ['invalid profile', "UPDATE agent_profiles SET project_id='other-project'"], + ['changed runner agent', null], + ['changed account', null], + ])('blocks a %s approval and clears it before any initial prompt', async (change, sql) => { + approveCallback(); + const before = fixture.sqlite.prepare('SELECT * FROM credential_limit_windows').all(); + if (sql) fixture.sqlite.exec(sql); + if (change === 'expired') vi.advanceTimersByTime(60_000); + if (change === 'changed runner agent') fixture.state.config.agentType = 'claude-code'; + if (change === 'changed account') + vi.mocked(getSelectedAgentCredentialReference).mockResolvedValueOnce( + 'cc_credentials:other' + ); + const run = runner(); + await run.runner.alarm(); + expect(run.state().currentStep).toBe('node_selection'); + expect(run.state().stepResults.nodeId).toBeNull(); + expect(run.alarm()).toBeNull(); + expect(startSamAwareAgentSession).not.toHaveBeenCalled(); + const saved = savedApproval(); + expect(saved.admission_state).toBe('provider_limit_blocked'); + expect(JSON.parse(saved.provider_limit_wait_json)).toMatchObject({ + phase: 'blocked', + credentialKey: 'cc_credentials:quota-key', + }); + expect(JSON.parse(saved.provider_limit_wait_json).ownerOverride).toBeUndefined(); + expect(fixture.sqlite.prepare('SELECT * FROM credential_limit_windows').all()).toEqual( + before + ); + }); + }); + describe('owner controls on a held, never-started task', () => { async function heldTask() { const db = drizzle(fixture.rc.env.DATABASE, { schema }); diff --git a/apps/api/tests/integration/provider-limit-credential-injection.test.ts b/apps/api/tests/integration/provider-limit-credential-injection.test.ts index fbc342fab4..f9c5bf2f39 100644 --- a/apps/api/tests/integration/provider-limit-credential-injection.test.ts +++ b/apps/api/tests/integration/provider-limit-credential-injection.test.ts @@ -76,6 +76,111 @@ describe('provider wait credential pin at the authenticated secret injection rou env ); } + describe('scoped callback approval at credential injection', () => { + function scopedApproval() { + pin('cc_credentials:pinned'); + sqlite.exec(`INSERT INTO agent_profiles(id,user_id,project_id,name,agent_type) VALUES ('approved-profile','user-1','project-1','Approved','opencode'); + INSERT INTO skills(id,user_id,project_id,name,agent_type) VALUES ('approved-skill','user-1','project-1','Approved',NULL); + UPDATE tasks SET agent_profile_hint='approved-profile',skill_id='approved-skill',admission_state=NULL WHERE id='task-1'; + UPDATE agent_sessions SET agent_profile_id='approved-profile',skill_id='approved-skill'; + INSERT INTO credential_limit_windows(project_id,credential_reference,window_type,status,resets_at,observed_at) + VALUES ('project-1','cc_credentials:pinned','subscription','rejected',9999999999999,1)`); + const wait = JSON.parse( + ( + sqlite.prepare('SELECT provider_limit_wait_json AS value FROM tasks').get() as { + value: string; + } + ).value + ); + const approved = { + ...wait, + ownerOverride: { + credentialKey: 'cc_credentials:pinned', + grantedAt: Date.now(), + profileId: 'approved-profile', + skillId: 'approved-skill', + agentType: 'opencode', + expiresAt: Date.now() + 60_000, + }, + }; + sqlite.prepare('UPDATE tasks SET provider_limit_wait_json=?').run(JSON.stringify(approved)); + return JSON.stringify(approved); + } + + it('injects only the approved account without editing the live rejected window or callback approval', async () => { + const approved = scopedApproval(); + const before = sqlite.prepare('SELECT * FROM credential_limit_windows').all(); + const response = await inject(); + expect(response.status, await response.clone().text()).toBe(200); + expect(await response.json()).toMatchObject({ + apiKey: key.secret, + credentialReference: 'cc_credentials:pinned', + }); + expect(sqlite.prepare('SELECT * FROM credential_limit_windows').all()).toEqual(before); + expect(sqlite.prepare('SELECT provider_limit_wait_json AS value FROM tasks').get()).toEqual({ + value: approved, + }); + }); + + it.each([ + ['expired', null], + ['changed task profile', 'UPDATE tasks SET agent_profile_hint=NULL'], + ['changed task skill', 'UPDATE tasks SET skill_id=NULL'], + ['changed profile agent', "UPDATE agent_profiles SET agent_type='claude-code'"], + ['changed skill agent', "UPDATE skills SET agent_type='claude-code'"], + ['invalid profile ownership', "UPDATE agent_profiles SET project_id='other-project'"], + ['changed account', null], + ])('withholds the secret for %s and removes approval', async (change, sql) => { + const approved = JSON.parse(scopedApproval()); + if (sql) sqlite.exec(sql); + if (change === 'expired') { + approved.ownerOverride.expiresAt = Date.now() - 1; + sqlite.prepare('UPDATE tasks SET provider_limit_wait_json=?').run(JSON.stringify(approved)); + } + if (change === 'changed account') key.reference = 'cc_credentials:other'; + const response = await inject(); + expect(response.status, await response.clone().text()).toBe(409); + expect(await response.text()).not.toContain(key.secret); + const saved = sqlite + .prepare('SELECT admission_state,provider_limit_wait_json FROM tasks') + .get() as { admission_state: string; provider_limit_wait_json: string }; + expect(saved.admission_state).toBe('provider_limit_blocked'); + expect(JSON.parse(saved.provider_limit_wait_json)).toMatchObject({ phase: 'blocked' }); + expect(JSON.parse(saved.provider_limit_wait_json).ownerOverride).toBeUndefined(); + expect(sqlite.prepare('SELECT agent_credential_reference FROM agent_sessions').get()).toEqual( + { agent_credential_reference: null } + ); + }); + + it('rechecks approval after attribution so a profile mutation cannot leak the secret', async () => { + scopedApproval(); + const prepare = env.DATABASE.prepare.bind(env.DATABASE); + env.DATABASE.prepare = ((query: string) => { + const statement = prepare(query); + if (!/UPDATE agent_sessions/i.test(query)) return statement; + const bind = statement.bind.bind(statement); + statement.bind = ((...values: unknown[]) => { + const bound = bind(...values); + const first = bound.first.bind(bound); + bound.first = (async () => { + const result = await first(); + sqlite.exec('UPDATE tasks SET skill_id=NULL'); + return result; + }) as typeof bound.first; + return bound; + }) as typeof statement.bind; + return statement; + }) as typeof env.DATABASE.prepare; + const response = await inject(); + expect(response.status).toBe(409); + expect(await response.text()).not.toContain(key.secret); + const saved = sqlite.prepare('SELECT provider_limit_wait_json AS value FROM tasks').get() as { + value: string; + }; + expect(JSON.parse(saved.value).ownerOverride).toBeUndefined(); + }); + }); + it('matching pin can receive its selected credential', async () => { pin('cc_credentials:pinned'); const response = await inject(); diff --git a/apps/api/tests/integration/provider-limit-force-resume.test.ts b/apps/api/tests/integration/provider-limit-force-resume.test.ts new file mode 100644 index 0000000000..0b83de9570 --- /dev/null +++ b/apps/api/tests/integration/provider-limit-force-resume.test.ts @@ -0,0 +1,485 @@ +/** Owner HTTP action -> native D1 CAS + ProjectData session authority -> retained runner. */ +import Database from 'better-sqlite3'; +import { Hono } from 'hono'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import * as schema from '../../src/db/schema'; +import { runMigrations } from '../../src/durable-objects/migrations'; +import { + createAttentionMarker, + listActiveAttentionMarkers, +} from '../../src/durable-objects/project-data/attention'; +import { syncProviderLimitAttention } from '../../src/durable-objects/project-data/provider-limit-attention'; +import { resolveSessionAccess } from '../../src/durable-objects/project-data/session-access'; +import { getSession } from '../../src/durable-objects/project-data/session-reads'; +import { findRecoveryAuthorityFailure } from '../../src/durable-objects/task-runner/recovery-authority'; +import type { StartTaskInput } from '../../src/durable-objects/task-runner/types'; +import type { Env } from '../../src/env'; +import { AppError } from '../../src/middleware/error'; +import { providerLimitResumeRoutes } from '../../src/routes/tasks/provider-limit-resume'; +import { + newProviderLimitWait, + type ProviderLimitWait, +} from '../../src/services/provider-limit-policy'; +import { createAllSchemaTables } from '../helpers/sqlite-d1'; +import { + createEvictionEnv, + pickEvictionPools, + seedEvictionOwnerAndNode, +} from '../helpers/workspace-eviction-route-harness'; +import { createSqlStorage } from '../unit/durable-objects/sql-storage-test-utils'; + +const boundary = vi.hoisted(() => ({ + userId: 'user-1', + start: vi.fn(), + nudge: vi.fn<(...args: unknown[]) => Promise>(), + selected: vi.fn<(...args: unknown[]) => Promise>(), + sql: null as unknown as SqlStorage, +})); +vi.mock('../../src/middleware/auth', () => ({ + getUserId: () => boundary.userId, + requireAuth: () => async (_c: unknown, next: () => Promise) => next(), + requireApproved: () => async (_c: unknown, next: () => Promise) => next(), +})); +// Credential decryption is outside this slice. Profile resolution, source generation, +// credential reference comparison and every persistence predicate remain real. +vi.mock('../../src/routes/credentials', () => ({ + getSelectedAgentCredentialReference: (...args: unknown[]) => boundary.selected(...args), +})); +vi.mock('../../src/services/task-runner-do', () => ({ + startTaskRunnerDO: (...args: unknown[]) => boundary.start(...args), + ensureTaskRunnerStarted: vi.fn(async () => false), + nudgeTaskRunnerDO: (...args: unknown[]) => boundary.nudge(...args), +})); +vi.mock('../../src/services/project-data', () => ({ + getSessionAccess: async (_env: unknown, _project: string, sessionId: string, userId: string) => ({ + session: getSession(boundary.sql, sessionId), + access: resolveSessionAccess(boundary.sql, sessionId, userId), + }), + getSession: async (_env: unknown, _project: string, sessionId: string) => + getSession(boundary.sql, sessionId), + syncProviderLimitAttention: async ( + env: Env, + projectId: string, + taskId: string, + sessionId: string + ) => syncProviderLimitAttention(boundary.sql, env.DATABASE, { projectId, taskId, sessionId }), +})); + +describe('callback provider hold owner force resume', () => { + let d1: Database.Database; + let local: Database.Database; + let env: Env; + let app: Hono<{ Bindings: Env }>; + beforeEach(async () => { + vi.resetAllMocks(); + boundary.userId = 'user-1'; + boundary.nudge.mockResolvedValue(true); + boundary.selected.mockResolvedValue('cc_credentials:account-1'); + d1 = new Database(':memory:'); + createAllSchemaTables(d1, schema); + env = createEvictionEnv(d1, { ENCRYPTION_KEY: 'test-key' }); + seedEvictionOwnerAndNode(d1); + await pickEvictionPools(env); + local = new Database(':memory:'); + boundary.sql = createSqlStorage(local); + runMigrations(boundary.sql); + boundary.sql + .exec(`INSERT INTO chat_sessions(id,task_id,created_by_user_id,status,topic,message_count,started_at,created_at,updated_at) + VALUES ('chat-1','task-1','user-1','sleeping','Task',1,1,1,1)`); + d1.exec(`INSERT INTO agent_profiles(id,project_id,user_id,name,agent_type) + VALUES ('profile-1','project-1','user-1','Claude','claude-code'); + INSERT INTO workspaces(id,user_id,project_id,node_id,status,branch,vm_size,vm_location,workspace_profile,created_at,updated_at) + VALUES ('workspace-1','user-1','project-1','node-1','deleted','main','small','nbg1','lightweight',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP); + INSERT INTO tasks(id,project_id,user_id,chat_session_id,agent_profile_hint,title,status,priority,task_mode,dispatch_depth,triggered_by,created_by,created_at,updated_at) + VALUES ('task-1','project-1','user-1','chat-1','profile-1','Task','queued',0,'task',0,'mcp','user-1',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP); + INSERT INTO agent_sessions(id,workspace_id,user_id,status,agent_type,agent_profile_id,agent_credential_reference,agent_credential_generation) + VALUES ('source-1','workspace-1','user-1','stopped','claude-code','profile-1','cc_credentials:account-1',7); + INSERT INTO session_snapshots(id,project_id,user_id,chat_session_id,workspace_id,node_id,runtime,status,degradation,manifest_r2_key,manifest_json,expires_at,sleeping_at,sleep_status,recovery_status,recovery_task_id,recovery_attempt_id,recovery_attempts,sleep_attempts,created_at,updated_at) + VALUES ('snapshot-1','project-1','user-1','chat-1','workspace-1','node-1','vm','available','none','retained/wip','{}','2099-01-01T00:00:00Z',CURRENT_TIMESTAMP,'sleeping','waking','task-1','existing-claim',1,1,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`); + setWait({ + ...newProviderLimitWait({ + taskId: 'task-1', + origin: 'callback', + incidentId: 'rejected-prompt-1', + credentialKey: 'cc_credentials:account-1', + previous: null, + now: Date.now(), + resetsAt: Date.now() + 8 * 60 * 60_000, + jitter: 0, + }), + sourceAgentSessionId: 'source-1', + sourceCredentialGeneration: 7, + }); + app = new Hono<{ Bindings: Env }>(); + app.onError((error, c) => + error instanceof AppError + ? c.json(error.toJSON(), error.statusCode) + : c.json({ error: String(error) }, 500) + ); + app.route('/projects/:projectId/tasks', providerLimitResumeRoutes); + }); + afterEach(() => { + d1.close(); + local.close(); + }); + + function task() { + return d1.prepare("SELECT * FROM tasks WHERE id='task-1'").get() as Record; + } + function claim() { + return d1.prepare('SELECT * FROM session_snapshots').get() as Record; + } + function wait(): ProviderLimitWait { + return JSON.parse(task().provider_limit_wait_json as string); + } + function setWait(value: ProviderLimitWait) { + d1.prepare( + "UPDATE tasks SET provider_limit_wait_json=?,admission_state='provider_limit_waiting',admission_reason=?,admission_next_retry_at=? WHERE id='task-1'" + ).run(JSON.stringify(value), value.reason, new Date(value.nextRetryAt).toISOString()); + } + function resume(project = 'project-1') { + return app.request( + `/projects/${project}/tasks/task-1/provider-limit/start-anyway`, + { method: 'POST' }, + env + ); + } + async function expectRefused(status = 409) { + const original = task().provider_limit_wait_json; + const originalClaim = claim(); + const response = await resume(); + expect(response.status, await response.clone().text()).toBe(status); + expect(task().provider_limit_wait_json).toBe(original); + expect(claim()).toEqual(originalClaim); + expect(boundary.nudge).not.toHaveBeenCalled(); + expect(boundary.start).not.toHaveBeenCalled(); + } + + it('overrides a future timer while preserving the exact snapshot and already-owned recovery claim', async () => { + const before = claim(); + const held = wait(); + createAttentionMarker(boundary.sql, { + sessionId: 'chat-1', + taskId: 'task-1', + workspaceId: null, + kind: 'needs_input', + source: 'test', + }); + expect(held.nextRetryAt).toBeGreaterThan(Date.now()); + const response = await resume(); + expect(response.status, await response.clone().text()).toBe(202); + expect(await response.json()).toEqual({ status: 'waking', taskId: 'task-1' }); + expect(boundary.nudge).toHaveBeenCalledExactlyOnceWith( + env, + 'task-1', + 'Owner resumed despite provider limit' + ); + expect(boundary.start).not.toHaveBeenCalled(); + expect(claim()).toEqual(before); + expect(task()).toMatchObject({ + status: 'queued', + workspace_id: null, + chat_session_id: 'chat-1', + admission_state: null, + admission_next_retry_at: null, + }); + expect(wait()).toMatchObject({ + phase: 'released', + incidentId: held.incidentId, + sourceAgentSessionId: 'source-1', + sourceCredentialGeneration: 7, + attempts: held.attempts, + ownerOverride: { + credentialKey: held.credentialKey, + profileId: 'profile-1', + skillId: null, + agentType: 'claude-code', + expiresAt: held.deadlineAt, + }, + }); + expect(wait().scheduleKey).not.toBe(held.scheduleKey); + expect(listActiveAttentionMarkers(boundary.sql, 'chat-1')).toEqual([ + expect.objectContaining({ kind: 'needs_input' }), + ]); + expect(getSession(boundary.sql, 'chat-1')).toMatchObject({ + status: 'sleeping', + taskId: 'task-1', + }); + }); + + it('serializes simultaneous clicks through the persisted hold CAS', async () => { + const before = claim(); + const responses = await Promise.all([resume(), resume()]); + expect(responses.map((r) => r.status).sort()).toEqual([202, 409]); + expect(boundary.nudge).toHaveBeenCalledOnce(); + expect(boundary.start).not.toHaveBeenCalled(); + expect(claim()).toEqual(before); + }); + + it('restores the original hold after a definitive nudge refusal without releasing its claim', async () => { + const original = task().provider_limit_wait_json; + const before = claim(); + boundary.nudge.mockResolvedValueOnce(false); + expect((await resume()).status).toBe(409); + expect(task()).toMatchObject({ + admission_state: 'provider_limit_waiting', + provider_limit_wait_json: original, + }); + expect(claim()).toEqual(before); + expect((await resume()).status).toBe(202); + }); + + it('retains approval and the claim when a nudge response is lost', async () => { + const before = claim(); + boundary.nudge.mockRejectedValueOnce(new Error('RPC response lost')); + expect((await resume()).status).toBe(409); + expect(task().admission_state).toBeNull(); + expect(wait()).toMatchObject({ + phase: 'released', + ownerOverride: { credentialKey: 'cc_credentials:account-1' }, + }); + expect(claim()).toEqual(before); + expect((await resume()).status).toBe(409); + expect(boundary.nudge).toHaveBeenCalledOnce(); + }); + + it('does not overwrite a newer recovery attempt when a nudge definitively fails', async () => { + boundary.nudge.mockImplementationOnce(async () => { + d1.exec("UPDATE session_snapshots SET recovery_attempt_id='new-claim'"); + return false; + }); + expect((await resume()).status).toBe(409); + expect(claim().recovery_attempt_id).toBe('new-claim'); + expect(task().admission_state).toBeNull(); + expect(wait().phase).toBe('released'); + }); + + it('claims an unclaimed sleeping snapshot through normal recovery and starts the same task', async () => { + d1.exec( + "UPDATE workspaces SET runtime_deletion_confirmed_at=CURRENT_TIMESTAMP; UPDATE tasks SET status='sleeping',workspace_id='workspace-1'; UPDATE session_snapshots SET recovery_status=NULL,recovery_task_id=NULL,recovery_attempt_id=NULL" + ); + const response = await resume(); + expect(response.status, await response.clone().text()).toBe(202); + expect(boundary.nudge).not.toHaveBeenCalled(); + expect(boundary.start).toHaveBeenCalledOnce(); + expect(boundary.start.mock.calls[0]?.[1]).toMatchObject({ + taskId: 'task-1', + resumeSnapshotChatSessionId: 'chat-1', + }); + expect(claim()).toMatchObject({ + id: 'snapshot-1', + recovery_status: 'waking', + recovery_task_id: 'task-1', + recovery_attempt_id: expect.any(String), + manifest_r2_key: 'retained/wip', + }); + expect(task()).toMatchObject({ + id: 'task-1', + chat_session_id: 'chat-1', + status: 'queued', + admission_state: null, + }); + }); + + it('revokes an approved existing runner after project write access is removed', async () => { + expect((await resume()).status).toBe(202); + const input: StartTaskInput = { + taskId: 'task-1', + projectId: 'project-1', + userId: 'user-1', + config: { + vmSize: 'small', + vmLocation: 'nbg1', + branch: 'main', + defaultBranch: 'main', + preferredNodeId: null, + userName: 'Test User', + userEmail: 'test@example.com', + githubId: 'gh-1', + taskTitle: 'Task', + taskDescription: 'Continue the task', + repository: 'owner/repo', + installationId: 'install-1', + outputBranch: null, + projectDefaultVmSize: null, + chatSessionId: 'chat-1', + agentType: 'claude-code', + workspaceProfile: 'lightweight', + devcontainerConfigName: null, + cloudProvider: 'hetzner', + credentialAttributionUserId: 'user-1', + credentialAttributionProjectId: null, + credentialAttributionSource: 'user', + taskMode: 'task', + model: null, + effort: null, + permissionMode: null, + opencodeProvider: null, + opencodeBaseUrl: null, + systemPromptAppend: null, + agentProfileHint: 'profile-1', + attachments: null, + resumeSnapshotChatSessionId: 'chat-1', + recoveryAttemptId: 'existing-claim', + // The pre-existing human wake has no orchestration parent guard. + recoverySourceTaskId: null, + }, + }; + const ctx = { storage: { get: vi.fn(async () => undefined) } } as unknown as DurableObjectState; + expect(await findRecoveryAuthorityFailure(env, ctx, input)).toBeNull(); + d1.exec("UPDATE project_members SET role='viewer'"); + expect(await findRecoveryAuthorityFailure(env, ctx, input)).toBe('recovery_task_authority'); + expect(claim().recovery_attempt_id).toBe('existing-claim'); + }); + + it('restores a retryable hold when a newly claimed recovery cannot start', async () => { + d1.exec( + "UPDATE workspaces SET runtime_deletion_confirmed_at=CURRENT_TIMESTAMP; UPDATE tasks SET status='sleeping',workspace_id='workspace-1'; UPDATE session_snapshots SET recovery_status=NULL,recovery_task_id=NULL,recovery_attempt_id=NULL" + ); + const original = task().provider_limit_wait_json; + boundary.start.mockRejectedValueOnce(new Error('runner unavailable')); + const response = await resume(); + expect(response.status, await response.clone().text()).toBe(409); + expect(task()).toMatchObject({ + status: 'sleeping', + workspace_id: null, + admission_state: 'provider_limit_waiting', + provider_limit_wait_json: original, + }); + expect(claim()).toMatchObject({ + id: 'snapshot-1', + recovery_status: 'failed', + manifest_r2_key: 'retained/wip', + }); + expect((await resume()).status).toBe(202); + }); + + it.each([ + ['expired', "UPDATE session_snapshots SET expires_at='2000-01-01T00:00:00Z'"], + ['malformed expiry', "UPDATE session_snapshots SET expires_at='tomorrow'"], + ['unavailable', "UPDATE session_snapshots SET status='failed'"], + ['incoherent degradation', "UPDATE session_snapshots SET degradation='missing_wip'"], + ['degraded without reason', "UPDATE session_snapshots SET status='degraded'"], + ['awake snapshot', "UPDATE session_snapshots SET sleep_status='waking'"], + ['foreign claim', "UPDATE session_snapshots SET recovery_task_id='another-task'"], + ['claim without attempt', 'UPDATE session_snapshots SET recovery_attempt_id=NULL'], + ['active workspace', "UPDATE workspaces SET status='running'"], + ['different workspace', "UPDATE tasks SET workspace_id='another-workspace'"], + ['changed generation', 'UPDATE agent_sessions SET agent_credential_generation=8'], + [ + 'changed source account', + "UPDATE agent_sessions SET agent_credential_reference='cc_credentials:other'", + ], + ['changed source profile', 'UPDATE agent_sessions SET agent_profile_id=NULL'], + ['invalid profile ownership', "UPDATE agent_profiles SET project_id='another-project'"], + ['changed profile agent', "UPDATE agent_profiles SET agent_type='codex'"], + ['cancelled task', "UPDATE tasks SET status='cancelled'"], + ['terminal task', "UPDATE tasks SET status='completed'"], + ])('refuses %s without mutating the hold or claim', async (_label, mutation) => { + d1.exec(mutation); + await expectRefused(); + }); + + it('supports snapshots with an explicit degradation reason', async () => { + d1.exec("UPDATE session_snapshots SET status='degraded',degradation='missing_wip'"); + const before = claim(); + const response = await resume(); + expect(response.status, await response.clone().text()).toBe(202); + expect(claim()).toEqual(before); + }); + + it.each([ + ['deadline expired', { deadlineAt: 1 }], + ['missing credential', { credentialKey: null }], + ['blocked wait', { phase: 'blocked' }], + ['missing source', { sourceAgentSessionId: undefined }], + ['missing source generation', { sourceCredentialGeneration: undefined }], + ] as const)('refuses a %s callback hold', async (_label, mutation) => { + setWait({ ...wait(), ...mutation }); + await expectRefused(); + }); + + it('refuses a changed selected account', async () => { + boundary.selected.mockResolvedValueOnce('cc_credentials:other'); + await expectRefused(); + }); + + it('rejects task-owner access when session ownership changed', async () => { + boundary.sql.exec("UPDATE chat_sessions SET created_by_user_id='other'"); + await expectRefused(403); + }); + + it('rejects a task/session authority mismatch', async () => { + boundary.sql.exec("UPDATE chat_sessions SET task_id='another-task'"); + await expectRefused(); + }); + + it('rejects a session that is already active', async () => { + boundary.sql.exec("UPDATE chat_sessions SET status='active'"); + await expectRefused(); + }); + + it('refuses another maintainer and a cross-project lookup', async () => { + d1.exec( + "INSERT INTO users(id,status) VALUES ('other','active'); INSERT INTO project_members(project_id,user_id,role,status) VALUES ('project-1','other','maintainer','active')" + ); + boundary.userId = 'other'; + await expectRefused(403); + boundary.userId = 'user-1'; + expect((await resume('another-project')).status).toBe(404); + }); + + it('refuses revoked project capability before issuing approval', async () => { + d1.exec("UPDATE project_members SET role='viewer'"); + await expectRefused(403); + }); + + it.each([ + ['cancelled', "UPDATE tasks SET status='cancelled'"], + ['source generation changed', 'UPDATE agent_sessions SET agent_credential_generation=8'], + [ + 'source account changed', + "UPDATE agent_sessions SET agent_credential_reference='cc_credentials:other'", + ], + ['task profile changed', 'UPDATE tasks SET agent_profile_hint=NULL'], + ['membership revoked', "UPDATE project_members SET status='removed'"], + ['user disabled', "UPDATE users SET status='suspended'"], + ['snapshot expired', "UPDATE session_snapshots SET expires_at='2000-01-01T00:00:00Z'"], + ['snapshot invalidated', "UPDATE session_snapshots SET status='failed'"], + ['workspace awoke', "UPDATE workspaces SET status='running'"], + ['claim owner changed', "UPDATE session_snapshots SET recovery_task_id='another-task'"], + ['source agent changed', "UPDATE agent_sessions SET agent_type='openai-codex'"], + ['claim replaced', "UPDATE session_snapshots SET recovery_attempt_id='new-claim'"], + ])('CAS refuses a concurrent %s before the runner nudge', async (_label, mutation) => { + const original = task().provider_limit_wait_json; + boundary.selected.mockImplementationOnce(async () => { + d1.exec(mutation); + return 'cc_credentials:account-1'; + }); + const response = await resume(); + expect(response.status, await response.clone().text()).toBe(409); + expect(task().provider_limit_wait_json).toBe(original); + expect(boundary.nudge).not.toHaveBeenCalled(); + expect(boundary.start).not.toHaveBeenCalled(); + }); + it('refuses expiry elapsed during credential resolution without changing the hold', async () => { + const original = task().provider_limit_wait_json; + const originalClaim = claim(); + let restoreClock: (() => void) | undefined; + boundary.selected.mockImplementationOnce(async () => { + const clock = vi.spyOn(Date, 'now').mockReturnValue(wait().deadlineAt + 1); + restoreClock = () => clock.mockRestore(); + return 'cc_credentials:account-1'; + }); + try { + const response = await resume(); + expect(response.status, await response.clone().text()).toBe(409); + expect(task().provider_limit_wait_json).toBe(original); + expect(claim()).toEqual(originalClaim); + expect(boundary.nudge).not.toHaveBeenCalled(); + } finally { + restoreClock?.(); + } + }); +}); diff --git a/apps/api/tests/unit/services/vm-prompt-delivery-adapter.test.ts b/apps/api/tests/unit/services/vm-prompt-delivery-adapter.test.ts index 10a69fbbe4..ffe83ce83e 100644 --- a/apps/api/tests/unit/services/vm-prompt-delivery-adapter.test.ts +++ b/apps/api/tests/unit/services/vm-prompt-delivery-adapter.test.ts @@ -1217,3 +1217,28 @@ describe('attachment delivery ordering', () => { expect(mocks.sendPromptToAgentOnNode).not.toHaveBeenCalled(); }); }); + +describe('issued prompt receipt reconciliation never wakes a runtime', () => { + beforeEach(() => vi.clearAllMocks()); + it.each([ + ['sleeping VM', { ...targetRow, workspace_status: 'sleeping' }], + ['deleted VM', { ...targetRow, workspace_status: 'deleted' }], + ['sleeping Instant', sleptContainerRow], + ['missing workspace', null], + ])('keeps %s ambiguous without replay, recovery, or provisioning', async (_label, row) => { + mocks.ensureSessionRecovery.mockResolvedValue({ status: 'waking', taskId: 'task-1' }); + const request = input(false); + request.claim.mode = 'reconcile'; + request.claim.message.sourceKind = 'scheduled_action'; + request.claim.message.runtimeIdentity = 'issued-runtime-1'; + // The schedule was cancelled after issue; the source guard allows only a + // receipt lookup. Target resolution itself must not provision a new runtime. + request.beforeSideEffect = async () => null; + const result = await new DefaultVmPromptDeliveryAdapter(envWithTarget(row)).reconcile(request); + expect(result.kind).toBe('ambiguous'); + expect(mocks.ensureSessionRecovery).not.toHaveBeenCalled(); + expect(mocks.wakeSession).not.toHaveBeenCalled(); + expect(mocks.sendPromptToAgentOnNode).not.toHaveBeenCalled(); + expect(mocks.nodeAgentRequest).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/tests/workers/provider-limit-full-restore.test.ts b/apps/api/tests/workers/provider-limit-full-restore.test.ts index da0580069c..9db4e6c8d4 100644 --- a/apps/api/tests/workers/provider-limit-full-restore.test.ts +++ b/apps/api/tests/workers/provider-limit-full-restore.test.ts @@ -11,6 +11,7 @@ import { parseProviderLimitWait, PROVIDER_LIMIT_CONTINUATION, } from '../../src/services/provider-limit-policy'; +import { ensureSessionRecovery } from '../../src/services/session-recovery'; import { buildSessionSnapshotR2Key } from '../../src/services/session-snapshots'; import { acceptedPromptResponse, @@ -28,6 +29,7 @@ import { taskRunner, waitForWakeReadiness, } from './helpers/provider-limit-restore'; +import { seedSignedInUser } from './helpers/seed-d1'; declare const __PROVIDER_LIMIT_CALLBACKS__: Array<{ name: string; @@ -142,6 +144,20 @@ function vmPeer(f: Fixture, replacementNode: string, restoreFailure: boolean) { available: true, manifest: { acpSessionId: 'saved-harness', agentType: f.agentType }, }); + // A real VM resolves/injects the selected account when it loads the saved + // harness too. Model that callback, not only the fresh /start branch. + const injected = await SELF.fetch( + `https://api.test.example.com/api/workspaces/${workspaceId}/agent-key`, + { + method: 'POST', + headers: { + Authorization: `Bearer ${tokens.get(workspaceId)}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ agentType: f.agentType, agentSessionId: path.split('/')[4] }), + } + ); + expect(injected.status, await injected.clone().text()).toBe(200); return Response.json({ status: restoreFailure ? 'failed' : 'restored' }); } if (path.endsWith('/start')) { @@ -343,3 +359,165 @@ describe('provider limit -> canonical sleep -> full restored continuation', () = 30_000 ); }); + +describe('owner force-resume before the recorded reset through public HTTP', () => { + it.each([false, true])( + 'retains the original delivery and snapshot (claimed=%s)', + async (claimed) => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date(recorded.now)); + const f = await agentOnVm('task'); + const calls = vmPeer(f, `replacement-${f.id}`, false); + const token = await signCallbackToken(f.workspaceId, testEnv, { callbackGeneration: null }); + const callback = await SELF.fetch( + `https://api.test.example.com/api/projects/${f.projectId}/tasks/${f.taskId}/status/callback`, + { + method: 'POST', + headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ...callbackCases[0]!.callback, + providerLimitAgentSessionId: `a-${f.id}`, + }), + } + ); + expect(callback.status, await callback.text()).toBe(200); + await runSessionSleepSweep(testEnv); + await deleteSleptWorkspace(f.nodeId, f.taskId); + await readyReplacementNode(f); + const deliveryId = `original-human-message-${f.id}`; + const accepted = await f.stub.acceptPromptDelivery({ + deliveryId, + targetSessionId: f.chatSessionId, + sourceTaskId: f.taskId, + senderType: 'human', + senderId: f.userId, + sourceKind: 'user_followup', + messageClass: 'deliver', + displayContent: 'Please continue my existing work now.', + deliveryContent: 'Please continue my existing work now.', + ttlMs: 60 * 60_000, + }); + const waitBefore = parseProviderLimitWait( + (await env.DATABASE.prepare('SELECT * FROM tasks WHERE id=?') + .bind(f.taskId) + .first>())!.provider_limit_wait_json as string + )!; + expect(waitBefore.nextRetryAt).toBeGreaterThan(Date.now()); + if (claimed) { + expect(await ensureSessionRecovery(testEnv, f.projectId, f.chatSessionId)).toMatchObject({ + status: 'waking', + taskId: f.taskId, + }); + // The existing runner really holds on the old future timer. + await runInDurableObject(taskRunner(f.taskId), (instance) => instance.alarm()); + expect( + ( + await env.DATABASE.prepare('SELECT * FROM tasks WHERE id=?') + .bind(f.taskId) + .first>() + )?.admission_state + ).toBe('provider_limit_waiting'); + } + const snapshotBefore = await env.DATABASE.prepare( + 'SELECT * FROM session_snapshots WHERE chat_session_id=?' + ) + .bind(f.chatSessionId) + .first(); + const cookie = await seedSignedInUser(f.userId); + const act = () => + SELF.fetch( + `https://api.test.example.com/api/projects/${f.projectId}/tasks/${f.taskId}/provider-limit/start-anyway`, + { + method: 'POST', + headers: { Cookie: cookie, Origin: 'https://app.test.example.com' }, + } + ); + const response = await act(); + expect(response.status, await response.clone().text()).toBe(202); + expect(await response.json()).toMatchObject({ status: 'waking', taskId: f.taskId }); + expect((await act()).status).toBe(409); + const snapshotAfter = await env.DATABASE.prepare( + 'SELECT * FROM session_snapshots WHERE chat_session_id=?' + ) + .bind(f.chatSessionId) + .first(); + expect(snapshotAfter).toMatchObject({ + id: snapshotBefore!.id, + manifest_r2_key: snapshotBefore!.manifest_r2_key, + }); + if (claimed) + expect(snapshotAfter!.recovery_attempt_id).toBe(snapshotBefore!.recovery_attempt_id); + await driveMove(f); + await waitForWakeReadiness(f); + for (let pass = 0; pass < 4; pass++) await runDueDelivery(f, Date.now() + pass * 60_000); + const prompts = calls.filter( + (c) => c.path.endsWith('/prompt') && c.body.deliveryId === deliveryId + ); + expect(prompts).toHaveLength(1); + expect(prompts[0]!.body.prompt).toBe('Please continue my existing work now.'); + expect( + await sqlRows( + f.stub, + 'SELECT id,prompt_message_id,delivery_state FROM session_inbox WHERE id=?', + deliveryId + ) + ).toEqual([ + { + id: deliveryId, + prompt_message_id: accepted.message.promptMessageId, + delivery_state: 'acked', + }, + ]); + // Late old scheduled continuations cannot cause an extra provider prompt. + vi.setSystemTime(waitBefore.nextRetryAt + 1); + await fireSchedule(f); + for (let pass = 0; pass < 3; pass++) await runDueDelivery(f, Date.now() + pass * 60_000); + expect( + calls.filter( + (c) => + c.path.endsWith('/prompt') && + String(c.body.prompt).includes(PROVIDER_LIMIT_CONTINUATION) + ) + ).toHaveLength(0); + const running = await env.DATABASE.prepare( + `SELECT a.id,a.agent_credential_generation,w.id AS workspace_id,w.callback_generation + FROM tasks t JOIN workspaces w ON w.id=t.workspace_id + JOIN agent_sessions a ON a.workspace_id=w.id AND a.status='running' WHERE t.id=?` + ) + .bind(f.taskId) + .first<{ + id: string; + agent_credential_generation: number; + workspace_id: string; + callback_generation: string | null; + }>(); + const nextToken = await signCallbackToken(running!.workspace_id, testEnv, { + callbackGeneration: running!.callback_generation, + }); + const rejectedAgain = await SELF.fetch( + `https://api.test.example.com/api/projects/${f.projectId}/tasks/${f.taskId}/status/callback`, + { + method: 'POST', + headers: { Authorization: `Bearer ${nextToken}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ...callbackCases[0]!.callback, + providerLimitAgentSessionId: running!.id, + providerLimitCredentialGeneration: running!.agent_credential_generation, + providerLimitPromptAttemptId: 99, + }), + } + ); + expect(rejectedAgain.status, await rejectedAgain.text()).toBe(200); + const parkedAgain = await env.DATABASE.prepare( + 'SELECT admission_state,provider_limit_wait_json FROM tasks WHERE id=?' + ) + .bind(f.taskId) + .first<{ admission_state: string; provider_limit_wait_json: string }>(); + expect(parkedAgain!.admission_state).toBe('provider_limit_waiting'); + const freshWait = parseProviderLimitWait(parkedAgain!.provider_limit_wait_json)!; + expect(freshWait.ownerOverride).toBeUndefined(); + expect(freshWait.scheduleKey).not.toBe(waitBefore.scheduleKey); + }, + 30_000 + ); +}); diff --git a/apps/web/src/components/ProviderLimitResume.tsx b/apps/web/src/components/ProviderLimitResume.tsx index 77ee6b0ba8..cc187c48a3 100644 --- a/apps/web/src/components/ProviderLimitResume.tsx +++ b/apps/web/src/components/ProviderLimitResume.tsx @@ -12,6 +12,13 @@ const ACTIONS = { done: 'Waking…', failed: 'Unable to resume task. Try again.', }, + 'resume-anyway': { + run: startProviderLimitTaskAnyway, + idle: 'Resume anyway', + pending: 'Resuming…', + done: 'Waking…', + failed: 'Unable to resume this session. Try again.', + }, 'start-anyway': { run: startProviderLimitTaskAnyway, idle: 'Start anyway', @@ -23,7 +30,7 @@ const ACTIONS = { /** * One explicit owner action on a provider-limit hold: resume a blocked wait, or start a - * never-started task now despite the limit. Accepted actions stay disabled until fresh + * never-started task or resume a saved waiting session despite the limit. Accepted actions stay disabled until fresh * server state arrives. */ export function ProviderLimitResume({ @@ -54,7 +61,7 @@ export function ProviderLimitResume({ } return ( -
+
diff --git a/apps/web/src/components/inbox/useInbox.ts b/apps/web/src/components/inbox/useInbox.ts index 55ad3c5343..2da1c684d6 100644 --- a/apps/web/src/components/inbox/useInbox.ts +++ b/apps/web/src/components/inbox/useInbox.ts @@ -9,6 +9,7 @@ import { inboxItemQueryOptions, inboxListQueryOptions, inboxQueryKeys, + projectOverviewQueryKeys, } from '../../lib/query-options'; import { isRenderableInboxItem } from './inbox-model'; @@ -63,13 +64,18 @@ export function useInboxItem(projectId: string | null, ref: string | null) { }); } -/** Refetch every inbox list and count (after an answer or an archive). */ +/** + * Refetch every inbox list and count (after an answer or an archive), and the Project Overview's + * read: whether a chat is paused on its person is part of it (Running now's "Paused on this"), so + * coming back to the Overview after answering must not show the chat still waiting (slice F2). + */ export function useInvalidateInbox() { const scope = useQueryScope(); const queryClient = useQueryClient(); return useCallback(() => { if (!scope) return; void queryClient.invalidateQueries({ queryKey: inboxQueryKeys.all(scope) }); + void queryClient.invalidateQueries({ queryKey: projectOverviewQueryKeys.all(scope) }); }, [queryClient, scope]); } diff --git a/apps/web/src/components/inbox/useInboxWalk.ts b/apps/web/src/components/inbox/useInboxWalk.ts index 7cb50e5693..dab7e6fe72 100644 --- a/apps/web/src/components/inbox/useInboxWalk.ts +++ b/apps/web/src/components/inbox/useInboxWalk.ts @@ -1,7 +1,8 @@ import type { InboxItem } from '@simple-agent-manager/shared'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { useSearchParams } from 'react-router'; +import { useLocation, useSearchParams } from 'react-router'; +import { INBOX_FROM_PARAM } from '../../lib/project-routes'; import { isStaleInboxError } from './inbox-actions'; import { type InboxView, nextAfter, parseInboxView, walkOrder } from './inbox-model'; import type { InboxReceipt } from './InboxItemView'; @@ -33,6 +34,10 @@ export function useInboxWalk({ isMobile: boolean; }) { const [params, setParams] = useSearchParams(); + const location = useLocation(); + // A replace keeps the entry's history state (it is the same entry); a push starts clean. + const entryStateRef = useRef(location.state); + entryStateRef.current = location.state; const view = parseInboxView(params.get('filter')); const itemParam = params.get('item'); const projectParam = projectId ?? params.get('project'); @@ -105,7 +110,7 @@ export function useInboxWalk({ } return next; }, - { replace } + { replace, state: replace ? entryStateRef.current : undefined } ); }, [projectId, setParams] @@ -120,6 +125,9 @@ export function useInboxWalk({ else out.set('filter', next); out.delete('item'); out.delete('project'); + // Browsing the inbox by chip: Back from the next item returns to the list, not to the + // page that opened the first one. + out.delete(INBOX_FROM_PARAM); return out; }, { replace: true } diff --git a/apps/web/src/lib/project-route-prefetch.ts b/apps/web/src/lib/project-route-prefetch.ts index ffbfa2f29f..d93ea50e49 100644 --- a/apps/web/src/lib/project-route-prefetch.ts +++ b/apps/web/src/lib/project-route-prefetch.ts @@ -5,9 +5,12 @@ import { type ChatSessionListItem, listChatSessions } from './api'; import { CHAT_SESSION_LIST_LIMIT } from './chat-query-config'; import { chatSessionMessagesQueryOptions, + inboxListQueryOptions, projectChatSessionsQueryOptions, projectDetailQueryOptions, + projectOverviewQueryOptions, } from './query-options'; +import { isProjectOverviewRoute } from './shell-routes'; /** * The project chat sidebar's first session-list read. @@ -91,12 +94,18 @@ export function prefetchProjectRoute( void queryClient.prefetchQuery(projectDetailQueryOptions(queryScope, projectId)); + // The project index lands on the Overview (inbox slice F2): its aggregated read and the + // first page of Needs you, the same entries the page reads. + if (isProjectOverviewRoute(pathname)) { + void queryClient.prefetchQuery(projectOverviewQueryOptions(queryScope, projectId)); + void queryClient.prefetchInfiniteQuery( + inboxListQueryOptions(queryScope, projectId, 'needs_you') + ); + return; + } + const selected = matchPath('/projects/:id/chat/:sessionId', pathname); - const chatRoute = - selected ?? - matchPath('/projects/:id/chat', pathname) ?? - // The project index redirects to its chat. - matchPath('/projects/:id', pathname); + const chatRoute = selected ?? matchPath('/projects/:id/chat', pathname); if (!chatRoute) return; void queryClient.prefetchQuery(initialChatSessionListQueryOptions(queryScope, projectId)); diff --git a/apps/web/src/lib/project-routes.ts b/apps/web/src/lib/project-routes.ts index 23f459758c..06a6f468fd 100644 --- a/apps/web/src/lib/project-routes.ts +++ b/apps/web/src/lib/project-routes.ts @@ -15,6 +15,30 @@ const projectRoot = (projectId: string) => `/projects/${encodeURIComponent(proje /** The project itself (its default view). */ export const projectPath = (projectId: string) => projectRoot(projectId); +/** The project's Overview, its landing page (`projectPath` redirects here). */ +export const projectOverviewPath = (projectId: string) => `${projectRoot(projectId)}/overview`; + +/** + * Query parameter on an inbox item URL saying where it was opened from, so the item view's Back + * returns there. `useInboxWalk` copies every parameter when it moves between items, so the value + * survives answering, stepping and archiving. + */ +export const INBOX_FROM_PARAM = 'from'; +export const INBOX_FROM_OVERVIEW = 'overview'; + +/** + * History state on an inbox entry whose previous history entry is the Overview: the Overview + * pushed it. Moving between items replaces the entry and keeps the state; opening another item + * pushes a new entry without it. Back pops only while it is set, so it can never pop to an item. + */ +export const OVERVIEW_BEHIND_STATE = 'samOverviewBehind'; + +/** One item in the project inbox's item view, opened from the Overview's Needs you. */ +export const projectInboxItemFromOverviewPath = (projectId: string, ref: string) => { + const params = new URLSearchParams({ item: ref, [INBOX_FROM_PARAM]: INBOX_FROM_OVERVIEW }); + return `${projectRoot(projectId)}/inbox?${params.toString()}`; +}; + /** A chat in the project: the chats automations start, and the chats linked work points at. */ export const projectChatPath = (projectId: string, sessionId: string) => `${projectRoot(projectId)}/chat/${encodeURIComponent(sessionId)}`; diff --git a/apps/web/src/lib/shell-routes.ts b/apps/web/src/lib/shell-routes.ts index 8e0981c8d0..7a07d3ee2f 100644 --- a/apps/web/src/lib/shell-routes.ts +++ b/apps/web/src/lib/shell-routes.ts @@ -1,8 +1,8 @@ /** * Routes that lay out their own SAM Glass panes over the void (the project chat, the agent * chat, the comment reader, the project Overview (sections are panes with a task box pinned - * under them) and the inbox at both scopes). Every other routed page renders inside one content pane that - * the app shell provides. + * under them) together with the project index that redirects to it, and the inbox at both + * scopes). Every other routed page renders inside one content pane that the app shell provides. * * Shared by `AppShell` (whether to wrap the outlet in a pane) and `Project` (whether to skip * the padded page layout), so the two can never disagree about which routes are full-bleed. @@ -10,12 +10,21 @@ export function isFullBleedRoute(pathname: string): boolean { return ( /^\/projects\/[^/]+\/(chat|agent|overview|inbox)(\/|$)/.test(pathname) || + isProjectOverviewRoute(pathname) || /^\/inbox\/?$/.test(pathname) || /^\/projects\/[^/]+\/comments\/[^/]+\/[^/]+\/?$/.test(pathname) ); } -/** The project routes that render the project chat: its index (a redirect) and `chat/*`. */ +/** The project routes that render the project chat: `chat` and `chat/*`. */ export function isProjectChatRoute(pathname: string): boolean { - return /\/projects\/[^/]+(?:\/chat(?:\/|$)|\/?$)/.test(pathname); + return /\/projects\/[^/]+\/chat(?:\/|$)/.test(pathname); +} + +/** + * The project routes that render the Overview: `overview`, and the project index, which + * redirects to it (inbox slice F2: opening a project lands on its Overview). + */ +export function isProjectOverviewRoute(pathname: string): boolean { + return /^\/projects\/(?!new\/?$|invite(?:\/|$))[^/]+(?:\/overview)?\/?$/.test(pathname); } diff --git a/apps/web/src/pages/TaskRedirect.tsx b/apps/web/src/pages/TaskRedirect.tsx index 554bb6a2d1..cf7048fb55 100644 --- a/apps/web/src/pages/TaskRedirect.tsx +++ b/apps/web/src/pages/TaskRedirect.tsx @@ -3,6 +3,7 @@ import { useEffect, useState } from 'react'; import { Navigate, useParams } from 'react-router'; import { getTaskSessions } from '../lib/api'; +import { projectChatPath, projectPath } from '../lib/project-routes'; import { useProjectContext } from './ProjectContext'; /** @@ -45,9 +46,9 @@ export function TaskRedirect() { ); } - const target = sessionId - ? `/projects/${projectId}/chat/${sessionId}` - : `/projects/${projectId}/chat`; + // A task with a chat opens that chat; one without (never started) opens its project's + // Overview, where its failure or Running now row is (inbox slice F2). + const target = sessionId ? projectChatPath(projectId, sessionId) : projectPath(projectId); return ; } diff --git a/apps/web/src/pages/inbox/InboxPage.tsx b/apps/web/src/pages/inbox/InboxPage.tsx index 4f4cb9ae2a..3cbdd6507b 100644 --- a/apps/web/src/pages/inbox/InboxPage.tsx +++ b/apps/web/src/pages/inbox/InboxPage.tsx @@ -1,8 +1,8 @@ import type { InboxItem } from '@simple-agent-manager/shared'; import { Button, IconButton, Pane, Spinner } from '@simple-agent-manager/ui'; import { Archive, ArrowLeft, ChevronLeft, ChevronRight, MessageSquare } from 'lucide-react'; -import { useEffect, useMemo, useRef } from 'react'; -import { useNavigate } from 'react-router'; +import { useCallback, useEffect, useMemo, useRef } from 'react'; +import { useLocation, useNavigate, useSearchParams } from 'react-router'; import { useInboxPermissionDetail } from '../../components/inbox/inbox-actions'; import { buildRows, hasPinnedControls, stackPosition } from '../../components/inbox/inbox-model'; @@ -22,10 +22,38 @@ import { useInboxCount } from '../../components/inbox/useInbox'; import { useInboxWalk } from '../../components/inbox/useInboxWalk'; import { useIsMobile } from '../../hooks/useIsMobile'; import { useMinuteClock } from '../../hooks/useMinuteClock'; -import { projectChatPath } from '../../lib/project-routes'; +import { + INBOX_FROM_OVERVIEW, + INBOX_FROM_PARAM, + OVERVIEW_BEHIND_STATE, + projectChatPath, + projectOverviewPath, +} from '../../lib/project-routes'; type Walk = ReturnType; +/** + * An item opened from the project Overview's Needs you (`?from=overview`): Back goes to the + * Overview, in-app, so the page is not reloaded and shows the reduced count from the shared inbox + * queries. When this history entry sits right on top of the Overview's (`OVERVIEW_BEHIND_STATE`: + * the Overview pushed it and the walk has only replaced it since), Back pops it; otherwise (a + * second item opened from the list, a fresh tab) it replaces this entry with the Overview. + */ +function useReturnToOverview(projectId: string | null) { + const [params] = useSearchParams(); + const navigate = useNavigate(); + const location = useLocation(); + const fromOverview = Boolean(projectId) && params.get(INBOX_FROM_PARAM) === INBOX_FROM_OVERVIEW; + const overviewBehind = + (location.state as Record | null)?.[OVERVIEW_BEHIND_STATE] === true; + const returnToOverview = useCallback(() => { + if (!projectId) return; + if (overviewBehind) navigate(-1); + else navigate(projectOverviewPath(projectId), { replace: true }); + }, [navigate, overviewBehind, projectId]); + return { fromOverview, returnToOverview }; +} + /** The open item: top bar, receipt, scrolling body and pinned answer controls. */ /** Focus the list row that holds `ref` (the row of its stack), after Back on a phone. */ function focusRow(ref: string) { @@ -45,12 +73,15 @@ function ItemPane({ item, now, focusOnMount, + onBackToOverview, }: { walk: Walk; item: InboxItem; now: number; /** An item opened by the person (not desktop's default first item) takes focus at once. */ focusOnMount: boolean; + /** Set when the item was opened from the Overview: Back returns there, on both sizes. */ + onBackToOverview: (() => void) | null; }) { const navigate = useNavigate(); const headingRef = useRef(null); @@ -81,16 +112,27 @@ function ItemPane({ return ( <>
- } - onClick={() => { - walk.close(); - focusRow(item.ref); - }} - showTooltip={false} - className="md:hidden" - /> + {onBackToOverview ? ( + // Desktop has the header's "Back to Overview" beside the list; one control per screen. + } + onClick={onBackToOverview} + showTooltip={false} + className="md:hidden" + /> + ) : ( + } + onClick={() => { + walk.close(); + focusRow(item.ref); + }} + showTooltip={false} + className="md:hidden" + /> + )}

Inbox

+ {fromOverview && ( + + )}
) : ( void; profilePicker: UseProfilePickerResult; @@ -140,6 +145,7 @@ export function ChatInput({ projectId, agents, agentProfiles, + profilesLoading = false, selectedProfileId, onProfileChange, profilePicker, @@ -188,9 +194,11 @@ export function ChatInput({ const selectedProfile = selectedProfileId ? (agentProfiles.find((p) => p.id === selectedProfileId) ?? null) : null; - const needsProfileBeforeSubmit = agentProfiles.length === 0 && agents.length >= 1; + const needsProfileBeforeSubmit = + !profilesLoading && agentProfiles.length === 0 && agents.length >= 1; const noAgents = agents.length === 0; - const inputDisabled = noAgents || needsProfileBeforeSubmit || profileWizard.open; + const inputDisabled = + noAgents || needsProfileBeforeSubmit || profileWizard.open || Boolean(profilesLoading); const showToolbar = !inputDisabled && agentProfiles.length > 0; const composerPlaceholder = getComposerPlaceholder({ noAgents, diff --git a/apps/web/src/pages/project-chat/useProfileChoice.ts b/apps/web/src/pages/project-chat/useProfileChoice.ts index e3a7779072..eaa8034844 100644 --- a/apps/web/src/pages/project-chat/useProfileChoice.ts +++ b/apps/web/src/pages/project-chat/useProfileChoice.ts @@ -74,6 +74,7 @@ export function useProfileChoice({ }>) { const { profiles: agentProfiles, + loading: profilesLoading, createProfile: createProfileMutation, updateProfile, } = useAgentProfiles(projectId, queryScope); @@ -208,6 +209,8 @@ export function useProfileChoice({ return { agentProfiles, + /** The first read of the project's profiles is still in flight (no list yet). */ + profilesLoading, selectedProfileId, setSelectedProfileId, profilePicker, diff --git a/apps/web/src/pages/project-overview/NeedsYouSection.tsx b/apps/web/src/pages/project-overview/NeedsYouSection.tsx new file mode 100644 index 0000000000..9fd8065e54 --- /dev/null +++ b/apps/web/src/pages/project-overview/NeedsYouSection.tsx @@ -0,0 +1,216 @@ +/** + * "Needs you" on the Project Overview (inbox slice F2, spec idea 01M7G03ZCQ6TM6CMEYDRKQ8ST9 + * section 4.2): the first rows of this project's inbox for the viewer, in inbox order, with the + * count and a link to the project inbox. It is the inbox itself, not a copy: the same queries + * (`useInboxList` / `useInboxCount`, refreshed by the notification socket, no polling), the same + * rows (`InboxRow`, `buildRows`) and the same item view, which a row opens. + */ +import type { InboxItem } from '@simple-agent-manager/shared'; +import { Pane } from '@simple-agent-manager/ui'; +import { ChevronRight } from 'lucide-react'; +import { useCallback, useEffect, useMemo } from 'react'; +import { Link, useNavigate } from 'react-router'; + +import { buildRows, isPausedOnItem } from '../../components/inbox/inbox-model'; +import { InboxRow } from '../../components/inbox/InboxRow'; +import { useInboxCount, useInboxList } from '../../components/inbox/useInbox'; +import { useIsMobile } from '../../hooks/useIsMobile'; +import { useMinuteClock } from '../../hooks/useMinuteClock'; +import { OVERVIEW_BEHIND_STATE, projectInboxItemFromOverviewPath } from '../../lib/project-routes'; +import { Section, SectionHead } from './sections'; + +/** + * Chats paused on one of the viewer's open inbox items, from the loaded list. `complete` is false + * when the list has further pages the Overview did not fetch (more than one page of items): a + * paused item may then sit past the first page, so the Overview read's own flag still counts. + */ +export interface ViewerPausedChats { + ids: ReadonlySet; + complete: boolean; +} + +/** Rows shown before "All N": three keep Running now on a phone's first screen. */ +export const NEEDS_YOU_ROWS_PHONE = 3; +export const NEEDS_YOU_ROWS_DESKTOP = 5; + +/** + * This project's open inbox items for the viewer, and the chats they pause. Read once by the + * Overview and handed to Needs you and Running now, so the two sections word the same chat the + * same way ("paused on this"). + */ +export function useNeedsYou(projectId: string) { + const list = useInboxList(projectId, 'needs_you'); + const count = useInboxCount(projectId); + const complete = list.loaded && !list.hasNextPage; + const pausedSessionIds = useMemo(() => { + if (!list.loaded) return null; + const ids = new Set(); + for (const item of list.items) { + if (item.sessionId && isPausedOnItem(item)) ids.add(item.sessionId); + } + return { ids, complete }; + }, [list.items, list.loaded, complete]); + return useMemo(() => ({ list, count, pausedSessionIds }), [list, count, pausedSessionIds]); +} + +export type NeedsYou = ReturnType; + +/** Approximate height of one row, so a loading list reserves its space instead of jumping. */ +const ROW_HEIGHT_PX = 64; + +/** + * The item last opened from Needs you. Coming back to the Overview puts keyboard focus on its row + * (or, once it is answered and gone, on the section), as the inbox's own Back does for its list. + * Kept until the list has settled after the return: the cached list can still hold an answered + * item while its refetch is in flight. + */ +let returnFocusRef: string | null = null; + +/** `data-focus-target` of the Needs you section, in whichever form it is rendered. */ +const FOCUS_TARGET = 'needs-you'; + +/** + * Put focus where the person left. While the list is refetching, focus the row if it is still + * there and keep the target; once settled, fall back to the section if the row is gone and focus + * has not moved on to something else, then forget the target. + */ +function restoreReturnFocus(settled: boolean) { + const ref = returnFocusRef; + const container = document.querySelector(`[data-focus-target="${FOCUS_TARGET}"]`); + if (!ref || !container) return; + const row = [...container.querySelectorAll('[data-inbox-refs]')].find((candidate) => + (candidate.dataset.inboxRefs ?? '').split(' ').includes(ref) + ); + if (row) { + if (document.activeElement !== row) row.focus(); + } else if (settled) { + const active = document.activeElement; + if (!active || active === document.body || container.contains(active)) container.focus(); + } + if (settled) returnFocusRef = null; +} + +/** The section when there is no list to show: one quiet line, not an empty panel. */ +function QuietLine({ + projectId, + text, + className, + announce, +}: { + projectId: string; + text: string; + className: string; + /** Announce the text (a settled answer); a loading line stays silent. */ + announce: boolean; +}) { + return ( + +

Needs you

+

+ {text} +

+ + Inbox +
+ ); +} + +export function NeedsYouSection({ + projectId, + needsYou, + className = '', +}: { + projectId: string; + needsYou: NeedsYou; + className?: string; +}) { + const isMobile = useIsMobile(); + const now = useMinuteClock(); + const navigate = useNavigate(); + const { list, count } = needsYou; + const rows = useMemo(() => buildRows(list.items), [list.items]); + const limit = isMobile ? NEEDS_YOU_ROWS_PHONE : NEEDS_YOU_ROWS_DESKTOP; + const shown = rows.slice(0, limit); + const open = useCallback( + (item: InboxItem) => { + returnFocusRef = item.ref; + // The inbox item view's Back pops back here while this state is on its entry. + navigate(projectInboxItemFromOverviewPath(projectId, item.ref), { + state: { [OVERVIEW_BEHIND_STATE]: true }, + }); + }, + [navigate, projectId] + ); + // Back from an item: put focus where the person left, following the list until it settles. + const settled = list.loaded && !list.isFetching; + useEffect(() => { + if (list.loaded) restoreReturnFocus(settled); + }, [list.loaded, list.items, settled]); + + const expected = count.data?.needsYou ?? 0; + if (!list.loaded && !list.error && expected > 0) { + // The count already says there are items: hold their space so nothing below jumps. + return ( +
+ +
+
+ ); + } + + if (rows.length === 0) { + const text = list.loaded + ? 'Nothing needs you.' + : list.error + ? 'Couldn’t load what needs you. It will retry.' + : 'Checking what needs you…'; + return ( + + ); + } + + // The count route counts what the viewer can act on; until it answers, the list stands in. + const total = count.data?.needsYou ?? list.items.length; + const inbox = `/projects/${projectId}/inbox`; + return ( +
+ +
    + {shown.map((row) => ( + + ))} +
+
+ ); +} diff --git a/apps/web/src/pages/project-overview/OverviewTaskBox.tsx b/apps/web/src/pages/project-overview/OverviewTaskBox.tsx index 0147e9f98a..6e2781dbb0 100644 --- a/apps/web/src/pages/project-overview/OverviewTaskBox.tsx +++ b/apps/web/src/pages/project-overview/OverviewTaskBox.tsx @@ -154,6 +154,7 @@ export function OverviewTaskBox({ projectId={projectId} agents={composer.configuredAgents} agentProfiles={composer.agentProfiles} + profilesLoading={profileChoice.profilesLoading} selectedProfileId={composer.selectedProfileId} onProfileChange={profileChoice.setSelectedProfileId} profilePicker={profileChoice.profilePicker} diff --git a/apps/web/src/pages/project-overview/index.tsx b/apps/web/src/pages/project-overview/index.tsx index 26060d4a39..573472b0ac 100644 --- a/apps/web/src/pages/project-overview/index.tsx +++ b/apps/web/src/pages/project-overview/index.tsx @@ -3,36 +3,70 @@ * running, what the accounts have left, which automations are broken, what happened recently, * and a task box that starts work without leaving the page. * + * It is the project's landing page (inbox slice F2): `/projects/:id` redirects here, and chat is + * one tap away (the Chat nav item on desktop, the Chat control in the phone app bar). + * * Layout (`OverviewLayout`): one DOM tree that CSS arranges, so crossing the phone/desktop * breakpoint never remounts the task box or a section (`apps/web/.claude/rules/48`, rule 5). * - Phone: one scrolling column in `PHONE_ORDER`, the task box pinned under it. - * - Desktop: a wide `main` column with the task box pinned under it, and a `rail`. - * - * Later slices: F2 adds the brief and Needs you. They go at the top of `main`, Running now and - * Recently move to the `rail`, and `PHONE_ORDER` puts Needs you first. Each is a slot - * assignment below; no section needs to change. + * - Desktop: a wide `main` column (the brief slot, then Needs you) with the task box pinned under + * it, and a `rail` (Running now, This week, Budgets, Automations, Recently). */ -import type { ReactNode } from 'react'; +import { MessageSquare } from 'lucide-react'; +import { type ReactNode, useEffect, useMemo } from 'react'; +import { useNavigate } from 'react-router'; +import { useAppShell } from '../../components/AppShell'; import { useProfileUsages } from '../../components/project-chat/profile-picker'; +import { useIsMobile } from '../../hooks/useIsMobile'; import { useNewChatComposer } from '../project-chat/useNewChatComposer'; import { useProjectContext } from '../ProjectContext'; import { AutomationsSection } from './AutomationsSection'; import { BudgetsSection } from './BudgetsSection'; +import { NeedsYouSection, useNeedsYou } from './NeedsYouSection'; import { OverviewTaskBox } from './OverviewTaskBox'; import { RecentlySection, RunningNowSection } from './sections'; import { ThisWeekSection } from './ThisWeekSection'; import { useProjectOverview } from './useProjectOverview'; -/** Phone order of the sections, as Tailwind `order-*` classes (desktop ignores them). */ +/** + * Phone order of the sections, as Tailwind `order-*` classes (desktop ignores them). The Insights + * build's This week pane sits directly under Running now. + */ const PHONE_ORDER = { - running: 'order-1 md:order-none', - thisWeek: 'order-2 md:order-none', - budgets: 'order-3 md:order-none', - automations: 'order-4 md:order-none', - recently: 'order-5 md:order-none', + needsYou: 'order-1 md:order-none', + running: 'order-2 md:order-none', + thisWeek: 'order-3 md:order-none', + budgets: 'order-4 md:order-none', + automations: 'order-5 md:order-none', + recently: 'order-6 md:order-none', } as const; +/** + * Chat, one tap from the landing page: on a phone it takes the app bar's primary slot (the + * project chat puts its own chat-list toggle there). Desktop has the Chat nav item. + */ +function usePhoneChatControl(projectId: string) { + const isMobile = useIsMobile(); + const navigate = useNavigate(); + const { setScreenAction } = useAppShell(); + const action = useMemo( + () => + isMobile + ? { + label: 'Chat', + icon: , + onClick: () => navigate(`/projects/${projectId}/chat`), + } + : null, + [isMobile, navigate, projectId] + ); + useEffect(() => { + setScreenAction(action); + return () => setScreenAction(null); + }, [action, setScreenAction]); +} + const GUTTER = 'gap-[var(--sam-space-gutter)]'; /** @@ -79,6 +113,8 @@ export function OverviewLayout({ export function ProjectOverview() { const { projectId } = useProjectContext(); const overview = useProjectOverview(projectId); + const needsYou = useNeedsYou(projectId); + usePhoneChatControl(projectId); const composer = useNewChatComposer(); // The same usage the task box's ring shows; Budgets reads it rather than fetching again. const profileUsages = useProfileUsages(composer.agentProfiles, projectId, true); @@ -88,16 +124,37 @@ export function ProjectOverview() { return ( + {/* BRIEF SLOT (inbox slice I, spec 4.3): the generated brief renders here, above Needs + you. Nothing renders here until then: no placeholder. */} + + + } + rail={ <> + {/* Insights slice F: the week's flow, linking into Insights. Under Running now. */} + + + } - rail={ - <> - {/* Insights slice F: the week's flow, linking into Insights. Top of the rail. */} - - - - - } taskBox={ {children} @@ -89,13 +95,30 @@ export function SectionNote({ children }: { children: ReactNode }) { return

{children}

; } -function RunningIcon({ chat }: { chat: OverviewRunningChat }) { - if (chat.state === 'waiting') { +/** + * Whether the chat is paused on something the viewer must answer. The viewer's own inbox decides + * (`viewerPaused`, from the Needs you list), so Running now and Needs you word the same chat the + * same way (inbox slice F2). The Overview read's own flag stands in until that list has loaded, + * and also counts while the list has unfetched pages (its item may be past the first page). + */ +export function isPausedOnViewer( + chat: OverviewRunningChat, + viewerPaused: ViewerPausedChats | null +): boolean { + if (chat.state === 'starting') return false; + const readSaysYou = chat.state === 'waiting' && chat.waitingOnViewer; + if (!viewerPaused) return readSaysYou; + if (viewerPaused.ids.has(chat.sessionId)) return true; + return !viewerPaused.complete && readSaysYou; +} + +function RunningIcon({ chat, pausedOnYou }: { chat: OverviewRunningChat; pausedOnYou: boolean }) { + if (pausedOnYou || chat.state === 'waiting') { return (