Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.
TypeScript agentai-agentai-agentsai-assistantandroidautomationchatgptcoding-agentcomputer-usedesktop-appelectronllmlocal-firstmcpmulti-agentollamaopenaiprivacyself-hostedtypescript
fix(chat): a slow start waits for Bot and model info instead of failing
leen.zhoua00d2bf07ee9
diff --git a/apps/desktop/src/renderer/features/chat/screen/chat-history-view.tsx b/apps/desktop/src/renderer/features/chat/screen/chat-history-view.tsxindex 964ab0a..a8a5b0b 100644--- a/apps/desktop/src/renderer/features/chat/screen/chat-history-view.tsx+++ b/apps/desktop/src/renderer/features/chat/screen/chat-history-view.tsx@@ -127,9 +127,9 @@ export function renderChatHistory(screen: ChatScreenModel) {className={styles.messages}style={userBubbleStyle(state.bot?.avatarColor)}>- {state.loading && (+ {(state.loading || state.metadataRetrying) && (<p className={styles.notice} role="status">- {t("chat.loadingHistory")}+ {t(state.metadataRetrying ? "chat.metadataWaiting" : "chat.loadingHistory")}</p>)}{(state.historyError || state.metadataError || workplaces.error || topicPlace.error) && (diff --git a/packages/client-core/src/chat/metadata.ts b/packages/client-core/src/chat/metadata.tsindex d8f23c1..043a7cd 100644--- a/packages/client-core/src/chat/metadata.ts+++ b/packages/client-core/src/chat/metadata.ts@@ -2,6 +2,61 @@ import { type Bot, canonicalImageModelId, RpcError, RpcErrorCodes } from "@pibotimport { readMainBot } from "./main-bot.ts";import type { ChatSession } from "./session.ts";+/** A slow start (brain ready after ~25 s under load) answers its first catalog reads late. */+const STARTUP_PATIENCE_MS = 60_000;+const RETRY_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];++/**+ * Failures that say "not answered yet" rather than "the brain answered no": a deadline, a busy+ * queue, a port replaced mid-read, or a lane cancelled by its own 30 s deadline. A real answer+ * (internal, invalid params, a missing Bot) is shown at once.+ */+function notAnsweredYet(error: unknown) {+ if (error instanceof RpcError)+ return (+ error.code === RpcErrorCodes.timeout ||+ error.code === RpcErrorCodes.closed ||+ error.code === RpcErrorCodes.busy+ );+ return (+ (error instanceof Error || error instanceof DOMException) &&+ (error.name === "AbortError" || error.message === "Read capacity reached")+ );+}++function pause(ms: number, signal: AbortSignal) {+ return new Promise<void>((resolve, reject) => {+ const done = () => {+ clearTimeout(timer);+ signal.removeEventListener("abort", done);+ if (signal.aborted) reject(signal.reason);+ else resolve();+ };+ const timer = setTimeout(done, ms);+ signal.addEventListener("abort", done, { once: true });+ });+}++/** Retries unanswered reads with backoff until the patience window closes, then rethrows. */+async function patiently<T>(+ operation: () => Promise<T>,+ signal: AbortSignal,+ waiting: () => void,+ started = Date.now(),+): Promise<T> {+ for (let attempt = 0; ; attempt++) {+ try {+ return await operation();+ } catch (error) {+ signal.throwIfAborted();+ const delay = RETRY_DELAYS_MS[Math.min(attempt, RETRY_DELAYS_MS.length - 1)] as number;+ if (!notAnsweredYet(error) || Date.now() - started + delay > STARTUP_PATIENCE_MS) throw error;+ waiting();+ await pause(delay, signal);+ }+ }+}+export async function readBot(this: ChatSession, signal: AbortSignal) {signal.throwIfAborted();if (this.target.botId) {@@ -43,18 +98,32 @@ export async function refreshMetadata(this: ChatSession, confirmedBot?: Bot) {const version = ++this.metadataVersion;const botVersion = this.botVersion;const previous = this.state.bot;- this.patch({ metadataLoading: true, metadataError: false });+ this.patch({ metadataLoading: true, metadataError: false, metadataRetrying: false });try {// Read the selected catalog for the confirmed save, without replacing it with an older profile.const signal = AbortSignal.any([read.signal, this.lifetime.signal]);- this.identityRead = confirmedBot ? Promise.resolve(confirmedBot) : this.readBot(signal);+ const started = Date.now();+ // Only this refresh may say it is waiting; a newer one owns the flag from its first patch.+ const waiting = () => {+ if (this.metadataRead === read && !this.state.metadataRetrying)+ this.patch({ metadataRetrying: true });+ };+ this.identityRead = confirmedBot+ ? Promise.resolve(confirmedBot)+ : patiently(() => this.readBot(signal), signal, waiting, started);// Most Bots are text Bots: read the model list beside the identity, not after it, so it joins// the catalog read the same mount starts instead of following it as a second request.const readModels = () =>- this.reads.read(- "models:available",- (signal) => this.peer.call("models.list", { availableOnly: true }, { signal }),+ patiently(+ () =>+ this.reads.read(+ "models:available",+ (signal) => this.peer.call("models.list", { availableOnly: true }, { signal }),+ signal,+ ),signal,+ waiting,+ started,);const early = (confirmedBot ?? previous)?.category === "image" ? undefined : readModels();// Unused if the Bot turns out to be an image Bot; the finally block releases the lane.@@ -66,19 +135,28 @@ export async function refreshMetadata(this: ChatSession, confirmedBot?: Bot) {this.patch({ bot, metadataError: !bot });const images =bot?.category === "image" && bot.modelProvider && bot.modelId- ? await this.reads.read(- `images:${bot.modelProvider}:${bot.modelId}`,- (signal) =>- this.peer.call(- "models.images",- {- availableOnly: true,- selected: { provider: bot.modelProvider as string, id: bot.modelId as string },- limit: 1,- },- { signal },+ ? await patiently(+ () =>+ this.reads.read(+ `images:${bot.modelProvider}:${bot.modelId}`,+ (signal) =>+ this.peer.call(+ "models.images",+ {+ availableOnly: true,+ selected: {+ provider: bot.modelProvider as string,+ id: bot.modelId as string,+ },+ limit: 1,+ },+ { signal },+ ),+ signal,),signal,+ waiting,+ started,): [];const image = images.find(@@ -103,12 +181,12 @@ export async function refreshMetadata(this: ChatSession, confirmedBot?: Bot) {void this.checkContextHint();} catch {if (!read.signal.aborted && version === this.metadataVersion && botVersion === this.botVersion)- this.patch({ metadataError: true });+ this.patch({ metadataError: true, metadataRetrying: false });} finally {read.abort();if (this.metadataRead === read) {this.metadataRead = undefined;- this.patch({ metadataLoading: false });+ this.patch({ metadataLoading: false, metadataRetrying: false });}}}diff --git a/packages/client-core/src/chat/types.ts b/packages/client-core/src/chat/types.tsindex ec92a95..621bf61 100644--- a/packages/client-core/src/chat/types.ts+++ b/packages/client-core/src/chat/types.ts@@ -53,6 +53,8 @@ export interface ChatState {historyError: boolean;metadataError: boolean;metadataLoading: boolean;+ /** A Bot or model read went unanswered (slow start) and is being retried; not an error yet. */+ metadataRetrying?: boolean;loadingMore: boolean;hasMore: boolean;pending: boolean;diff --git a/packages/i18n/src/sections/chat.ts b/packages/i18n/src/sections/chat.tsindex c10329a..d550cd9 100644--- a/packages/i18n/src/sections/chat.ts+++ b/packages/i18n/src/sections/chat.ts@@ -197,6 +197,7 @@ export const chatZh = {"errors.mention_unresolved":"这个 @ 对应不上群里唯一的一个 Bot。请从 @ 列表里选出要找的 Bot 再发送。","chat.metadataError": "无法加载 Bot 和模型信息,请重试。",+ "chat.metadataWaiting": "Bot 和模型信息还在加载,请稍等…","chat.stopError": "停止请求失败,请再点一次停止。","chat.sendUncertain": "未能确认消息是否发送成功。请查看聊天记录后再重试。","chat.retryNeedsHistory": "加载更早的消息后可以重试。",@@ -448,6 +449,7 @@ export const chatEn: { [K in keyof typeof chatZh]: string } = {"errors.mention_unresolved":"This @mention doesn’t match exactly one Bot in the group. Pick the Bot from the @ list, then send again.","chat.metadataError": "Couldn’t load the Bot and model information. Please try again.",+ "chat.metadataWaiting": "Still loading the Bot and model information…","chat.stopError": "Couldn’t stop the reply. Please press Stop again.","chat.sendUncertain":"Couldn’t confirm whether the message was sent. Check the chat history before retrying.",