π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(chat): show the run status tray without waiting for the gateway handshake (#19745)
Arvin Xue809cc9f40c9
diff --git a/packages/trpc/src/client/lambda.test.ts b/packages/trpc/src/client/lambda.test.tsindex 046d52866c1..34a5b85a28c 100644--- a/packages/trpc/src/client/lambda.test.ts+++ b/packages/trpc/src/client/lambda.test.ts@@ -73,6 +73,86 @@ describe('lambdaClient large-input query transport', () => {);});+describe('lambdaClient transport lanes', () => {+ const fetchMock = vi.fn();++ // A batched request expects an array body with one entry per operation in it+ // (the procedures are comma-joined in the path); an unbatched one expects the+ // plain result object. Answering both shapes keeps a wrongly-shared batch from+ // failing as a transport error instead of the assertion that describes it.+ const respondByLane = (input: RequestInfo | URL) => {+ const url = String(input);+ if (!url.includes('batch=1')) return Promise.resolve(okTrpcResponse(null));++ const procedures = url.split('/trpc/lambda/')[1]?.split('?')[0]?.split(',') ?? [''];+ return Promise.resolve(+ new Response(+ JSON.stringify(procedures.map(() => ({ result: { data: superjson.serialize(null) } }))),+ { headers: { 'content-type': 'application/json' }, status: 200 },+ ),+ );+ };++ const requestedUrls = () =>+ fetchMock.mock.calls.map(([input]) => String(input as RequestInfo | URL));++ beforeEach(() => {+ vi.stubGlobal('fetch', fetchMock);+ vi.stubGlobal('location', new URL('http://localhost/chat'));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ fetchMock.mockReset();+ });++ // Regression: every `device.*` read hops from the server to one of the user's+ // own machines and is capped by a 10-60s RPC timeout. Batched with ordinary+ // lambda reads, one sleeping laptop held the whole batch's response β opening a+ // topic with a working directory fires several such hops at once, which is what+ // made an obviously-live run render as idle after a topic switch.+ it('keeps device.* hops out of the batch carrying ordinary lambda reads', async () => {+ fetchMock.mockImplementation(respondByLane);++ await Promise.all([+ lambdaClient.device.gitBranch.query({ deviceId: 'dev_1', path: '/repo' }),+ lambdaClient.agent.getAgentConfigById.query({ agentId: 'agt_test' }),+ ]);++ expect(fetchMock).toHaveBeenCalledTimes(2);+ const urls = requestedUrls();+ expect(+ urls.some(+ (url) => url.includes('device.gitBranch') && !url.includes('agent.getAgentConfigById'),+ ),+ ).toBe(true);+ expect(+ urls.some(+ (url) => url.includes('agent.getAgentConfigById') && !url.includes('device.gitBranch'),+ ),+ ).toBe(true);+ });++ // The gateway reconnect cannot register its local operation β and so cannot+ // show the status tray, the sidebar elapsed time or the stop button β until+ // this token comes back. It is a cheap read; it must never queue behind a+ // slower sibling in the shared batch.+ it('sends the gateway token refresh as its own unbatched request', async () => {+ fetchMock.mockImplementation(respondByLane);++ await Promise.all([+ lambdaClient.aiAgent.refreshGatewayToken.query({ topicId: 'tpc_1' }),+ lambdaClient.agent.getAgentConfigById.query({ agentId: 'agt_test' }),+ ]);++ expect(fetchMock).toHaveBeenCalledTimes(2);+ const tokenUrl = requestedUrls().find((url) => url.includes('aiAgent.refreshGatewayToken'));+ expect(tokenUrl).toBeDefined();+ expect(tokenUrl).not.toContain('batch=1');+ expect(tokenUrl).not.toContain('agent.getAgentConfigById');+ });+});+describe('lambdaClient unreadable response handling', () => {const fetchMock = vi.fn();diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.tsindex 23b167621da..034444d015e 100644--- a/packages/trpc/src/client/lambda.ts+++ b/packages/trpc/src/client/lambda.ts@@ -201,7 +201,31 @@ const initialLoadProcedures = new Set(['user.getUserState', 'config.getGlobalCon// its `JSON.parse` with `Unexpected token '<'`. Split it out so a slow message// read only slows itself.const slowProcedures = new Set(['market.getAssistantList', 'message.getMessages']);-const SKIP_BATCH_PROCEDURES = new Set([...initialLoadProcedures, ...slowProcedures]);+// Procedures whose latency is felt directly as "the UI is stuck". The gateway+// token refresh gates every reconnect: until it answers, the client cannot+// register the local operation that drives the status tray, the sidebar elapsed+// time and the stop button β so a topic switch shows a live run as idle for as+// long as the slowest procedure sharing its batch. It is a cheap read; give it+// its own request instead of the shared queue.+const latencyCriticalProcedures = new Set([+ 'aiAgent.refreshGatewayToken',+ // The share-visitor mirror of the same reconnect handshake.+ 'shareChat.refreshGatewayToken',+]);+const SKIP_BATCH_PROCEDURES = new Set([+ ...initialLoadProcedures,+ ...slowProcedures,+ ...latencyCriticalProcedures,+]);++// Every `device.*` read leaves the server and hops to one of the user's own+// machines, where the server waits out a 10-60s RPC timeout if that machine is+// asleep, offline or busy. Batched with ordinary lambda reads, one such hop+// holds the whole batch's response β opening a topic with a working directory+// fires several of them at once (git branch / ahead-behind / working tree /+// linked PR / agent quota). Keep them batched among themselves, but in their+// own dataloader so they can only ever delay each other.+const DEVICE_RPC_PREFIX = 'device.';// Queries whose input can exceed the GET URL budget (`maxURLLength` 2083):// the transfer-job status poll sends the visible-topic candidate set (up to@@ -223,7 +247,14 @@ const buildHttpLinks = (options: typeof linkOptions) =>condition: (op) => LARGE_INPUT_QUERY_PROCEDURES.has(op.path),false: splitLink({condition: (op) => SKIP_BATCH_PROCEDURES.has(op.path),- false: httpBatchLink({ ...options, maxURLLength: 2083 }),+ false: splitLink({+ condition: (op) => op.path.startsWith(DEVICE_RPC_PREFIX),+ // Two distinct link instances on purpose: each `httpBatchLink` owns its+ // own dataloader, which is what keeps the device hops in a separate HTTP+ // request from everything else.+ false: httpBatchLink({ ...options, maxURLLength: 2083 }),+ true: httpBatchLink({ ...options, maxURLLength: 2083 }),+ }),true: httpLink(options),}),true: httpLink({ ...options, methodOverride: 'POST' }),diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 142a41612aa..0a9d1d87d01 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -3037,9 +3037,65 @@ describe('GatewayActionImpl', () => {const action = new GatewayActionImpl(set as any, get, undefined);action.createClient = vi.fn(() => createMockClient());- return { action, captured, connectToGateway, internalDispatchTopic };+ return {+ action,+ captured,+ completeOperation,+ connectToGateway,+ internalDispatchTopic,+ startOperation,+ };}+ // Regression: the status tray, the topic-list elapsed time and the stop+ // button are all driven by this local operation, and creating it only after+ // `refreshGatewayToken` resolved made them wait on a round trip that shares+ // the batched tRPC lane β so switching into a topic whose run was plainly+ // alive showed an idle composer for as long as the slowest procedure in that+ // batch. The marker already proves the run exists; register off it at once.+ it('registers the local operation before the token refresh resolves', async () => {+ const { action, connectToGateway, startOperation } = createSeededReconnectHarness();+ let releaseToken: (value: { token: string }) => void = () => {};+ vi.mocked(aiAgentService.refreshGatewayToken).mockReturnValueOnce(+ new Promise<{ token: string }>((resolve) => {+ releaseToken = resolve;+ }),+ );++ const pending = action.reconnectToGatewayOperation({+ assistantMessageId: 'ast-1',+ operationId: 'server-op-1',+ topicId: 'topic-1',+ });++ // Synchronously after the call: the token request is still in flight.+ expect(startOperation).toHaveBeenCalledTimes(1);+ expect(connectToGateway).not.toHaveBeenCalled();++ releaseToken({ token: 'fresh-token' });+ await pending;++ expect(connectToGateway).toHaveBeenCalled();+ });++ // The operation is created optimistically off the marker, so every bail-out+ // has to retire it β otherwise a stale marker leaves the composer spinning+ // on a run that nothing will ever settle.+ it('retires the optimistic operation when refreshGatewayToken returns NOT_FOUND', async () => {+ const { action, completeOperation } = createSeededReconnectHarness();+ vi.mocked(aiAgentService.refreshGatewayToken).mockRejectedValueOnce({+ data: { code: 'NOT_FOUND' },+ });++ await action.reconnectToGatewayOperation({+ assistantMessageId: 'ast-1',+ operationId: 'server-op-1',+ topicId: 'topic-1',+ });++ expect(completeOperation).toHaveBeenCalledWith('gw-op-reconnect');+ });+// Regression: a stale local runningOperation fires a reconnect,// but the server already cleared its marker and answers refreshGatewayToken// with TRPC NOT_FOUND. The reconnect must clear the local marker and baildiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 927fc29bf49..2db8070042e 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -1349,34 +1349,6 @@ export class GatewayActionImpl {?.runningOperation?.operationId;if (topicCurrentOpId && topicCurrentOpId !== operationId) return;- // Get a fresh JWT token (original expired after 5 min). The server throws- // TRPCError NOT_FOUND when it has no running operation on this topic β our- // local marker is stale (e.g. an error run cleared the server marker but not- // the store). Clear it and bail silently so the reconnect SWR fetcher resolves- // and does not retry the 404 forever.- let token: string;- try {- // Share visitors have no owner-scoped access to `aiAgentService.refreshGatewayToken`- // (its TopicModel is scoped to the caller, and share topics belong to the- // creator) β see the param JSDoc above for why the visitor mirror is used instead.- ({ token } = agentShareId- ? await shareChatService.refreshGatewayToken(agentShareId, topicId)- : await aiAgentService.refreshGatewayToken(topicId));- } catch (error) {- if (isTrpcErrorCode(error, 'NOT_FOUND')) {- this.clearLocalRunningOperation({ operationId, topicId });- return;- }- throw error;- }-- // Re-check after the async token refresh: a newer executeGatewayAgent call may have- // taken over for this topic while we were waiting. If so, bail to avoid a duplicate stream.- // (disconnectFromGateway on the stale op is a no-op here because we haven't connected yet.)- const topicOpIdAfterRefresh = topicSelectors.getTopicById(topicId)(this.#get())?.metadata- ?.runningOperation?.operationId;- if (topicOpIdAfterRefresh && topicOpIdAfterRefresh !== operationId) return;-const agentId = params.agentId ?? this.#get().activeAgentId;// Carry agentShareId the same way executeGatewayAgent's execution context// does β `createGatewayEventHandler` branches on `context.agentShareId` to@@ -1417,8 +1389,16 @@ export class GatewayActionImpl {const startTime = [markerStartedAt, assistantMessageStart].find(Number.isFinite);- // Create a local operation for UI loading state, stashing the server op id- // so intervention flows can find it after reconnect as well.+ // Create the local operation BEFORE the token refresh below. The marker this+ // reconnect is acting on already proves the topic is running, and this+ // operation is what every "a run is in flight" surface reads β the status+ // tray, the topic-list elapsed time, the stop button. Creating it after the+ // refresh made all of them wait on a round trip that shares the batched tRPC+ // lane, where one slow sibling (a `device.*` git/quota hop to the user's own+ // machine, up to its 15s server timeout) left an obviously-live run looking+ // idle for seconds after every topic switch. Each bail-out below retires it.+ // The server op id is stashed so intervention flows can find it after+ // reconnect as well.const { operationId: gatewayOpId } = this.#get().startOperation({context,metadata: {@@ -1446,6 +1426,42 @@ export class GatewayActionImpl {await interruptGatewayTaskOrThrow({ operationId });});+ // Get a fresh JWT token (original expired after 5 min). The server throws+ // TRPCError NOT_FOUND when it has no running operation on this topic β our+ // local marker is stale (e.g. an error run cleared the server marker but not+ // the store). Clear it and bail silently so the reconnect SWR fetcher resolves+ // and does not retry the 404 forever.+ let token: string;+ try {+ // Share visitors have no owner-scoped access to `aiAgentService.refreshGatewayToken`+ // (its TopicModel is scoped to the caller, and share topics belong to the+ // creator) β see the param JSDoc above for why the visitor mirror is used instead.+ ({ token } = agentShareId+ ? await shareChatService.refreshGatewayToken(agentShareId, topicId)+ : await aiAgentService.refreshGatewayToken(topicId));+ } catch (error) {+ // The operation above was created on the strength of the marker; a refusal+ // (or a transport failure SWR may retry) means no stream is coming, so+ // retire it instead of leaving a spinner nothing will ever settle.+ this.#get().completeOperation(gatewayOpId);++ if (isTrpcErrorCode(error, 'NOT_FOUND')) {+ this.clearLocalRunningOperation({ operationId, topicId });+ return;+ }+ throw error;+ }++ // Re-check after the async token refresh: a newer executeGatewayAgent call may have+ // taken over for this topic while we were waiting. If so, bail to avoid a duplicate stream.+ // (disconnectFromGateway on the stale op is a no-op here because we haven't connected yet.)+ const topicOpIdAfterRefresh = topicSelectors.getTopicById(topicId)(this.#get())?.metadata+ ?.runningOperation?.operationId;+ if (topicOpIdAfterRefresh && topicOpIdAfterRefresh !== operationId) {+ this.#get().completeOperation(gatewayOpId);+ return;+ }+const eventHandler = createGatewayEventHandler(this.#get, {assistantMessageId,context,