diff --git a/src/mms/MmsProfileServices.ts b/src/mms/MmsProfileServices.ts index 47e2444c5e..579ef8e3d2 100644 --- a/src/mms/MmsProfileServices.ts +++ b/src/mms/MmsProfileServices.ts @@ -1955,6 +1955,9 @@ export class MmsProfileServices { this.personalBots?.threadRunEnded(payload.threadId) this.threadWakes.threadRunEnded(payload.threadId) }) + // Retry clears why a thread's worktree could not be set up: a bot's job still open on its failed run (a restart lost + // the run's end) reads it first and ends with why, and the retried run's work opens a follow-up job. + this.orchestrator.on('setup-retry', (payload: { threadId: string }) => this.personalBots?.checkJobs(payload.threadId)) // Any Stop that reaches a thread, and every subagent below it, ends its watch at once. this.orchestrator.on('threads-stopped', (payload: { threadIds: string[] }) => this.pullRequestWatch.onStopped(payload.threadIds)) // An archived thread's watch ends as archived, not as stopped (`OrchestratorService.archiveThread`). diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 17dfd19357..1a1d6f38c6 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -47,8 +47,8 @@ import { botDeviceAllowed, DEFAULT_BOT_DEVICE_ACCESS } from '../../../shared/bot import { BOT_COMMANDS_OPEN, BOT_HELD_POWER_TEXT, subagentHold, type BotHeldPower, type BotRuntimeHold, type BotSubagentHold } from '../../../shared/bots/personal/subagentHold' import type { BotAuthority, BotCheck, BotCheckDenied, BotMcpTool, BotSubagents, BotSubagentView, BotThreadRole, BotThreads, NormalisedCall, WallReason } from '../../../shared/bots/personal/authority' import { launchedActive, type BotChatMessage, type BotChip, type BotError, type BotLaunchedThread, type BotPermissionItem } from '../../../shared/bots/personal/chat' -import { jobAskerOf, jobStateOf, jobStep, resultLine, type JobThreadView } from '../jobs' -import { BOT_JOB_ENDED, jobLine, jobNoticeInput, jobNoticeLabel, relatedJobsLine, THREAD_MESSAGE_KEY_PREFIX, threadMessageInput, threadMessageLabel, type BotJob, type BotJobState } from '../../../shared/bots/personal/jobs' +import { endedLine, jobAskerOf, jobStateOf, jobStep, type JobThreadView } from '../jobs' +import { BOT_JOB_ENDED, jobLine, jobNoticeInput, jobNoticeLabel, relatedJobsLine, THREAD_MESSAGE_KEY_PREFIX, threadMessageInput, threadMessageLabel, type BotJob, type BotJobState, type JobSetupFailure } from '../../../shared/bots/personal/jobs' import { threadLink } from '../../../shared/threadLink' import { isStricter, narrowPermissionMode, type PermissionMode } from '../../../shared/permissionMode' import { @@ -10384,6 +10384,27 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } } + /** + * The run that started job `jobId` never started its agent: setting up its thread's worktree failed (`thread_create` + * follows the run it started instead of waiting on it). The job ends as failed with why, once: a job that already + * moved on its own (`checkJobs` read the failure when the run ended) or ended is left as it is. A Retry that already + * started a newer run does not hide this run's failure; that run's work opens a follow-up job (`followUpJob`). + * Never throws. + */ + jobSetupFailed(botId: string, jobId: string, failure: JobSetupFailure): void { + let job: BotJob | undefined + try { + job = this.store.job(jobId) + } catch { + return + } + if (!job || job.botId !== botId || job.endedAt || BOT_JOB_ENDED.has(job.state)) return + const seen: JobThreadView = { status: 'failed', setupFailure: failure } + void this.deliverJobNotice(job, 'failed', endedLine(seen), seen).catch((error: unknown) => { + console.warn('a bot job\'s notice could not be delivered', { jobId, error: error instanceof Error ? error.message : String(error) }) + }) + } + /** The jobs not ended on `threadId` look at their thread now. Never throws. */ checkJobs(threadId: string): void { // The local thread store has no view of a remote worker. Its absence here doesn't prove the worker stopped. @@ -10424,7 +10445,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { private stepJob(job: BotJob, seen: JobThreadView): void { const step = jobStep(job, jobStateOf(seen.status)) if (!step) return - const line = BOT_JOB_ENDED.has(step.state) ? resultLine(seen.result) : undefined + const line = BOT_JOB_ENDED.has(step.state) ? endedLine(seen) : undefined if (!step.notice) { if (this.store.moveJob(job.id, job.state, step.state)) this.changed({ botId: job.botId }) return @@ -10447,7 +10468,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { return } const next: BotJob = { ...job, state, ...(line ? { line } : {}), ...(seen.title?.trim() ? { title: jobLine(seen.title, 200) } : {}) } - const input = jobNoticeInput(next, BOT_JOB_ENDED.has(state) ? { result: seen.result } : { asks: seen.asks, onHold: seen.status === 'on_hold' }) + const input = jobNoticeInput(next, BOT_JOB_ENDED.has(state) ? { result: seen.result, ...(seen.setupFailure ? { setupFailure: seen.setupFailure } : {}) } : { asks: seen.asks, onHold: seen.status === 'on_hold' }) const paused = Boolean(registry.pausedReason) const activationId = newActivationId() let refused: BotEngineError | undefined @@ -10458,7 +10479,9 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { if (!paused) refused = this.queueChatInTx(job.botId, `job:${job.id}:${activationId}`, input, activationId, this.jobDevice(job), { fast: state === 'needs_input' }) // Nothing shows in the chat: the notice is the bot's to act on, and only what it says reaches the owner. if (!paused && !refused) return true - this.chat.post({ id: `bm_job_${job.id}_${activationId}`, botId: job.botId, author: 'bot', kind: 'run_report', text: `${jobNoticeLabel(next)}: ${threadLink(job.threadId)}. I didn't follow up on this: ${paused ? 'I\'m paused.' : refused!.message}`, external: true, lane: 'chat' }) + // A run that never started says why, as the job's line keeps it: the owner sees it with no turn of the bot's. + const why = state === 'failed' && seen.setupFailure && line ? ` ${line}` : '' + this.chat.post({ id: `bm_job_${job.id}_${activationId}`, botId: job.botId, author: 'bot', kind: 'run_report', text: `${jobNoticeLabel(next)}: ${threadLink(job.threadId)}.${why} I didn't follow up on this: ${paused ? 'I\'m paused.' : refused!.message}`, external: true, lane: 'chat' }) return false }) if (started === undefined) return @@ -11078,6 +11101,11 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { }, jobs: { open: (botId, from, input) => this.openJob(botId, from, input), + setupFailed: (botId, jobId, failure) => this.jobSetupFailed(botId, jobId, failure), + launched: (botId, threadId) => { + const job = this.store.firstJobOn(botId, threadId) + return job ? { jobId: job.id } : undefined + }, message: (botId, threadId, input) => this.threadMessage(botId, threadId, input) }, wakes: { diff --git a/src/mms/bots/jobs.ts b/src/mms/bots/jobs.ts index fb4ced3259..58a89ea1cb 100644 --- a/src/mms/bots/jobs.ts +++ b/src/mms/bots/jobs.ts @@ -1,5 +1,5 @@ import type { BotLaunchedThread } from '../../shared/bots/personal/chat' -import { jobLine, type BotJob, type BotJobAsker, type BotJobState, type BotThreadAsk } from '../../shared/bots/personal/jobs' +import { jobLine, type BotJob, type BotJobAsker, type BotJobState, type BotThreadAsk, type JobSetupFailure } from '../../shared/bots/personal/jobs' import { modelFacingReplyText } from '../../shared/applets' import type { ChatMessage } from '../../shared/types' import type { BotActivationRow } from './store/BotStore' @@ -18,6 +18,8 @@ export interface JobThreadView { result?: string /** The thread's own requests waiting for a person (not its subagents'), oldest first, when it waits for one. */ asks?: BotThreadAsk[] + /** Why its last run never started: setting up its worktree failed (`Thread.setupFailure` of that run). */ + setupFailure?: JobSetupFailure } /** @@ -50,6 +52,14 @@ export function jobStep(job: Pick, next: BotJobState | undefine return { state: next, notice: next !== 'running' } } +/** + * The line a job keeps once its thread ended as `seen` says (`BotJob.line`): why its run never started when its worktree + * could not be set up (Mousse's plain reason, never Git's output), else the first line of its answer (`resultLine`). + */ +export function endedLine(seen: Pick): string | undefined { + return seen.setupFailure?.reason.trim() ? jobLine(seen.setupFailure.reason) : resultLine(seen.result) +} + /** A line that only lays the answer out: a heading, a rule, or a code fence. */ const LAYOUT_LINE = /^(?:#{1,6}(?:\s|$)|([-*_=])(?:\s*\1){2,}$|```|~~~)/ diff --git a/src/mms/bots/launchedThreads.ts b/src/mms/bots/launchedThreads.ts index 0d946083f8..e06a16bd18 100644 --- a/src/mms/bots/launchedThreads.ts +++ b/src/mms/bots/launchedThreads.ts @@ -24,6 +24,8 @@ export interface LaunchedThreadMeta { archivedAt?: string /** `Thread.lineage`: set on a subagent's thread, naming the thread that started it. */ lineage?: ThreadLineage + /** `Thread.setupFailure`: why its last message could not start (a job's notice says it). */ + setupFailure?: Thread['setupFailure'] } /** How a thread's last run ended, when none runs now: finished, failed, stopped (or cut off), or it never ran. */ @@ -355,7 +357,10 @@ export function jobThreadIn(profile: Parameters[0] & { // The reply that run ended on, by its id, never a progress message or an earlier turn's reply (`jobResultOf`). const result = run ? jobResultOf(profile.recorded?.(threadId, run.runId), profile.messages?.(threadId) ?? [], run.runId) : undefined const asks = listed.status === 'needs_input' ? profile.pending?.(threadId).map(threadAsk) : undefined - return { status: listed.status, ...(title ? { title } : {}), ...(result?.trim() ? { result } : {}), ...(asks?.length ? { asks } : {}) } + // That run never started: its worktree could not be set up, and the thread keeps why for that run (a Retry clears it). + const failure = listed.status === 'failed' && run && thread.setupFailure?.runId === run.runId ? thread.setupFailure : undefined + const setupFailure = failure ? { reason: failure.reason, ...(failure.detail ? { detail: failure.detail } : {}), retryable: failure.retryable } : undefined + return { status: listed.status, ...(title ? { title } : {}), ...(result?.trim() ? { result } : {}), ...(asks?.length ? { asks } : {}), ...(setupFailure ? { setupFailure } : {}) } } /** diff --git a/src/mms/bots/seams.ts b/src/mms/bots/seams.ts index d0b81aca81..766af1cb70 100644 --- a/src/mms/bots/seams.ts +++ b/src/mms/bots/seams.ts @@ -8,6 +8,7 @@ import type { BotModelRows, BotPickMiss } from '../../shared/bots/personal/model import type { BotQuestionAsk, BotQuestionStatus } from '../../shared/bots/personal/questions' import type { BotCard } from '../../shared/bots/personal/cards' import type { BotWakeEvent } from '../../shared/bots/personal/wakes' +import type { JobSetupFailure } from '../../shared/bots/personal/jobs' import type { BotSandboxPolicy } from '../../shared/bots/personal/sandbox' import type { BotJournalKind, BotJournalWho, BotMemoryEntry, BotMemoryForgetResult, BotMemoryListing } from '../../shared/bots/personal/memory' import type { Enforceability, ProviderSelection, RunPolicy } from '../../shared/harness/types' @@ -234,6 +235,16 @@ export interface BotToolHost { */ jobs?: { open(botId: string, from: string, input: { threadId: string; title: string; project?: string; sent: string }): { jobId: string } + /** + * The run that started job `jobId` never started its agent: its thread's worktree could not be set up. The job ends + * as failed with why, once, unless it already moved or ended. Absent: the caller waits for setup instead. + */ + setupFailed?(botId: string, jobId: string, failure: JobSetupFailure): void + /** + * The job the call that started `threadId` opened, ended or not, for a retry of that call (its first reply was lost): + * the same job as the first answer named. Undefined when it opened none. + */ + launched?(botId: string, threadId: string): { jobId: string } | undefined /** * A message thread `threadId`, which bot `botId` started, sends the bot while it works (`message_parent`): a notice * turn in the bot's chat, keyed by `requestKey` so a retry replays. Throws, with why in words for the thread, when diff --git a/src/mms/bots/store/BotStore.ts b/src/mms/bots/store/BotStore.ts index b8eb327dd4..3394ecc311 100644 --- a/src/mms/bots/store/BotStore.ts +++ b/src/mms/bots/store/BotStore.ts @@ -2306,6 +2306,12 @@ export class BotStore { return this.all('SELECT * FROM bot_jobs WHERE thread_id = ? AND ended_at IS NULL ORDER BY created_at', threadId).map(jobOf) } + /** The bot's first job on `threadId`, ended or not: the one the call that started the thread opened. */ + firstJobOn(botId: string, threadId: string): BotJob | undefined { + const row = this.get('SELECT * FROM bot_jobs WHERE bot_id = ? AND thread_id = ? ORDER BY created_at, rowid LIMIT 1', botId, threadId) + return row ? jobOf(row) : undefined + } + /** The bot's newest job on `threadId`, ended or not. */ latestJobOn(botId: string, threadId: string): BotJob | undefined { const row = this.get('SELECT * FROM bot_jobs WHERE bot_id = ? AND thread_id = ? ORDER BY created_at DESC, rowid DESC LIMIT 1', botId, threadId) diff --git a/src/mms/orchestrator/OrchestratorService.ts b/src/mms/orchestrator/OrchestratorService.ts index 6999bcab50..56c5563af2 100644 --- a/src/mms/orchestrator/OrchestratorService.ts +++ b/src/mms/orchestrator/OrchestratorService.ts @@ -11186,6 +11186,12 @@ export class OrchestratorService extends EventEmitter { rmSync(claimed, { force: true }) } if (typeof kept.content !== 'string' || !kept.content) throw new DomainRpcError('nothing_to_retry', 'The message to send again could not be read.', { threadId }) + // Whoever follows the failed run reads why before it is cleared (a bot's job, when a restart lost its earlier read). + try { + this.emit('setup-retry', { threadId }) + } catch (error) { + console.warn('a setup retry could not be told', { threadId, error: error instanceof Error ? error.message : String(error) }) + } this.threadStore.setThreadSetupFailure(threadId, undefined) const input: OrchestratorSendRequest = { content: kept.content, diff --git a/src/mms/run/mcp/appTools/thread.ts b/src/mms/run/mcp/appTools/thread.ts index aefe4cf05d..f0b0891beb 100644 --- a/src/mms/run/mcp/appTools/thread.ts +++ b/src/mms/run/mcp/appTools/thread.ts @@ -1177,6 +1177,41 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B return undefined } } + /** + * A retry of a personal bot's `thread_create` whose first reply was lost: the job that first call opened on the thread, + * so the retry names the same job. Nothing when the ledger is not here or kept none. + */ + const launchedJob = (threadId: string, ctx: ToolCallContext): { job: { jobId: string; next: string } } | undefined => { + const deps = bots?.() + const activation = deps?.host.activationOf(ctx.caller.threadId) + if (!deps?.host.jobs?.launched || !activation) return undefined + try { + const found = deps.host.jobs.launched(activation.botId, threadId) + return found ? { job: { jobId: found.jobId, next: BOT_JOB_NEXT } } : undefined + } catch { + return undefined + } + } + /** + * The first run of a thread a personal bot started, which job `jobId` of its ledger follows: the bot is answered without + * waiting for the thread's folder to be set up, and a worktree that could not be set up for that run ends the job as + * failed with why (`jobs.setupFailed`), once. False when the ledger can't take it: the caller waits for setup instead. + */ + const followJobSetup = (threadId: string, sent: { runId?: string; queued?: boolean; replayed?: boolean }, jobId: string, ctx: ToolCallContext): boolean => { + const deps = bots?.() + const jobs = deps?.host.jobs + const activation = deps?.host.activationOf(ctx.caller.threadId) + if (!jobs?.setupFailed || !activation || !host.waitForSetup) return false + // As `setupOf`: only a run that started now has a setup to follow. + if (!sent.runId || sent.queued || sent.replayed) return true + void host.waitForSetup(threadId, sent.runId).then((setup) => { + const failure = setup.status === 'failed' ? setup.failure : undefined + if (failure) jobs.setupFailed!(activation.botId, jobId, { reason: failure.reason, ...(failure.detail ? { detail: failure.detail } : {}), retryable: failure.retryable }) + }).catch((error: unknown) => { + console.warn('a bot thread\'s setup could not be followed', { threadId, error: error instanceof Error ? error.message : String(error) }) + }) + return true + } /** * The parent `message_parent` reaches from `threadId`: a subagent's parent thread, or the personal bot that started the * thread. Nothing else is a parent: a thread another agent launched with thread_create has none to message. @@ -2976,6 +3011,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B ? `${botRequestPrefix('thread_create', ctx.caller.threadId, ctx.turn.bot!.activationId)}${toolRequestId(args, ctx)}` : `thread_create:${ctx.caller.threadId}:${toolRequestId(args, ctx)}`) if (saved?.launch.threadId) return json({ + ...launchedJob(saved.launch.threadId, ctx), threadId: saved.launch.threadId, link: threadLink(saved.launch.threadId), replayed: true, ask: saved.launch.ask, attempt: requestKey }) let created: AgentCreatedThread @@ -3002,11 +3038,15 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B title: created.title, project: projectName(created.projectId) ?? undefined, sent: saved.launch.payload.firstMessage, ...(created.firstMessage?.sent === true ? {} : { uncertain: true }) }) - const job = saved + const opened = saved ? savedJob && { job: { ...savedJob, next: BOT_JOB_NEXT } } : firstSent ? botJob(created.threadId, created.title, created.projectId, args.firstMessage as string, ctx) : undefined + // A retry of the call names the job the first call opened. + const job = opened ?? (created.replayed ? launchedJob(created.threadId, ctx) : undefined) const told = job ?? (notify && firstSent ? await botNotify(created.threadId, created.title, args.firstMessage as string, ctx) : {}) - const setup = firstSent && created.firstMessage?.sent === true ? await setupOf(host, created.threadId, created.firstMessage) : {} + // A job the ledger keeps is the answer: the bot hears of a worktree that could not be set up in its job's notice. + const followed = firstSent && job && created.firstMessage?.sent === true && followJobSetup(created.threadId, created.firstMessage, job.job.jobId, ctx) + const setup = firstSent && created.firstMessage?.sent === true && !followed ? await setupOf(host, created.threadId, created.firstMessage) : {} return json({ ...told, ...setup, diff --git a/src/shared/bots/personal/jobs.ts b/src/shared/bots/personal/jobs.ts index cfa388b814..3294d431d0 100644 --- a/src/shared/bots/personal/jobs.ts +++ b/src/shared/bots/personal/jobs.ts @@ -72,6 +72,17 @@ export interface BotThreadAsk { questions: Array<{ id: string; text: string; options: Array<{ id: string; label: string }> }> } +/** + * Why a job's run never started (`JobThreadView.setupFailure`): setting up its thread's worktree failed. `reason` is + * Mousse's plain line (`setupFailureReason`), `detail` what Git said, `retryable` whether the thread kept the message + * for its Retry button (`Thread.setupFailure`). + */ +export interface JobSetupFailure { + reason: string + detail?: string + retryable: boolean +} + /** Most requests of a thread one notice shows (`jobNoticeInput`), oldest first. */ export const BOT_NOTICE_ASKS = 3 /** Most characters of one request a notice shows. */ @@ -158,17 +169,20 @@ function askText(ask: BotThreadAsk): string { * The text a job's notice turn starts with (a chat turn of the bot's own, `job::`): how the job stands, framed * as Mousse's, with the thread's words as data: its answer held to `BOT_REPORT_MAX_CHARS` once its turn ended * (`result`), or what it asks while it waits (`asks`, its own requests, at most `BOT_NOTICE_ASKS`). `onHold`: it waits - * on a pause only a person ends. What to tell the owner is the bot's call (the standing instructions); the turn may act - * on threads (`threadsActOf`). + * on a pause only a person ends. `setupFailure`: its run never started because its worktree could not be set up, with + * why. What to tell the owner is the bot's call (the standing instructions); the turn may act on threads (`threadsActOf`). */ -export function jobNoticeInput(job: BotJob, seen: { result?: string; asks?: readonly BotThreadAsk[]; onHold?: boolean } = {}): string { +export function jobNoticeInput(job: BotJob, seen: { result?: string; asks?: readonly BotThreadAsk[]; onHold?: boolean; setupFailure?: JobSetupFailure } = {}): string { const report = jobReport(job) const parts: NoticePart[] = [] const asks = job.state === 'needs_input' && !seen.onHold ? (seen.asks ?? []).slice(0, BOT_NOTICE_ASKS) : [] + const setup = job.state === 'failed' ? seen.setupFailure : undefined if (job.state === 'needs_input') parts.push(seen.onHold ? 'A thread you handed work to is paused; only your owner can resume it.' : asks.length ? 'A thread you handed work to asks:' : 'A thread you handed work to waits for a person (a question or an approval, in it or in a subagent of it).') else if (job.state === 'gone') parts.push('A thread you handed work to was deleted before it finished.') + else if (setup) + parts.push('A thread you handed work to did not start: its worktree could not be set up.') else parts.push(`A thread you handed work to finished its turn (${jobStateWords(job.state)}).`) for (const ask of asks) parts.push(quoted(`${ask.approval ? 'approval' : 'question'} ${ask.requestId}`, askText(ask))) @@ -176,7 +190,11 @@ export function jobNoticeInput(job: BotJob, seen: { result?: string; asks?: read parts.push(`Link: ${report.link}\nWho asked: ${jobAskerWords(job.askedBy)}.`) if (job.ownerAsk) parts.push(`Saved ask assigned to this job: ${job.ownerAsk}`) parts.push(quoted('the request', jobLine(job.request))) - if (seen.result?.trim()) parts.push(quoted('its answer', capReport(seen.result, 'read the rest with thread_read view "messages"').text)) + if (setup) { + parts.push(quoted('why it did not start', jobLine(setup.reason, 400))) + if (setup.detail?.trim()) parts.push(quoted('what Git said', jobLine(setup.detail, 400))) + parts.push(`The thread shows this reason${setup.retryable ? ' and a Retry button that sends the same message again' : ''}. Tell your owner in one line, with the link.`) + } else if (seen.result?.trim()) parts.push(quoted('its answer', capReport(seen.result, 'read the rest with thread_read view "messages"').text)) else if (job.state !== 'needs_input' && job.state !== 'gone') parts.push('It ended without a final answer: thread_read shows what happened (view "events" for why a run failed).') if (asks.length) parts.push("Answer what you can with request_answer; only a real owner's call goes to them, as your own short question.") return notice({ kind: 'job_update', reply: 'if-needed', ref: job.threadId }, parts) diff --git a/tests/bots/botJobs.test.ts b/tests/bots/botJobs.test.ts index 04efd95aff..7221c4db33 100644 --- a/tests/bots/botJobs.test.ts +++ b/tests/bots/botJobs.test.ts @@ -260,6 +260,76 @@ describe('the ledger in the bot engine', () => { expect(notices(jobId)).toBe(2) }) + describe('a thread whose worktree could not be set up: one failed notice with why, however the ledger hears of it', () => { + const failure = { reason: 'Couldn\'t make the thread\'s worktree.', detail: 'fatal: \'C:/w/t\' already exists', retryable: true } + const failedNotice = (jobId: string) => { + const turns = noticeTurns() + expect(turns).toHaveLength(1) + const input = (turns[0]!.trigger as { input: string }).input + expect(input).toContain('did not start: its worktree could not be set up') + expect(input).toContain(`\n${failure.reason}`) + expect(input).toContain('already exists') + expect(input).toContain('Retry button') + // The ledger keeps why as the job's line: Mousse's plain reason, not Git's output. + expect(f.store.job(jobId)).toMatchObject({ state: 'failed', endedAt: expect.any(String), line: failure.reason }) + expect(notices(jobId)).toBe(1) + } + + it('told by thread_create, even after a Retry started a newer run; the run\'s end seen later says nothing more', async () => { + const jobId = await handOff('Fix the login page in project Web', 't6', 'm6') + // The owner pressed Retry before the ledger read the thread: it works again on a newer run. + threads.set('t6', { status: 'running', title: 'Fix the login page' }) + f.bots.jobSetupFailed(botId, jobId, failure) + await flush() + failedNotice(jobId) + threads.set('t6', { status: 'failed', title: 'Fix the login page', setupFailure: failure }) + f.bots.threadRunEnded('t6') + f.bots.jobSetupFailed(botId, jobId, failure) + await flush() + expect(noticeTurns()).toHaveLength(1) + }) + + it('seen when the run ended (thread_create\'s reply was lost, or the app restarted); thread_create\'s word after it says nothing more', async () => { + const jobId = await handOff('Fix the login page in project Web', 't7', 'm7') + threads.set('t7', { status: 'failed', title: 'Fix the login page', setupFailure: failure }) + f.bots.threadRunEnded('t7') + await flush() + failedNotice(jobId) + f.bots.jobSetupFailed(botId, jobId, failure) + await flush() + expect(noticeTurns()).toHaveLength(1) + }) + + it('a paused bot is told why in its line with the link, whichever way the ledger hears of it, once', async () => { + const settings = getDefaultSettings(); settings.experimental.botAsksFirstOff = false + f.host.settings = { get: () => settings } as never + const told = await handOff('Fix the login page in project Web', 't9', 'm9') + const read = await handOff('Fix the signup page in project Web', 't10', 'm10') + await f.bots.service.pause(botId) + f.bots.jobSetupFailed(botId, told, failure) + threads.set('t10', { status: 'failed', title: 'Fix the signup page', setupFailure: failure }) + f.bots.threadRunEnded('t10') + f.bots.jobSetupFailed(botId, told, failure) + f.bots.jobSetupFailed(botId, read, failure) + await flush() + expect(noticeTurns()).toEqual([]) + for (const [jobId, threadId] of [[told, 't9'], [read, 't10']]) { + const reports = chatOf(f, botId).filter((message) => message.kind === 'run_report' && message.text.includes(`mousse://thread/${threadId}`)) + expect(reports.map((message) => message.text)).toEqual([expect.stringContaining(`failed: mousse://thread/${threadId}. ${failure.reason} I didn't follow up on this: I'm paused.`)]) + expect(f.store.job(jobId)).toMatchObject({ state: 'failed', line: failure.reason }) + expect(notices(jobId)).toBe(1) + } + }) + + it('another bot\'s job is left as it is', async () => { + const jobId = await handOff('Fix the login page in project Web', 't8', 'm8') + f.bots.jobSetupFailed('another-bot', jobId, failure) + await flush() + expect(noticeTurns()).toEqual([]) + expect(f.store.job(jobId)).toMatchObject({ state: 'running' }) + }) + }) + it('a second message to a thread still on the job joins it; a paused bot is told in a line with the link, and no turn starts', async () => { const jobId = await handOff('Fix the login page in project Web', 't3', 'm3') expect(f.bots.openJob(botId, f.store.listActivations(botId).at(-1)!.id, { threadId: 't3', title: 'Fix the login page', sent: 'Also the logout.' }).jobId).toBe(jobId) diff --git a/tests/run/botOwnerAsks.test.ts b/tests/run/botOwnerAsks.test.ts index ebf678f929..1bea6f1442 100644 --- a/tests/run/botOwnerAsks.test.ts +++ b/tests/run/botOwnerAsks.test.ts @@ -208,7 +208,8 @@ describe('personal bot owner asks', () => { else expect(JSON.parse(initial.text)).toMatchObject({ threadId: 'thread-1' }) expect(JSON.parse((await fromOwner('asks_save', { asks: ['Reworded ask', 'New slot on replay'] })).text).asks).toEqual([ask]) const replay = await fromOwner('thread_create', { ...launch, title: 'Reworded title', clientRequestId: 'other-call' }) - expect(JSON.parse(replay.text)).toMatchObject({ threadId: 'thread-1', replayed: true }) + // The same job as the first call opened, even when its reply was lost. + expect(JSON.parse(replay.text)).toMatchObject({ threadId: 'thread-1', replayed: true, job: { jobId: f.store.jobsOfOwnerAsk(botId, ask.ask)[0]!.id } }) const update = await fromOwner('item_save', { ask: ask.ask, text: 'Reworded item', state: 'building' }) expect(JSON.parse(update.text)).toMatchObject({ id: 'i1', open: 1 }) expect(await fromOwner('item_save', { text: 'Another way to word this owner ask' })).toMatchObject({ isError: true }) diff --git a/tests/run/botThreadsDaemon.test.ts b/tests/run/botThreadsDaemon.test.ts index 87923727c5..077b1cc513 100644 --- a/tests/run/botThreadsDaemon.test.ts +++ b/tests/run/botThreadsDaemon.test.ts @@ -18,13 +18,18 @@ import type { PermissionMode } from '../../src/shared/permissionMode' import type { RunSettings } from '../../src/shared/settings' import { usageLimitError } from '../../src/mms/orchestrator/providerErrors' import { ThreadJournal } from '../../src/mms/data/ThreadJournal' -import { BOT_THREAD_ACT_TOOLS, BOT_THREAD_READ_TOOLS } from '../../src/shared/bots/personal/manifest' +import { BOT_THREAD_ACT_TOOLS, BOT_THREAD_READ_TOOLS, BOT_THREADS_PERMISSION, botStarterManifest } from '../../src/shared/bots/personal/manifest' +import { createBotAuthority } from '../../src/mms/bots/authority/botAuthority' +import { botManifestDigest, compileBotThread } from '../../src/mms/bots/grants/compile' +import { ThreadWorkspaceManager } from '../../src/mms/workspace/ThreadWorkspaceManager' +import { resolveRepositoryIdentity } from '../../src/mms/git/RepositoryIdentity' +import { defaultThreadWorktreePath } from '../../src/mms/worktree/worktreeLayout' import type { BotAuthority } from '../../src/shared/bots/personal/authority' import type { AgentActor } from '../../src/mms/run/types' import type { EventEmitter } from 'node:events' -import { launchedThreadsIn, watchLaunchedThreads } from '../../src/mms/bots/launchedThreads' +import { jobThreadIn, launchedThreadsIn, watchLaunchedThreads } from '../../src/mms/bots/launchedThreads' import { BOT_LAUNCHED_RECENT_MS, launchedActive } from '../../src/shared/bots/personal/chat' -import { appTurn } from './appToolsFixture' +import { appToolRegistry, appTurn, fakeAppToolHost } from './appToolsFixture' import { PI, phase6Daemon, piAdapter, waitFor, type Phase6Daemon } from './phase6Fixture' vi.setConfig({ testTimeout: 60_000 }) @@ -797,4 +802,110 @@ describe('a bot\'s threads in the service ("use your threads")', () => { await waitFor(() => JSON.stringify(refreshes.at(-1)) === JSON.stringify([['on_hold', false]]), 'a refresh once the queue stopped') unwatch() }) + + /** + * A Git project whose new worktrees wait on `gate` and then fail (something already at the worktree's place), and the + * real `thread_create` tool under a bot chat turn that holds "use your threads", with the bot's ledger (`jobs`). + */ + const gitWorld = async (jobs: Record) => { + const w = world() + const repo = join(w.home, 'repo') + mkdirSync(repo) + const git = (...args: string[]) => execFileSync('git', args, { cwd: repo, stdio: 'ignore' }) + git('init', '-q'); git('config', 'user.name', 'Test'); git('config', 'user.email', 'test@example.test') + writeFileSync(join(repo, 'README'), 'base\n'); git('add', '.'); git('commit', '-qm', 'base') + const project = w.d.projects.openProject(repo) + const started = await w.d.engine.dispatch({ kind: 'send', threadId: w.chat.id, clientRequestId: 'bot-chat', source: 'gui' }) + if (started.status !== 'accepted') throw new Error('the bot chat run was refused') + w.d.engine.markStarting(started.runId) + w.d.engine.markRunning(started.runId) + const starter = botStarterManifest() + const grant = { ...starter, appTools: [...starter.appTools, BOT_THREADS_PERMISSION] } + const scratch = join(w.home, 'bots', 'scratch', 'act-1') + mkdirSync(scratch, { recursive: true }) + const compiled = compileBotThread({ + grant, digest: botManifestDigest(grant), thread: {}, scratch, profileHome: w.home, + nativeNames: (tools) => ({ ok: true, names: [...tools] }), remaining: { deadlineMs: 60_000 }, + botTools: { escalate: true, consult: false, memory: true, threads: 'all' } + }) + if (!compiled.ok) throw new Error(compiled.error.message) + const authority = createBotAuthority({ + activationId: 'act-1', role: 'activation', permissions: compiled.permissions, waiting: () => false, + counters: { charge: () => ({ ok: true, count: 1 }) }, time: { deadline: () => 0, signal: new AbortController().signal }, spend: null + }) + w.d.orch.appToolTurns.register(appTurn({ threadId: w.chat.id, runId: started.runId, bot: authority })) + const activation = { botId: 'b1', activationId: 'act-1', lane: 'chat', memoryLane: 'chat', role: 'home' } + w.d.orch.setBotAppTools({ bots: { host: { activationOf: (id: string) => (id === w.chat.id ? activation : undefined), jobs } } as never, memory: { activationOf: () => undefined } as never }) + const gate = Promise.withResolvers() + const key = resolveRepositoryIdentity(repo).key + const provision = ThreadWorkspaceManager.prototype.provision + vi.spyOn(ThreadWorkspaceManager.prototype, 'provision').mockImplementation(async function (this: ThreadWorkspaceManager, ...args) { + await gate.promise + const place = defaultThreadWorktreePath(w.home, key, args[0], args[1]) + mkdirSync(join(place, '..'), { recursive: true }) + writeFileSync(place, 'in the way\n') + return provision.apply(this, args) + }) + const { request } = appToolRegistry(w.d.engine, fakeAppToolHost().host) + const create = async (key: string) => { + const response = await w.d.orch.mcpToolRegistry().call('thread_create', { + kind: 'thread', projectId: project.id, title: 'Fix login', workspace: 'new_worktree', message: 'Look at the login page.', clientRequestId: key + }, request({ threadId: w.chat.id, runId: started.runId })) + expect(response.isError, response.text).toBeFalsy() + return JSON.parse(response.text) as Record + } + const done = () => { + vi.restoreAllMocks() + w.d.engine.markTerminal(started.runId, 'completed') + } + return { w, gate, create, done } + } + + it('a thread it starts answers with its job before its worktree is set up; a worktree that can\'t be made ends that job once, with why', async () => { + const setupFailed = vi.fn() + const launched = vi.fn(() => ({ jobId: 'job-1' })) + const { w, gate, create, done } = await gitWorld({ open: () => ({ jobId: 'job-1' }), setupFailed, launched }) + try { + // Answered while the worktree is still being set up: the job, and no setup line to wait for. + const made = await create('c1') + expect(made).toMatchObject({ job: { jobId: 'job-1' }, firstMessage: { sent: true } }) + expect(made.setup).toBeUndefined() + expect(setupFailed).not.toHaveBeenCalled() + gate.resolve() + await waitFor(() => setupFailed.mock.calls.length > 0, 'the job told of the failed setup') + expect(setupFailed).toHaveBeenCalledWith('b1', 'job-1', expect.objectContaining({ reason: expect.stringMatching(/^Couldn't/), detail: expect.stringMatching(/already exists/), retryable: true })) + // The thread keeps the same failure for that run, with its Retry. + expect(w.d.store.getThread(made.threadId)?.setupFailure).toMatchObject({ runId: made.firstMessage.runId, retryable: true }) + // The ledger's own read of the thread (after a lost reply or a restart) finds the same failure for that run. + await w.settled(made.firstMessage.runId) + expect(jobThreadIn({ threads: w.d.store, engine: w.d.engine, asks: () => false }, made.threadId)).toMatchObject({ status: 'failed', setupFailure: { reason: expect.stringMatching(/^Couldn't/), retryable: true } }) + // A retry of the call (its first reply lost) replays the thread with the job the first call opened, waits on + // nothing and tells the job nothing more. + expect(await create('c1')).toMatchObject({ threadId: made.threadId, replayed: true, job: { jobId: 'job-1' } }) + expect(launched).toHaveBeenCalledWith('b1', made.threadId) + expect(setupFailed).toHaveBeenCalledOnce() + // Retry before the ledger read the run (a restart lost the word above): the ledger reads that run's failure as + // Retry starts, before it is cleared. + const atRetry: unknown[] = [] + w.d.orch.on('setup-retry', ({ threadId }: { threadId: string }) => atRetry.push(jobThreadIn({ threads: w.d.store, engine: w.d.engine, asks: () => false }, threadId))) + await w.d.orch.retrySetup(made.threadId) + expect(atRetry).toEqual([expect.objectContaining({ status: 'failed', setupFailure: expect.objectContaining({ reason: expect.stringMatching(/^Couldn't/), retryable: true }) })]) + const retried = w.d.engine.store.listRuns(made.threadId, { limit: 1 })[0]!.runId + expect(retried).not.toBe(made.firstMessage.runId) + await w.settled(retried) + } finally { + done() + } + }) + + it('a bot whose ledger can\'t take a setup failure still waits for setup and is told why', async () => { + const { gate, create, done } = await gitWorld({ open: () => ({ jobId: 'job-1' }) }) + try { + gate.resolve() + const made = await create('c1') + expect(made).toMatchObject({ job: { jobId: 'job-1' }, setup: 'failed', setupError: expect.stringMatching(/already exists/) }) + } finally { + done() + } + }) })