A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Keep a Bot's input when its part switch fails, also during an unload
Fei24116aaaaaa5e452
diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.jsindex 3ca33676..04dcc6fa 100644--- a/ds-bot/src/host/parts.js+++ b/ds-bot/src/host/parts.js@@ -18,6 +18,7 @@ import { randomUUID } from 'node:crypto'import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'import { HANDOFF_ACK, HISTORY_TIMEOUT_MS, REPLY_KIND, SOURCE_KIND } from './constants.js'import { CHECKPOINT_PROMPT, STEWARD_SYSTEM, checkpointCount, checkpointTail, checkpointTailNote, checkpointText, linesFor, parseDecision, stewardRequest } from './steward.js'+import { RESUME_DELAY_MS } from './resume.js'import { clip, createClock, escapeRegExp, estimateTokens, splitRef, textOf } from './text.js'// An ask_user card as the user saw it. The user's reply is often just an option label,@@ -144,6 +145,7 @@ export function install(rt) {const STEWARD_TIMEOUT_MS = 120_000const STEWARD_LINES = 40const FOLDER_RETRY_MS = 300_000+ const PAUSE_NOTE = 'DS Bot paused your turn for a context check. Go on with it now from where you stopped.'// A broken provider adapter must not crash every turn; estimate from the// derived messages instead, with one warning.@@ -658,18 +660,82 @@ export function install(rt) {if (target === undefined || messages.length === 0) returnawait rt.ensureCapabilities(target)const agent = await rt.resolveAgent(target)+ // A retry after a forward that stopped halfway must not deliver the same input twice.+ const pending = [...agent.inbox.nextStep, ...agent.inbox.nextTurn]for (const message of messages) {const kind = message.source?.kind// DSH's notice of a folder change is about the Session it was queued in; the part// that goes on has its own folder, which its handoff names.if (kind === 'working-directory') continue+ const exchangeId = message.source?.exchangeId+ if (exchangeId !== undefined && pending.some(queued => queued.source?.exchangeId === exchangeId)) continueconst copy = createUserMessage({ content: message.content, ...(message.source ? { source: message.source } : {}) })if (kind === 'user' || kind === SOURCE_KIND || kind === REPLY_KIND) agent.followup(copy)else agent.inject(copy)+ pending.push(copy)}await ctx.sessions.flush(agent.session)}+ // The plugin's own fiber is disposed (a reload, or DSH closing): every service+ // lookup fails with the same inactive-context error, and logging through rt.warn+ // would fail the same way, so an unloaded failure is noted once at info instead.+ const unloaded = error => ctx.fiber?.uid === null || /in inactive context/.test(String(error?.message ?? error))+ const noteInfo = (template, ...args) => { try { ctx.logger.info(template, ...args) } catch {} }++ // A message's inbox boundary, the same one forward() delivers it to.+ const inboxTargetOf = message => (message.source?.kind === 'user' || message.source?.kind === SOURCE_KIND || message.source?.kind === REPLY_KIND ? 'next-turn' : 'next-step')++ // Input a switch could not hand on goes back into the part's own durable inbox, in+ // order: input followup would deliver waits for the next turn, the rest waits for+ // the next step. agent.inbox writes do not touch this plugin's context, so they+ // still work while it is being unloaded.+ const restore = (agent, messages) => {+ for (const message of [...messages].reverse()) {+ const exchangeId = message.source?.exchangeId+ const pending = [...agent.inbox.nextStep, ...agent.inbox.nextTurn]+ if (pending.some(queued => queued.id === message.id || (exchangeId !== undefined && queued.source?.exchangeId === exchangeId))) continue+ agent.inbox.prepend(inboxTargetOf(message), message)+ }+ }++ // Input in the inbox is durable but does not wake the driver; send() is what wakes+ // it. Re-send what waits, in order, the first message with the wake, so a stopped+ // turn goes on without waiting for the next input. Only while the plugin is live —+ // a turn that starts during unload would run without DS Bot's hooks.+ const wake = (agent) => {+ const pending = [...agent.inbox.nextStep, ...agent.inbox.nextTurn]+ for (const message of pending) agent.inbox.remove(message.id)+ pending.forEach((message, index) => agent.send(message, inboxTargetOf(message), index === 0))+ }++ // A switch that lost its move or its input to a failure leaves its part marked in+ // state.switching. Hand on what it kept: input an earlier part still holds goes to+ // the part that replaced it and the earlier part is archived as the switch meant+ // to; a part that stayed just wakes so its kept input goes on.+ async function heldBack() {+ await rt.load()+ if (rt.readOnly() !== undefined) return+ for (const [sessionId, owner] of Object.entries(state.switching ?? {})) {+ try {+ const agent = await rt.resolveAgent(sessionId)+ const held = [...agent.inbox.nextStep, ...agent.inbox.nextTurn]+ if (currentOf(owner) !== sessionId) {+ await forward(owner, held)+ for (const message of held) agent.inbox.remove(message.id)+ await ctx.workspaceRegistry.archiveSession(sessionId)+ .catch(error => rt.warn('ds-bot: earlier part %s not archived: %s', sessionId, error))+ } else {+ try { wake(agent) } catch (error) { rt.warn('ds-bot: part %s could not be woken for its kept input: %s', sessionId, error) }+ }+ delete state.switching[sessionId]+ await rt.save()+ } catch (error) {+ rt.warn('ds-bot: input kept in part %s was not handed on: %s', sessionId, error)+ }+ }+ }+// `hard`: past the hard line or the window, the part moves on even without a note// from the model. `folder`: the part moves on because its working folder changed.function startSwitch(agent, { resume = false, carry = [], info, joined, overflow = false, failed, bare = false, folder = false, hard = overflow || folder } = {}) {@@ -678,10 +744,18 @@ export function install(rt) {const job = { ...place, carry: [...carry], info, joined, resume, overflow, failed, bare, folder, hard, since: Date.now() }switches.set(agent.id, job)void runSwitch(agent, job)- .catch(error => rt.warn('ds-bot: %s did not move on to a fresh part: %s', rt.botOf(job.botId)?.name ?? agent.id, error))+ .catch(error => {+ if (unloaded(error)) return noteInfo('ds-bot: plugin unloaded while %s switched parts; input kept in part %s', rt.botOf(job.botId)?.name ?? agent.id, agent.id)+ rt.warn('ds-bot: %s did not move on to a fresh part: %s', rt.botOf(job.botId)?.name ?? agent.id, error)+ }).finally(async () => {switches.delete(agent.id)if (job.moved) {+ // A move that had to put input back keeps the part marked for the restart pass.+ if (job.kept !== true) {+ delete state.switching[agent.id]+ await rt.save()+ }noteFailures.delete(agent.id)folderRetry.delete(agent.id)// The folder may have changed again while the switch ran.@@ -690,20 +764,36 @@ export function install(rt) {}if (folder) folderRetry.set(agent.id, Date.now() + FOLDER_RETRY_MS)if (!job.noteFailed) partBase.set(agent.id, tokensOf(agent.session) ?? 0)- // The stopped turn goes on where it was.+ // The stopped turn goes on where it was. A retry finds the note among the+ // input this part kept, so it is added once.const back = job.carry.splice(0)- if (resume) {+ const noted = [...agent.inbox.nextStep, ...agent.inbox.nextTurn].some(message => textOf(message.content) === PAUSE_NOTE)+ if (resume && !back.some(message => textOf(message.content) === PAUSE_NOTE) && !noted) {const carried = job.joined?.length ? { joined: job.joined } : {}back.unshift(createUserMessage({- content: [{ type: 'text', text: 'DS Bot paused your turn for a context check. Go on with it now from where you stopped.' }],+ content: [{ type: 'text', text: PAUSE_NOTE }],source: job.info ? { ...job.info, ...carried } : { kind: SOURCE_KIND, form: 'relay', role: 'resume', exchangeId: randomUUID(), senderName: 'DS Bot', ...carried },}))}- await forward(job, back).catch(error => rt.warn('ds-bot: input for %s was not handed on: %s', agent.id, error))+ await forward(job, back).then(() => {+ delete state.switching[agent.id]+ }).catch((error) => {+ job.kept = true+ try { restore(agent, back) } catch {}+ if (unloaded(error)) return noteInfo('ds-bot: plugin unloaded during the switch of %s; input kept in part %s', agent.id, agent.id)+ rt.warn('ds-bot: input for %s was not handed on: %s', agent.id, error)+ // The input is back where it was; the turn that owns it goes on at once.+ try { wake(agent) } catch {}+ })+ await rt.save()})}async function runSwitch(agent, job) {+ // Marks the part while the switch runs; it stays marked whenever input was put+ // back, so a restart knows where to look without resolving every earlier part.+ state.switching[agent.id] = job.roomId === undefined ? { botId: job.botId } : { botId: job.botId, roomId: job.roomId }+ await rt.save()for (let attempt = 1; ; attempt += 1) {await agent.whenIdle()try {@@ -817,23 +907,41 @@ export function install(rt) {void rt.moveSchedules(agent.id, freshId)job.moved = trueconst resume = job.resume || job.overflow- await rt.ensureCapabilities(freshId)- const fresh = await rt.resolveAgent(freshId)- const cwd = fresh.session.header?.cwd- const folder = cwd !== undefined && cwd !== session.header?.cwd ? cwd : undefined- // A fresh part that is not where it was made for would move on at every step.- if (intended !== undefined && cwd !== undefined && cwd !== intended) {- folderRetry.set(freshId, Date.now() + FOLDER_RETRY_MS)- rt.warn('ds-bot: the fresh part of %s did not start in %s; it works in %s', bot.name, intended, cwd)- }- const text = handoffPackage({ room, segment, lines: carried, number: number + 1, resume, overflow: job.overflow, failed: job.failed, bare: job.bare, folder })- freshParts.set(freshId, estimateTokens(text))- fresh.followup(createUserMessage({ content: [{ type: 'text', text }], source: handoffSource(job, resume) }))- await ctx.sessions.flush(fresh.session)- // Then what the old part held: the stopped turn's input, then whatever waited.+ // Then what the old part held: the stopped turn's input, then whatever waited. It+ // moves first; only after that does the old inbox give it up, so a failure keeps it.const held = [...agent.inbox.nextStep, ...agent.inbox.nextTurn]+ const carry = []+ let folder+ try {+ await rt.ensureCapabilities(freshId)+ const fresh = await rt.resolveAgent(freshId)+ const cwd = fresh.session.header?.cwd+ folder = cwd !== undefined && cwd !== session.header?.cwd ? cwd : undefined+ // A fresh part that is not where it was made for would move on at every step.+ if (intended !== undefined && cwd !== undefined && cwd !== intended) {+ folderRetry.set(freshId, Date.now() + FOLDER_RETRY_MS)+ rt.warn('ds-bot: the fresh part of %s did not start in %s; it works in %s', bot.name, intended, cwd)+ }+ const text = handoffPackage({ room, segment, lines: carried, number: number + 1, resume, overflow: job.overflow, failed: job.failed, bare: job.bare, folder })+ freshParts.set(freshId, estimateTokens(text))+ fresh.followup(createUserMessage({ content: [{ type: 'text', text }], source: handoffSource(job, resume) }))+ await ctx.sessions.flush(fresh.session)+ carry.push(...job.carry.splice(0))+ await forward(job, [...carry, ...held])+ } catch (error) {+ job.kept = true+ try { restore(agent, [...carry, ...job.carry.splice(0)]) } catch {}+ throw error+ }for (const message of held) agent.inbox.remove(message.id)- await forward(job, [...job.carry.splice(0), ...held])+ // Input the old part claimed while the rest moved goes on after it.+ for (let late = job.carry.splice(0); late.length > 0; late = job.carry.splice(0)) {+ await forward(job, late).catch((error) => {+ job.kept = true+ try { restore(agent, late) } catch {}+ throw error+ })+ }ctx.logger.info('ds-bot: %s%s moved on to part %d at %d tokens (check line %d, hard line %d); %s; %d latest and %d earlier messages carried%s', bot.name, room ? ` in ${room.name}` : '', number + 1, tokens ?? -1, lines?.check ?? -1, lines?.hard ?? -1,written !== undefined ? `note written in ${written.attempts} attempt(s)` : `note put together by DS Bot (${noted.fallback}${noted.note ? `, carries part ${noted.noteFrom}'s` : ', nothing to carry'})`,carried.recent.length, carried.earlier.length, folder === undefined ? '' : `; now works in ${folder}`)@@ -1004,6 +1112,12 @@ export function install(rt) {if (end !== undefined && end.data?.reason?.kind !== 'error') rescued.delete(agent.id)}+ ctx.effect(() => {+ const timer = setTimeout(() => void heldBack().catch(error => rt.warn('ds-bot: handing on input kept in earlier parts failed: %s', error)), RESUME_DELAY_MS)+ timer.unref?.()+ return () => clearTimeout(timer)+ }, 'ds-bot: hand on input kept in earlier parts')+ctx.on('agent/status', ({ agent, status }) => {if (status === 'idle' && rt.isBotSession(agent.id)) {releaseRescued(agent)@@ -1098,5 +1212,5 @@ export function install(rt) {return { sessionId: parts.at(-1).sessionId, ...(await partPage(parts, index, cursor)) }}- Object.assign(rt, { clock, partsOf, historyEntry, partLines, noteText, earlierPage, chatPage, displayItems, followFolder, switchJobs: () => switches.values() })+ Object.assign(rt, { clock, partsOf, historyEntry, partLines, noteText, earlierPage, chatPage, displayItems, followFolder, heldBack, switchJobs: () => switches.values() })}diff --git a/ds-bot/src/host/resume.js b/ds-bot/src/host/resume.jsindex 11ba4540..27e52740 100644--- a/ds-bot/src/host/resume.js+++ b/ds-bot/src/host/resume.js@@ -11,7 +11,7 @@ import { join } from 'node:path'import { SOURCE_KIND } from './constants.js'// Long enough for DSH to finish opening its workspaces after a start.-const RESUME_DELAY_MS = 3000+export const RESUME_DELAY_MS = 3000// A delivery waiting longer than this was not lost to a restart.const QUEUED_KEPT_MS = 24 * 60 * 60 * 1000const QUEUED_MAX = 50diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.jsindex efa745bf..1f1e69f0 100644--- a/ds-bot/src/host/roster.js+++ b/ds-bot/src/host/roster.js@@ -538,6 +538,7 @@ export function install(rt) {for (const part of parts) {delete state.questions[part]delete state.exchangeTurns[part]+ delete state.switching[part]}const touched = []for (const room of Object.values(state.rooms)) {diff --git a/ds-bot/src/host/store.js b/ds-bot/src/host/store.jsindex c13c68a5..29ddf070 100644--- a/ds-bot/src/host/store.js+++ b/ds-bot/src/host/store.js@@ -18,7 +18,7 @@ export function install(rt) {const { ctx, home, statePath } = rt/** @type {{version:1, workspaceId?:string, mainBotIds:string[], bots:Record<string,any>, rooms:Record<string,any>, agents:Record<string,any>, capabilities:{items:Record<string,any>}, exchanges:any[], exchangeTurns:Record<string,number[]>, revision:number}} */- const state = { version: 1, mainBotIds: [], bots: {}, rooms: {}, agents: {}, capabilities: { items: {} }, exchanges: [], exchangeTurns: {}, works: {}, questions: {}, prefs: {}, revision: 0 }+ const state = { version: 1, mainBotIds: [], bots: {}, rooms: {}, agents: {}, capabilities: { items: {} }, exchanges: [], exchangeTurns: {}, works: {}, questions: {}, prefs: {}, switching: {}, revision: 0 }let loaded = nulllet writing = Promise.resolve()const { warn } = rt@@ -368,7 +368,9 @@ export function install(rt) {const sessionId = room.sessions?.[botId]if (sessionId === undefined) returndelete room.sessions[botId]+ for (const segment of room.segments?.[botId] ?? []) delete state.switching[segment.sessionId]if (room.segments !== undefined) delete room.segments[botId]+ delete state.switching[sessionId]groupOwners.delete(sessionId)rt.cancelApprovals?.(sessionId)// A plain archive refuses a running Session, which would go on working for a groupdiff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.jsindex 6adcdcf7..430f154f 100644--- a/ds-bot/test/install.test.js+++ b/ds-bot/test/install.test.js@@ -85,6 +85,7 @@ test('apply registers listeners, tools, and effects in a fixed order', (t) => {'on system-prompt/assemble (prepend)','on agent/request-error (prepend)','on agent/request-error (prepend)',+ 'effect ds-bot: hand on input kept in earlier parts','on agent/status','on llm/stream','on llm/stream',diff --git a/ds-bot/test/switch-keeps-input.test.js b/ds-bot/test/switch-keeps-input.test.jsnew file mode 100644index 00000000..92e6ae91--- /dev/null+++ b/ds-bot/test/switch-keeps-input.test.js@@ -0,0 +1,343 @@+import assert from 'node:assert/strict'+import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync, mkdirSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { test } from 'node:test'+import { createRuntime } from '../index.js'+import { fakeContext } from './fake-ctx.js'++// #280: a switch that fails while the plugin is being unloaded must not lose the input+// it carried — a turn's claimed messages and whatever the old part held. The old+// part's durable inbox keeps them (the fake persists it across starts), a switch is+// marked in state.switching until its input is handed on, a retry does not double,+// and the restart pass hands marked input on or wakes the part that kept it.+const TEAM = {+ version: 1,+ mainBotIds: ['a'],+ workspaceId: 'w1',+ bots: {+ a: { id: 'a', name: 'Chief', role: 'Boss', sessionId: 'a', createdAt: 1 },+ b: { id: 'b', name: 'Writer', role: 'Write', sessionId: 'b', createdAt: 2 },+ },+ rooms: {},+ agents: {},+ exchanges: [],+ exchangeTurns: {},+ questions: {},+ prefs: {},+ revision: 0,+}++// The error every ctx service lookup gives once the plugin's fiber is disposed.+const INACTIVE = 'cannot get required service "sessions" in inactive context'++// `fail.create`/`fail.resolve`/`fail.flush`: true fails with the inactive-context+// error; an Error value fails with it, so an ordinary error is testable too.+async function start({ fail = {}, services = {}, home: reuse } = {}) {+ const root = reuse === undefined+ ? realpathSync.native(mkdtempSync(join(tmpdir(), 'ds-bot-switch-')))+ : join(reuse, '..', '..')+ const home = reuse ?? join(root, 'dsh', 'bot')+ const team = join(home, 'workspace')+ const project = join(root, 'project')+ for (const dir of [team, project]) mkdirSync(dir, { recursive: true })+ if (reuse === undefined) writeFileSync(join(home, 'state.json'), JSON.stringify(TEAM))++ // The real inbox is durable; the fake keeps it in a file so a "restart" sees it.+ const inboxPath = join(home, 'fake-inbox.json')+ const inboxSeed = () => {+ try { return JSON.parse(readFileSync(inboxPath, 'utf8')) } catch { return {} }+ }+ const saved = inboxSeed()+ const persist = (agents) => {+ const all = { ...saved }+ for (const [id, agent] of agents) all[id] = { nextStep: agent.inbox.nextStep, nextTurn: agent.inbox.nextTurn }+ writeFileSync(inboxPath, JSON.stringify(all))+ }++ const ctx = fakeContext({ services })+ const warnings = []+ const infos = []+ ctx.logger = {+ warn: (...args) => warnings.push(args.map(String).join(' ')),+ info: (...args) => infos.push(args.map(String).join(' ')),+ }+ const errorOf = value => (value instanceof Error ? value : new Error(INACTIVE))+ let flushes = 0+ const created = []+ const resolved = []+ const archived = []+ const cwds = new Map()+ const agents = new Map()+ const agentOf = (sessionId) => {+ if (!agents.has(sessionId)) {+ const calls = []+ const nextStep = [...saved[sessionId]?.nextStep ?? []]+ const nextTurn = [...saved[sessionId]?.nextTurn ?? []]+ agents.set(sessionId, {+ id: sessionId,+ session: { id: sessionId, header: { cwd: cwds.get(sessionId) ?? team }, requestHeader: () => undefined, deriveMessages: () => [] },+ calls,+ status: 'idle',+ followup(message) { calls.push(['followup', message]) },+ steer(message) { calls.push(['steer', message]) },+ inject(message) { calls.push(['inject', message]) },+ send(message, target, wakeup) {+ ;(target === 'next-turn' ? nextTurn : nextStep).push(message)+ calls.push(['send', message, target, wakeup])+ persist(agents)+ },+ cancel() {},+ async whenIdle() {},+ async runMaintenance(fn) { return fn(AbortSignal.timeout(60_000)) },+ inbox: {+ nextStep,+ nextTurn,+ prepend(target, message) { ;(target === 'next-turn' ? nextTurn : nextStep).unshift(message); persist(agents) },+ append(target, message) { ;(target === 'next-turn' ? nextTurn : nextStep).push(message); persist(agents) },+ remove(id) {+ for (const list of [nextStep, nextTurn]) {+ const at = list.findIndex(message => message.id === id)+ if (at !== -1) { list.splice(at, 1); persist(agents); return true }+ }+ return false+ },+ },+ })+ }+ return agents.get(sessionId)+ }+ Object.assign(ctx, {+ llm: { listProviders: () => [], listModels: async () => [], resolveModelInfo: async () => ({}) },+ workspaceRegistry: {+ get: () => undefined,+ list: () => [{ id: 'w1', path: team }],+ resolveByPath: async () => undefined,+ create: async path => ({ id: 'w-new', path }),+ archiveSession: async (sessionId) => { archived.push(sessionId) },+ },+ sessionController: {+ create: async (options) => {+ if (fail.create) throw errorOf(fail.create)+ const sessionId = `s${created.length + 1}`+ created.push(options)+ cwds.set(sessionId, options.cwd ?? team)+ return { sessionId }+ },+ resolveAgent: async (sessionId) => {+ if (fail.resolve?.has(sessionId)) throw errorOf(fail.resolve)+ resolved.push(sessionId)+ return { agent: agentOf(sessionId) }+ },+ selectModel: async () => {},+ page: async () => ({ records: [], hasMore: false }),+ },+ sessionTitle: { rename: async () => {} },+ sessions: {+ // A number fails that call; true fails them all, so a test can break the flush+ // of the handed-on input without breaking the fresh part's own write before it.+ flush: async () => {+ flushes += 1+ if (fail.flush === true || fail.flush instanceof Error || fail.flush === flushes) throw errorOf(fail.flush)+ },+ },+ })+ let route+ const register = ctx.connection.fetch.register+ ctx.connection.fetch.register = (options) => {+ route = options+ return register(options)+ }+ const rt = createRuntime(ctx, { home })+ const call = async (endpoint, payload) => (await route.fetch(new Request('http://localhost/api/bot', {+ method: 'POST', body: JSON.stringify({ endpoint, payload }),+ }))).json()+ const tool = (name, args, sessionId) => ctx.registeredTools.get(name).execute(args, { agent: agentOf(sessionId), name, callId: 'c1' })+ const preStep = (sessionId, messages = [], step = 1) => ctx.listeners.get('agent/pre-step').at(-1)(+ { agent: agentOf(sessionId), messages, step, signal: AbortSignal.timeout(60_000) }, async () => 'next')+ const state = () => JSON.parse(readFileSync(join(home, 'state.json'), 'utf8'))+ const stop = async ({ keep = false } = {}) => {+ await ctx.dispose()+ if (!keep) rmSync(root, { recursive: true, force: true, maxRetries: 5 })+ }+ await tool('list_bots', {}, 'a')+ return { ctx, rt, root, home, team, project, created, resolved, archived, agentOf, call, tool, preStep, state, warnings, infos, fail, stop }+}++const settle = () => new Promise(resolve => setTimeout(resolve, 20))+const until = async (check, ms = 3000) => {+ const end = Date.now() + ms+ while (!check()) {+ if (Date.now() > end) throw new Error('until: the condition did not hold')+ await settle()+ }+}++const text = message => message.content.map(block => block.text ?? '').join('\n')+const inboxTexts = agent => [...agent.inbox.nextStep, ...agent.inbox.nextTurn].map(text)+const PAUSE = 'DS Bot paused your turn for a context check. Go on with it now from where you stopped.'+const said = (id, body, exchangeId) => ({ id, role: 'user', content: [{ type: 'text', text: body }], source: { kind: 'user', ...(exchangeId ? { exchangeId } : {}) } })+// A folder outside the team workspace asks for approval once; then the move is allowed.+const services = {+ sandboxPolicy: { resolve: () => ({ mode: 'workspace-write' }) },+ approval: { request: async () => 'allowed-once' },+}++// Writer's own chat gets a working folder while it is mid-turn; its next step starts+// the switch and carries that step's input along.+const moveWriter = async (host, input, step = 2) => {+ host.agentOf('b').status = 'running'+ assert.equal((await host.tool('update_bot', { work_dir: host.project }, 'b')).includes('From your next step on'), true)+ assert.deepEqual(await host.preStep('b', input, step), { kind: 'reject' })+}++test('a move that fails while the plugin unloads hands its input back to the part it left', async (t) => {+ // The first flush writes the fresh part's handoff; the second moves the input.+ const fail = { flush: 2 }+ const host = await start({ fail, services })+ t.after(host.stop)+ host.agentOf('b').inbox.nextTurn.push(said('h1', 'waiting input', 'e-held'))+ await moveWriter(host, [said('m1', 'Now build it', 'e-carry'), said('m2', 'and this too', 'e-carry2')])++ // The fresh part took over, then moving the input failed while unloaded.+ await until(() => host.infos.some(line => line.includes('plugin unloaded')))+ assert.equal(host.state().bots.b.sessionId, 's1')+ // The part stays marked until the restart pass hands the input on.+ assert.deepEqual(host.state().switching, { b: { botId: 'b' } })++ // carry went back in order at the front of next-turn; the held message stayed put.+ assert.deepEqual(inboxTexts(host.agentOf('b')), ['Now build it', 'and this too', 'waiting input'])+ assert.equal(host.warnings.length, 0)+ assert.ok(host.infos.some(line => line.includes('input kept in part')))+})++test('a move that never started keeps carry and one pause note in the inbox; a retry adds none', async (t) => {+ const fail = { create: true, flush: true }+ const host = await start({ fail, services })+ t.after(host.stop)+ await moveWriter(host, [said('m1', 'keep me', 'e1')])+ await until(() => host.infos.some(line => line.includes('plugin unloaded')))+ assert.equal(host.warnings.length, 0)+ assert.deepEqual(inboxTexts(host.agentOf('b')), [PAUSE, 'keep me'])+ // The part stayed put and kept its input, so it stays marked.+ assert.deepEqual(host.state().switching, { b: { botId: 'b' } })++ // A retry that also fails neither loses nor doubles the note; a folder move waits+ // out its retry cooldown, so the retry comes in as an overflow switch.+ const retry = () => Promise.all((host.ctx.listeners.get('agent/request-error') ?? [])+ .map(listener => listener({ agent: host.agentOf('b'), failure: { code: 'CONTEXT_WINDOW_EXCEEDED' }, signal: AbortSignal.timeout(60_000) }, async () => undefined)))+ await retry()+ await until(() => host.infos.filter(line => line.includes('plugin unloaded')).length >= 2)+ assert.deepEqual(inboxTexts(host.agentOf('b')), [PAUSE, 'keep me'])+ assert.deepEqual(host.state().switching, { b: { botId: 'b' } })++ // With the plugin live again the same input moves on — the note still only once.+ fail.create = false+ fail.flush = false+ await retry()+ await until(() => host.state().bots.b.sessionId === 's1' && host.state().switching?.b === undefined)+ const forwarded = host.agentOf('s1').calls.filter(([kind]) => kind === 'followup' || kind === 'inject').map(([, message]) => text(message))+ assert.equal(forwarded.filter(line => line === PAUSE).length, 1)+ assert.equal(forwarded.filter(line => line === 'keep me').length, 1)+ assert.deepEqual(inboxTexts(host.agentOf('b')), [])+ // The move finished and nothing stayed behind, so the mark is gone.+ assert.deepEqual(host.state().switching, {})+})++test('an ordinary failure during the move is still a warning, not the unload note', async (t) => {+ const fail = { create: new Error('disk full'), flush: new Error('disk full') }+ const host = await start({ fail, services })+ t.after(host.stop)+ await moveWriter(host, [said('m1', 'keep me', 'e1')])+ await until(() => host.warnings.some(line => line.includes('did not move on to a fresh part')))+ await until(() => host.warnings.some(line => line.includes('was not handed on')))+ assert.equal(host.infos.filter(line => line.includes('plugin unloaded')).length, 0)+ // The input is back in the part's inbox even for an ordinary failure.+ assert.deepEqual(inboxTexts(host.agentOf('b')), [PAUSE, 'keep me'])+})++test('an ordinary failure in the move that never started wakes the part at once', async (t) => {+ const fail = { create: new Error('disk full'), flush: new Error('disk full') }+ const host = await start({ fail, services })+ t.after(host.stop)+ await moveWriter(host, [said('m1', 'keep me', 'e1')])+ await until(() => host.warnings.some(line => line.includes('was not handed on')))+ const sends = host.agentOf('b').calls.filter(([kind]) => kind === 'send')+ // One wake on the first message, in the order the inbox kept them.+ assert.deepEqual(sends.map(([, message, target, wakeup]) => [text(message), target, wakeup]), [+ [PAUSE, 'next-turn', true],+ ['keep me', 'next-turn', false],+ ])+ assert.deepEqual(inboxTexts(host.agentOf('b')), [PAUSE, 'keep me'])+ // An unload instead would not wake it: no send calls at all.+ const failOff = { create: true, flush: true }+ const silent = await start({ fail: failOff, services })+ t.after(silent.stop)+ await moveWriter(silent, [said('m1', 'keep me', 'e1')])+ await until(() => silent.infos.some(line => line.includes('plugin unloaded')))+ assert.equal(silent.agentOf('b').calls.filter(([kind]) => kind === 'send').length, 0)+})++test('a marked earlier part hands its kept input on after a restart, once, and is archived', async (t) => {+ const fail = { flush: 2 }+ const host = await start({ fail, services })+ host.agentOf('b').inbox.nextTurn.push(said('h1', 'waiting input', 'e-held'))+ await moveWriter(host, [said('m1', 'Now build it', 'e-carry')])+ await until(() => host.infos.some(line => line.includes('plugin unloaded')))+ assert.equal(host.state().bots.b.sessionId, 's1')+ assert.deepEqual(host.state().switching, { b: { botId: 'b' } })+ await host.stop({ keep: true })++ // The restart: the kept input sits in the earlier part's (durable fake) inbox; a+ // copy of one message already reached the fresh part before the unload.+ const second = await start({ home: host.home, services })+ t.after(second.stop)+ second.agentOf('s1').inbox.nextTurn.push(said('m1-copy', 'Now build it', 'e-carry'))+ await second.rt.heldBack()++ const delivered = second.agentOf('s1').calls+ .filter(([kind, message]) => (kind === 'followup' || kind === 'inject') && message.source?.role !== 'handoff')+ .map(([, message]) => message.source?.exchangeId)+ assert.equal(delivered.filter(id => id === 'e-carry').length, 0) // already pending — not sent twice+ assert.equal(delivered.filter(id => id === 'e-held').length, 1)+ assert.deepEqual(inboxTexts(second.agentOf('b')), [])+ assert.ok(second.archived.includes('b'))+ assert.deepEqual(second.state().switching, {})+})++test('a marked part that stayed current is woken for its kept input, once, in order', async (t) => {+ const fail = { create: true, flush: true }+ const host = await start({ fail, services })+ await moveWriter(host, [said('m1', 'keep me', 'e1'), said('m2', 'and me', 'e2')])+ await until(() => host.infos.some(line => line.includes('plugin unloaded')))+ assert.equal(host.state().bots.b.sessionId, 'b')+ assert.deepEqual(host.state().switching, { b: { botId: 'b' } })+ await host.stop({ keep: true })++ const second = await start({ home: host.home, services })+ t.after(second.stop)+ await second.rt.heldBack()++ // The inbox kept the input; the wake re-sends it through send() so the driver runs.+ const sends = second.agentOf('b').calls.filter(([kind]) => kind === 'send')+ assert.deepEqual(sends.map(([, message, target, wakeup]) => [text(message), target, wakeup]), [+ [PAUSE, 'next-turn', true],+ ['keep me', 'next-turn', false],+ ['and me', 'next-turn', false],+ ])+ assert.deepEqual(inboxTexts(second.agentOf('b')), [PAUSE, 'keep me', 'and me'])+ assert.deepEqual(second.state().switching, {})+})++test('unmarked earlier parts are never resolved by the restart pass', async (t) => {+ const host = await start({ services })+ await moveWriter(host, [])+ await until(() => host.state().bots.b.sessionId === 's1')+ assert.deepEqual(host.state().switching, {})+ await host.stop({ keep: true })++ const second = await start({ home: host.home, services })+ t.after(second.stop)+ await second.rt.heldBack()+ assert.equal(second.resolved.includes('b'), false)+})