Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(antigravity): preserve ongoing work after progress replies
bingqilinweimaotaid97bf5db4daa
diff --git a/server/src/__tests__/agents-computer-engine-antigravity.test.ts b/server/src/__tests__/agents-computer-engine-antigravity.test.tsindex 561cac5..ca91292 100644--- a/server/src/__tests__/agents-computer-engine-antigravity.test.ts+++ b/server/src/__tests__/agents-computer-engine-antigravity.test.ts@@ -12,7 +12,8 @@ import { tmpdir } from 'node:os'import { delimiter, join } from 'node:path'import { afterEach, test } from 'node:test'import assert from 'node:assert/strict'-import { detectEngines, getAdapter, type EngineHopReport } from '../agents/computer/engine.js'+import { AgentRunner } from '../agents/computer/daemon.js'+import { detectEngines, getAdapter, type EngineHopReport, type EngineSession } from '../agents/computer/engine.js'const IS_WIN = process.platform === 'win32'const ORIGINAL_PATH = process.env.PATH@@ -42,15 +43,26 @@ rl.on('line', (line) => {const content = event?.message?.content || ''if (log) fs.appendFileSync(log, JSON.stringify({ type: 'prompt', event }) + '\\n')turn += 1- // The post-reply summary hop: agy keeps working after the tool result and- // never emits a terminal result event here, which is exactly the window the- // daemon bounds once the reply has landed.- if (process.env.FAKE_AGY_SCENARIO === 'stall') {+ if (process.env.FAKE_AGY_SCENARIO === 'reply-then-work') {out({ event: 'step_update', step_update: {- conversation_id: 'agy-conversation-1', step_index: turn, state: 'DONE', step_type: 'agent_response',- text_delta: 'partial summary',+ step_index: 1, state: 'DONE', step_type: 'agent_response',usage: { input_tokens: 100, output_tokens: 10, thinking_tokens: 4, cache_read_tokens: 40, total_tokens: 110 },} })+ out({ event: 'step_update', step_update: {+ step_index: 2, state: 'ACTIVE', step_type: 'tool', tool_name: 'run_tests',+ } })+ // The test releases the real work only after the reply and any notification.+ const work = setInterval(() => {+ if (!fs.existsSync(process.env.FAKE_AGY_FINISH)) return+ clearInterval(work)+ out({ event: 'step_update', step_update: {+ step_index: 2, state: 'DONE', step_type: 'tool', tool_info: { name: 'run_tests' },+ } })+ out({ event: 'result', result: {+ conversation_id: 'agy-conversation-1', status: 'SUCCESS', response: 'work completed',+ usage: { input_tokens: 100, output_tokens: 10, thinking_tokens: 4, cache_read_tokens: 40, total_tokens: 110 },+ } })+ }, 10)return}if (process.env.FAKE_AGY_SCENARIO === 'error') {@@ -126,6 +138,10 @@ async function fixture(scenario = 'ok'): Promise<Fixture> {const fake = join(binDir, 'agy')await writeFile(fake, FAKE_AGY, 'utf8')await chmod(fake, 0o755)+ if (IS_WIN) {+ await writeFile(join(binDir, 'agy.cmd'), `@echo off\r\n"${process.execPath}" "%~dp0agy" %*\r\n`, 'utf8')+ }+ process.env.PATH = `${binDir}${delimiter}${ORIGINAL_PATH ?? ''}`return {root, home, log,env: {@@ -133,6 +149,7 @@ async function fixture(scenario = 'ok'): Promise<Fixture> {PATH: `${binDir}${delimiter}${ORIGINAL_PATH ?? ''}`,FAKE_AGY_LOG: log,FAKE_AGY_SCENARIO: scenario,+ FAKE_AGY_FINISH: join(root, 'work-finished'),},}}@@ -152,7 +169,7 @@ async function waitFor(predicate: () => boolean, timeoutMs = 4_000): Promise<voi}}-test('antigravity persistent session uses auto stream-json without inner --sandbox and bills per-turn deltas', { skip: IS_WIN }, async () => {+test('antigravity persistent session uses auto stream-json without inner --sandbox and bills per-turn deltas', async () => {const f = await fixture()const hops: EngineHopReport[] = []const session = getAdapter('antigravity').startSession?.({@@ -200,7 +217,7 @@ test('antigravity persistent session uses auto stream-json without inner --sandbassert.deepEqual(prompts.map((record) => record.event.message.content), ['first prompt', 'second prompt'])})-test('antigravity resumed session passes --conversation and bills step usage without historical double-charging', { skip: IS_WIN }, async () => {+test('antigravity resumed session passes --conversation and bills step usage without historical double-charging', async () => {const f = await fixture('resume-history')const hops: EngineHopReport[] = []const logs: string[] = []@@ -240,7 +257,7 @@ test('antigravity resumed session passes --conversation and bills step usage witassert.equal(start.argv[start.argv.indexOf('--conversation') + 1], 'agy-conversation-resumed')})-test('antigravity keeps its usage baseline across a result that reports no usage', { skip: IS_WIN }, async () => {+test('antigravity keeps its usage baseline across a result that reports no usage', async () => {const f = await fixture('usage-gap')const hops: EngineHopReport[] = []const session = getAdapter('antigravity').startSession?.({@@ -276,7 +293,7 @@ test('antigravity keeps its usage baseline across a result that reports no usageassert.deepEqual(hops.map((hop) => hop.usage), [first.usage, third.usage])})-test('antigravity classify runs in plan mode with --sandbox and honors CUMORA_TRIAGE_MODEL', { skip: IS_WIN }, async () => {+test('antigravity classify runs in plan mode with --sandbox and honors CUMORA_TRIAGE_MODEL', async () => {const f = await fixture()process.env.CUMORA_TRIAGE_MODEL = 'Gemini 3.5 Flash (Low)'const result = await getAdapter('antigravity').classify({@@ -294,7 +311,7 @@ test('antigravity classify runs in plan mode with --sandbox and honors CUMORA_TRassert.equal(start.argv[start.argv.indexOf('--model') + 1], 'Gemini 3.5 Flash (Low)')})-test('antigravity failed result surfaces its reason and still reports spent usage', { skip: IS_WIN }, async () => {+test('antigravity failed result surfaces its reason and still reports spent usage', async () => {const f = await fixture('error')const result = await getAdapter('antigravity').run({home: f.home,@@ -308,7 +325,7 @@ test('antigravity failed result surfaces its reason and still reports spent usagassert.deepEqual(result.usage, { input_tokens: 10, output_tokens: 0, cache_read_input_tokens: 0 })})-test('antigravity seedHome writes AGENTS.md and native workspace skills', { skip: IS_WIN }, async () => {+test('antigravity seedHome writes AGENTS.md and native workspace skills', async () => {const f = await fixture()await getAdapter('antigravity').seedHome(f.home, {id: 'agy-reviewer', name: 'Aster', role: 'Reviewer', systemPrompt: 'Review independently.',@@ -320,7 +337,7 @@ test('antigravity seedHome writes AGENTS.md and native workspace skills', { skipassert.ok(existsSync(join(f.home, '.agents', 'skills')))})-test('antigravity is detected through the agy binary on PATH', { skip: IS_WIN }, async () => {+test('antigravity is detected through the agy binary on PATH', async () => {const f = await fixture()const old = process.env.PATHprocess.env.PATH = f.env.PATH@@ -331,7 +348,7 @@ test('antigravity is detected through the agy binary on PATH', { skip: IS_WIN },}})-test('antigravity inlines the standing prompt once, then only the delta rides each wake', { skip: IS_WIN }, async () => {+test('antigravity inlines the standing prompt once, then only the delta rides each wake', async () => {const f = await fixture()const session = getAdapter('antigravity').startSession?.({home: f.home,@@ -350,7 +367,7 @@ test('antigravity inlines the standing prompt once, then only the delta rides eaawait session.stop()})-test('antigravity resumed conversation already carries the standing prompt', { skip: IS_WIN }, async () => {+test('antigravity resumed conversation already carries the standing prompt', async () => {const f = await fixture('resume-history')const session = getAdapter('antigravity').startSession?.({home: f.home,@@ -363,76 +380,65 @@ test('antigravity resumed conversation already carries the standing prompt', { sawait session.stop()})-test('antigravity ends the post-reply summary hop after the grace and still bills the partial hop', { skip: IS_WIN }, async () => {- const f = await fixture('stall')- process.env.CUMORA_AGY_POST_REPLY_GRACE_MS = '20'- const logs: string[] = []- const session = getAdapter('antigravity').startSession?.({- home: f.home,- env: f.env,- onLog: (line) => logs.push(line),- })- assert.ok(session)-- // The fake never emits `result` — agy is still in its summary hop. Once the- // reply landed, that hop is pure dead time and must not hold the session.- const turn = session.send('reply then stall')- // A real reply lands long after agy's init event; wait for the conversation id- // the session persists so the early end can hand it to the next wake.- await waitFor(() => session.sessionId !== null)- session.noteReplyDelivered?.()- const result = await turn-- assert.equal(result.exitCode, 0, 'an early end is a completed turn, not a failure')- assert.equal(result.error, undefined)- assert.equal(result.sessionId, 'agy-conversation-1', 'the conversation id must survive so the next wake resumes it')- assert.deepEqual(result.usage, { input_tokens: 60, output_tokens: 10, cache_read_input_tokens: 40 })- assert.equal(session.alive, false, 'the stalled process is reaped instead of lingering')- assert.ok(logs.some((line) => line.includes('reply already delivered')))- await session.stop({ force: true })-})--test('antigravity answers a ping that lands after the reply by ending the tail immediately', { skip: IS_WIN }, async () => {- const f = await fixture('stall')- // Grace 0 disables the timer: only the steer path can finish this turn, which- // is exactly the behaviour under test.- process.env.CUMORA_AGY_POST_REPLY_GRACE_MS = '0'- const session = getAdapter('antigravity').startSession?.({- home: f.home,- env: f.env,- onLog: () => {},+for (const notice of ['grace elapsed', 'group notice', 'direct ping'] as const) {+ test(`antigravity keeps working after a progress reply and ${notice}`, { timeout: 10_000 }, async (t) => {+ const f = await fixture('reply-then-work')+ process.env.CUMORA_AGY_POST_REPLY_GRACE_MS = notice === 'grace elapsed' ? '20' : '0'+ const logs: string[] = []+ const hops: EngineHopReport[] = []+ const session = getAdapter('antigravity').startSession?.({+ home: f.home, env: f.env,+ onLog: (line) => logs.push(line),+ onHopUsage: (hop) => hops.push(hop),+ })+ assert.ok(session)+ t.after(() => session.stop({ force: true }))+ const steer = t.mock.method(session, 'steer')++ const runner = new AgentRunner(+ { serverUrl: 'https://server.example.test', computerId: 'fixture', deviceToken: 'fixture' },+ { id: 'agy-fixture', name: 'Fixture', role: null, systemPrompt: null, engine: 'antigravity', model: null, fastModel: null },+ 'antigravity',+ ) as unknown as {+ engineSession: EngineSession+ ensureToken(): Promise<string>+ invokeRuntimeCli(argv: string[], signal: AbortSignal): Promise<{ exitCode?: number }>+ maybeSteer(convo: string): Promise<void>+ }+ runner.engineSession = session+ t.mock.method(runner, 'ensureToken', async () => 'fixture-token')+ t.mock.method(globalThis, 'fetch', async (url: Parameters<typeof fetch>[0]) => String(url).endsWith('/runtime/cli')+ ? Response.json({ text: 'sent', exitCode: 0 })+ : Response.json({ rows: [{+ id: 'message-2', conversation_id: 'room', conversation_kind: 'group',+ author_kind: notice === 'direct ping' ? 'human' : 'agent', body: 'new activity',+ }] }))++ let settled = false+ const turn = session.send('send a progress reply, then finish the tests').then((result) => {+ settled = true+ return result+ })+ await waitFor(() => logs.includes('[antigravity] tool run_tests'))+ const reply = await runner.invokeRuntimeCli(['reply', 'room', 'tests are running'], new AbortController().signal)+ assert.equal(reply.exitCode, 0)+ if (notice !== 'grace elapsed') {+ await runner.maybeSteer('room')+ assert.equal(steer.mock.callCount(), 1, 'the daemon must deliver the notification to the live session')+ }+ await new Promise((resolve) => setTimeout(resolve, 60))+ assert.equal(settled, false, 'a progress reply must not complete an unfinished turn')+ assert.equal(session.alive, true, 'ongoing tool work must not be killed')++ await writeFile(f.env.FAKE_AGY_FINISH!, 'done')+ const result = await turn+ assert.equal(result.exitCode, 0)+ assert.equal(result.sessionId, 'agy-conversation-1')+ assert.deepEqual(result.usage, { input_tokens: 60, output_tokens: 10, cache_read_input_tokens: 40 })+ assert.equal(hops.length, 1)+ assert.deepEqual(hops[0].usage, result.usage)+ assert.equal(hops[0].toolUses, 1, 'the ongoing tool must complete before the turn finishes')+ assert.equal(session.alive, true, 'the completed session stays warm for the next wake')+ await session.stop()})- assert.ok(session)-- const turn = session.send('reply then a teammate pings')- await waitFor(() => session.sessionId !== null)- session.noteReplyDelivered?.()- session.steer('a teammate pinged you')- const result = await turn-- assert.equal(result.exitCode, 0)- assert.equal(result.sessionId, 'agy-conversation-1')- assert.equal(session.alive, false, 'the rerun picks the ping up on a resumed conversation')- await session.stop({ force: true })-})--test('antigravity keeps its tail when no reply landed (steer stays a logged no-op)', { skip: IS_WIN }, async () => {- const f = await fixture()- process.env.CUMORA_AGY_POST_REPLY_GRACE_MS = '20'- const logs: string[] = []- const session = getAdapter('antigravity').startSession?.({- home: f.home,- env: f.env,- onLog: (line) => logs.push(line),- })- assert.ok(session)-- const turn = session.send('a turn with no reply tool call')- session.steer('group noise')- const result = await turn-- assert.equal(result.exitCode, 0)- assert.equal(session.alive, true, 'nothing was delivered, so the running turn is left alone')- assert.ok(logs.some((line) => line.includes('same-turn steer is not supported')))- await session.stop()-})+}diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex e63a8a4..f38c0dc 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -2225,10 +2225,10 @@ export class AgentRunner {return { exitCode: 70, error: `HTTP ${res.status} ${body.slice(0, 200)}`.trim() }}const data = await res.json() as { text?: unknown; exitCode?: unknown }- const text = typeof data.text === 'string' ? data.text : ''- const exitCode = typeof data.exitCode === 'number' ? data.exitCode : 0- if (exitCode === 0) this.noteEngineReplyDelivered(argv, text)- return { text, exitCode }+ return {+ text: typeof data.text === 'string' ? data.text : '',+ exitCode: typeof data.exitCode === 'number' ? data.exitCode : 0,+ }} catch (err) {return { exitCode: 70, error: err instanceof Error ? err.message : String(err) }} finally {@@ -2237,18 +2237,6 @@ export class AgentRunner {}}- /** Forward a LANDED reply to the live engine session. This is the turn's- * user-visible effect: an engine with a post-tool summary hop (agy) can bound- * how long it keeps the session locked after the message is already out.- * A HELD response is NOT a delivery — the reply was withheld and the turn- * still has real work (re-compose), so it must keep its normal tail. */- private noteEngineReplyDelivered(argv: string[], text: string): void {- const command = argv[0]- if (command !== 'reply' && command !== 'send') return- if (/NOT sent/i.test(text)) return- try { this.engineSession?.noteReplyDelivered?.() } catch { /* observability only */ }- }-/** Env handed to the engine subprocess. Secure mode preserves the operator's* original PATH so model-writable <home>/bin cannot shadow the engine binary;* compatibility mode alone exposes its legacy CLI shim there. No server URL@@ -2697,15 +2685,10 @@ export class AgentRunner {// coordinates identically to the cloud pod-agent.GLANCE_YIELD_RULES + `\n\n` +postingMechanicsText(this.promptSurface()) +- // Two cost rules discovered on live `agy` runs:- // 1. The reply tool IS the deliverable. Anything the model writes after it- // returns is a summary nobody reads, but the engine still spends a full- // model hop on it while the session stays locked.- // 2. agy's command-safety monitor flags shell-operator-shaped commands- // (`unquoted_shell_operators`) and re-reviews every one of them with a- // small model — ~1.5s per `cumora` call, on the critical path of a reply.- `Once a \`cumora reply\` / \`send\` returns success the message is already delivered — ` +- `end the turn there. Do NOT restate it, summarise it, or narrate what you just did. ` ++ `After your work is complete and your final \`cumora reply\` returns success, end the turn. ` ++ `Do NOT restate it, summarise it, or narrate what you just did. ` ++ `A progress update or a brief reply to a mid-task ping does not complete your task — continue the work. ` ++ // agy's command-safety monitor re-reviews shell operators on each call.`Keep each \`cumora\` call a SINGLE fully quoted command with no pipes, \`&&\`, or redirection. ` +`When you're answering a ` +`SPECIFIC message, add \`--quote <message_id>\` so your reply threads to its context. ` +diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex f803e44..48f22c0 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -815,13 +815,6 @@ export interface EngineSession {* stream-json boundary so the agent answers a direct ping mid-task, then* continues. No-op if no turn is in flight. */steer(text: string): void- /** The daemon just observed that this turn's user-visible reply actually- * landed (a `cumora reply` / `send` returned success). Engines whose turn- * keeps working after the tool result — agy spends one more model hop on a- * summary the user never reads — use this to bound how long the session- * stays locked after the message is already out. Optional: engines whose- * turn ends with the reply simply ignore it. */- noteReplyDelivered?(): void/** Process is up and stdin is writable. */readonly alive: boolean/** The latest session id seen (to `--resume` if the process must be respawned). */@@ -5565,13 +5558,6 @@ class AntigravityTurnTracker {this.seenResponseSteps.clear()}- /** Usage accrued so far this turn (the per-step `agent_response` sum). Needed- * when a turn is completed early — BEFORE agy emits its terminal `result` —- * so the ledger still bills the work that actually ran. */- partialUsage(): EngineUsage | undefined {- return antigravityUsage(this.turnStepUsage)- }-/** Feed one event. True means the current turn reached its terminal result. */observe(event: AntigravityEvent): boolean {const id = event.conversation_id ?? event.init?.conversation_id ?? event.result?.conversation_id@@ -5631,26 +5617,6 @@ class AntigravityTurnTracker {}}-/** How long the session may stay locked in agy's post-tool summary hop AFTER the- * reply already landed. That hop is invisible to the user (they already have- * the message), yet it holds `pending`, so any ping arriving meanwhile waits.- *- * 60s, and that number is deliberate: ending a turn early is only possible by- * reaping the process (agy has no cancel-turn), which costs a 2.4–4.8s cold- * spawn on the NEXT wake and throws away the warm session this adapter exists- * to keep. So this must sit far ABOVE any healthy hop2 — a live account- * measured 8–15s on a thinking-tier model — and only catch runaway tails.- * Using it as a normal-turn optimisation is a trap: at 8s every turn tripped it- * and the warm session was never reused.- *- * 0 disables the early end entirely (pure protocol behaviour). */-function antigravityPostReplyGraceMs(): number {- const raw = process.env.CUMORA_AGY_POST_REPLY_GRACE_MS- if (raw == null || raw.trim() === '') return 60_000- const n = Number(raw)- return Number.isFinite(n) && n >= 0 ? n : 60_000-}-/** Re-inline the full standing prompt every N turns. `agy` exposes no* system-prompt file, so turn 1 carries it inline; keeping it out of turns* 2..N is what stops a persistent transcript from growing by a whole standing@@ -5673,9 +5639,6 @@ class AntigravitySession implements EngineSession {private standingDelivered: boolean/** Turns completed since the standing prompt was last inlined. */private standingTurns = 0- /** A `cumora reply`/`send` this turn actually landed. */- private replySent = false- private replyGrace: NodeJS.Timeout | null = nullconstructor(command: string,@@ -5724,8 +5687,6 @@ class AntigravitySession implements EngineSession {// daemon.turnPrompt), so an inlined standing prompt is about to enter the// transcript. Remember it on a SUCCESSFUL write only.const inlinedStanding = !this.standingDelivered- this.replySent = false- this.clearReplyGrace()this.tracker.beginTurn()return new Promise((resolve) => {this.pending = { resolve }@@ -5741,31 +5702,8 @@ class AntigravitySession implements EngineSession {})}- /** The daemon saw a `cumora reply`/`send` succeed this turn: the message is- * out, so only agy's summary hop remains. Bound it instead of letting it hold- * the session (and every queued ping) hostage. */- noteReplyDelivered(): void {- if (!this.pending || this.replySent) return- this.replySent = true- const grace = antigravityPostReplyGraceMs()- if (grace <= 0) return- this.replyGrace = setTimeout(() => {- this.replyGrace = null- if (!this.pending) return- this.finishTurnEarly(`reply already delivered — ending agy's post-tool summary hop after ${grace}ms`)- }, grace)- this.replyGrace.unref?.()- }-steer(_text: string): void {if (!this.pending) return- // Once the reply is out there is nothing left to steer into: the only work- // remaining is a summary hop the user never reads. End it now so the daemon's- // coalesced rerun answers the ping immediately instead of waiting the tail out.- if (this.replySent) {- this.finishTurnEarly('a ping arrived after the reply landed — ending the tail so the rerun answers it now')- return- }// The documented protocol requires waiting for a result before the next// user event. Queueing mid-turn would be an undocumented race; the daemon's// normal coalesced wake delivers the ping after this turn instead.@@ -5773,7 +5711,6 @@ class AntigravitySession implements EngineSession {}stop(options: { force?: boolean } = {}): Promise<void> {- this.clearReplyGrace()this.exited = truetry { this.child.stdin?.end() } catch { /* ignore */ }if (options.force) return terminateEngineTree(this.child, true)@@ -5786,33 +5723,6 @@ class AntigravitySession implements EngineSession {return this.stopPromise}- /** Complete the turn WITHOUT agy's terminal `result`, then reap the process.- * Only safe once the turn's user-visible effect already happened (the reply- * landed), so the missing summary cannot lose work. The conversation id is- * persisted by the daemon and the next wake resumes it via `--conversation`. */- private finishTurnEarly(detail: string): void {- if (!this.pending) return- this.opts.onLog(`[antigravity] ${detail}`)- const result: EngineRunResult = {- exitCode: 0,- sessionId: this.tracker.sessionId,- usage: this.tracker.partialUsage(),- model: this.tracker.model,- }- this.clearReplyGrace()- // Flip `exited` BEFORE settling so the close handler's die() finds no pending- // turn and stays silent — no spurious failure, no retry of a delivered reply.- this.exited = true- this.settle(result)- void terminateEngineTree(this.child, true)- }-- private clearReplyGrace(): void {- if (!this.replyGrace) return- clearTimeout(this.replyGrace)- this.replyGrace = null- }-private onStdout(buf: Buffer): void {this.outBuf += this.decoder.write(buf)let newline: number@@ -5872,7 +5782,6 @@ class AntigravitySession implements EngineSession {const pending = this.pendingif (!pending) returnthis.pending = null- this.clearReplyGrace()if (this.standingDelivered) {this.standingTurns += 1if (this.standingTurns >= ANTIGRAVITY_STANDING_REFRESH_TURNS) {