The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Desktop: the own agent says when it tries a model service again (#100)
riverisbuilding0a528f303dae
diff --git a/.changeset/pi-retry-notice.md b/.changeset/pi-retry-notice.mdnew file mode 100644index 0000000..4295f51--- /dev/null+++ b/.changeset/pi-retry-notice.md@@ -0,0 +1,5 @@+---+'@openfilm/desktop': patch+---++Desktop: when the app's own agent tries a model service again after waiting, the chat says so.diff --git a/apps/desktop/src/pi-agent.mjs b/apps/desktop/src/pi-agent.mjsindex d824923..4df4f0f 100644--- a/apps/desktop/src/pi-agent.mjs+++ b/apps/desktop/src/pi-agent.mjs@@ -17,7 +17,7 @@* since the request before.** What Pi does goes to the chat as ACP session updates: its words and thinking as they stream, each tool call (its- * kind, title and input) and its result, and after each answer how full the context is.+ * kind, title and input) and its result, after each answer how full the context is, and a model service tried again.*/import { mkdirSync, writeFileSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';@@ -26,7 +26,7 @@ import * as acp from '@agentclientprotocol/sdk';import { DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, createAgentSession } from '@earendil-works/pi-coding-agent';import { Agent, install, setGlobalDispatcher } from 'undici';import { agentSessionsDir, openLog } from './chat-store.mjs';-import { THINKING, WAIT_MINUTES, contextUsed, effortOption, modelOption, modelsJson, providerOf, stopReason, toolCall, toolContent } from './pi-config.mjs';+import { THINKING, WAIT_MINUTES, contextUsed, effortOption, modelOption, modelsJson, providerOf, retryNotice, stopReason, toolCall, toolContent } from './pi-config.mjs';/* stdout is the protocol's: anything else Pi or a library prints goes to stderr */console.log = console.info = console.warn = console.debug = (...args) => process.stderr.write(`${args.map(String).join(' ')}\n`);@@ -186,6 +186,10 @@ async function open(client, cwd, resumeId) {send({ sessionUpdate: 'tool_call_update', toolCallId: event.toolCallId, status: event.isError ? 'failed' : 'completed',content: toolContent(event.result), rawOutput: event.result?.content?.filter?.((b) => b?.type === 'text').map((b) => b.text).join('\n') ?? '' });break;+ case 'auto_retry_start':+ /* the service failed or sent nothing in time, and Pi tries again: the chat says so (nothing once it answers) */+ send(retryNotice(event));+ break;case 'compaction_end':/* Pi could not make room for the conversation: the turn ends on that (its last answer may not say it) */if (event.reason === 'overflow' && event.errorMessage) entry.overflow = event.errorMessage;diff --git a/apps/desktop/src/pi-agent.test.mjs b/apps/desktop/src/pi-agent.test.mjsindex ff904f8..1ae758f 100644--- a/apps/desktop/src/pi-agent.test.mjs+++ b/apps/desktop/src/pi-agent.test.mjs@@ -7,7 +7,7 @@ import { join } from 'node:path';import { AgentSession } from './agents.mjs';/** A service on the Chat Completions API that answers "ok" and notes the model each request named (and each request, and its key). */-async function service({ broke = false, fails = null } = {}) {+async function service({ broke = false, fails = null, busyOnce = false } = {}) {const asked = [];const bodies = [];const keys = [];@@ -20,6 +20,7 @@ async function service({ broke = false, fails = null } = {}) {bodies.push(JSON.parse(body || '{}'));keys.push(String(req.headers.authorization ?? ''));if (broke) { res.writeHead(402, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: { message: 'Insufficient Balance' } })); return; }+ if (busyOnce && asked.length === 1) { res.writeHead(503, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: { message: 'The service is busy.' } })); return; }if (fails) { res.writeHead(400, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: { message: fails } })); return; }res.writeHead(200, { 'content-type': 'text/event-stream' });const chunk = (choice, extra = {}) => `data: ${JSON.stringify({ id: 'c', object: 'chat.completion.chunk', created: 0, model, choices: [choice], ...extra })}\n\n`;@@ -172,3 +173,27 @@ test('a conversation too long for the model says so, and where its context is sesvc.close();}});++test('a service that fails and is tried again says so in the chat as a notice, and the turn goes on', { timeout: 60_000 }, async () => {+ const svc = await service({ busyOnce: true });+ const updates = [];+ const session = new AgentSession({+ agent: 'byok',+ cwd: mkdtempSync(join(tmpdir(), 'of-pi-')),+ harness: { home: mkdtempSync(join(tmpdir(), 'of-pi-home-')), models: [own('a', svc.url)], model: 'a', env: { OPENFILM_BYOK_KEY_a: 'sk' } },+ onUpdate: (update) => updates.push(update),+ });+ try {+ await session.start();+ assert.equal(await session.prompt([{ type: 'text', text: 'hi' }]), 'end_turn');+ assert.equal(svc.asked.length, 2, 'asked twice');+ const notices = updates.filter((u) => u.sessionUpdate === 'notice');+ assert.equal(notices.length, 1, 'one notice, and none once it answers');+ assert.equal(notices[0].severity, 'warning');+ assert.equal(notices[0].title, 'The model service failed; trying again (1 of 1).');+ assert.match(notices[0].description, /The service is busy/);+ } finally {+ session.close();+ svc.close();+ }+});diff --git a/apps/desktop/src/pi-config.mjs b/apps/desktop/src/pi-config.mjsindex 5665c1e..a1d2e16 100644--- a/apps/desktop/src/pi-config.mjs+++ b/apps/desktop/src/pi-config.mjs@@ -168,6 +168,17 @@ export function failureText(said) {return text;}+/**+ * Pi trying a model service again after it failed (its `auto_retry_start`), as the notice the chat shows: a service that+ * sent nothing in time in plain words, anything else with Pi's own.+ */+export function retryNotice(event) {+ const said = String(event?.errorMessage ?? '').trim();+ const again = `trying again (${event?.attempt ?? 1} of ${event?.maxAttempts ?? 1}).`;+ if (TIMED_OUT.test(said)) return { sessionUpdate: 'notice', severity: 'warning', title: `The model service didn't answer for ${WAIT_MINUTES} minutes; ${again}` };+ return { sessionUpdate: 'notice', severity: 'warning', title: `The model service failed; ${again}`, ...(said ? { description: said } : {}) };+}+/** How full the context is after an answer (ACP usage_update): what the conversation takes, of the model's window. */export function contextUsed(message, model) {const u = message?.usage;diff --git a/apps/desktop/src/pi-config.test.mjs b/apps/desktop/src/pi-config.test.mjsindex 23574f9..fce0b2e 100644--- a/apps/desktop/src/pi-config.test.mjs+++ b/apps/desktop/src/pi-config.test.mjs@@ -1,6 +1,6 @@import { test } from 'node:test';import assert from 'node:assert/strict';-import { THINKING, contextLength, contextUsed, effortOption, failureText, modelEffort, modelOption, modelsJson, outOfBalance, providerOf, stopReason, toolCall, toolContent } from './pi-config.mjs';+import { THINKING, contextLength, contextUsed, effortOption, failureText, modelEffort, modelOption, modelsJson, outOfBalance, providerOf, retryNotice, stopReason, toolCall, toolContent } from './pi-config.mjs';/** One of the person's own models, as the roster's harness gives it. */const own = (id, over = {}) => ({ id, name: id.toUpperCase(), api: 'openai-completions', baseUrl: `https://${id}.test/v1`, keyEnv: `K_${id}`, model: `${id}-model`, levels: ['auto'], effort: 'auto', ...over });@@ -110,3 +110,12 @@ test('why a turn failed, in plain words: a service that sent nothing in time, aassert.equal(failureText('401 Incorrect API key provided'), '401 Incorrect API key provided');assert.equal(failureText('terminated'), 'terminated', 'a connection cut off is not said to be a timeout');});++test('a model service tried again, as a notice: one that sent nothing in time in plain words, else with what Pi said', () => {+ assert.deepEqual(retryNotice({ type: 'auto_retry_start', attempt: 1, maxAttempts: 1, delayMs: 2000, errorMessage: 'Request timed out.' }), {+ sessionUpdate: 'notice', severity: 'warning', title: "The model service didn't answer for 15 minutes; trying again (1 of 1).",+ });+ assert.deepEqual(retryNotice({ type: 'auto_retry_start', attempt: 1, maxAttempts: 2, delayMs: 2000, errorMessage: '503 Service Unavailable' }), {+ sessionUpdate: 'notice', severity: 'warning', title: 'The model service failed; trying again (1 of 2).', description: '503 Service Unavailable',+ });+});