π€― 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): create the subtopic on the gateway send path (#18736)
Arvin Xuc7f975b707a3
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 568ad9b29ca..ff7df60fd61 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -863,6 +863,84 @@ code A/B, re-dispatch after each edit rather than expecting react-refresh to keethe messages β and re-run the identical dispatch + expand + scroll sequence on bothsides so the two frames differ only by the change.+#### A client bucket that keeps reverting mid-run is the gateway `uiMessages` snapshot, not your write++**Situation:** a store bucket (`dbMessagesMap[<key>]`) holds the right messages right+after a gateway send, then silently loses them a second or two later and stays wrong+for the rest of the session β while the database is correct the whole time.++**Doesn't work:** treating it as a race in your own write and adding another+`replaceMessages` / refetch earlier in the flow. The overwrite happens _after_ every+write you control, so each new attempt is undone the same way. It also looks like a+stale SWR tier (which it is not β a manual `refreshMessages()` fixes it, so the+server clearly has the data).++**Works:** the server pushes a canonical `uiMessages` snapshot at `step_start` and+`agent_runtime_end`, and `gatewayEventHandler` applies it as source of truth. That+snapshot is built by `AgentRuntimeService.queryUiMessages` from the operation's+`state.metadata`, so it is only as scoped as that metadata β a field the run needs+but the snapshot query omits makes every step boundary overwrite the bucket with a+_differently scoped_ message list. Identify the writer instead of guessing: record+every `replaceMessages` call with `new Error().stack` into a `window.__RM` ring+buffer, run the flow once, and read `action` (`gateway/step_start`,+`gateway/agent_runtime_end`) plus the frame. The `action` label alone names the+culprit. Verified in this catalogue: a subtopic run whose snapshot lacked `threadId`+kept replacing the thread's bucket with the topic's main spine.++**Corollary β use the non-gateway path as the control.** The same UI action with+`chatConfig.disableGatewayMode = true` runs through `sendMessageInServer` and never+applies a pushed snapshot. If the behavior is correct there and wrong in gateway+mode, the defect is in the gateway transport or in the server snapshot, and you have+halved the search space before reading any code.++#### `curl /health` does not prove the local agent-gateway trusts your key β run the JWT probe++**Situation:** restarting the local agent-gateway between acceptance rounds and+gating on `curl -s -o /dev/null -w '%{http_code}' http://localhost:<port>/health`.++**Doesn't work:** treating a 200 as "the closed loop is up". `/health` answers before+any key is checked, so it is equally 200 when `.dev.vars` carries a JWKS that has+nothing to do with the app's. The failure then surfaces far from its cause: runs+complete server-side (`agent_operations` = `done`, full content in `messages`) while+the browser's `execServerAgentRuntime` op ends after \~100ms, the assistant bubble+stays on the `...` placeholder for the rest of the session, and a cold reload shows+the reply β reading exactly like a client-side streaming regression in the branch+under test. The tells are `chat().gatewayConnections === {}`, no `GET /ws` in the+gateway log (only serverβgateway `push-event` lines, which use the static service+token and keep working), and `[Gateway] Auth failed ... signature verification+failed` in the browser console.++**Works:** after every gateway (re)start, run the decisive handshake and require+`auth_success` before collecting any evidence:++```bash+GATEWAY_PORT= < port > .agents/acceptance/scripts/agent-gateway/local-gateway-setup.sh+GATEWAY_WS=ws://localhost: .agents/acceptance/scripts/agent-gateway/local-gateway-probe.mjs < port > node+```++`.dev.vars` is regenerated per app instance, so restoring it at teardown (or another+worktree regenerating it) silently invalidates it for the next run β compare the+`kid` in `agent-gateway/.dev.vars` against `.records/env/agent-testing-jwks.json`+when in doubt.++#### A required local service can be someone else's, and `preflight` will not tell you++**Situation:** starting QStash / s3rver for a run through `init-dev-env.sh` in a+worktree while another agent-testing session is already active on the machine.++**Doesn't work:** trusting that a backgrounded `init-dev-env.sh qstash` (or `s3`)+came up because `preflight` then reports the service reachable. Both use fixed ports+(8080 / 29000), so the second starter dies immediately with+`address already in use` while the sibling session's process keeps answering β and+`preflight` is a reachability check, so it passes. The run works, but on services it+does not own.++**Works:** read the start log before assuming ownership+(`.records/logs/qstash.log`, `.records/logs/s3.log`), and treat "already in use" as+"this is not mine". It matters at teardown: stopping a service you did not start+kills the other session's run. Only the dev server (`stop-dev`, which verifies PID+ownership) and anything you launched on a port you chose yourself are yours to stop.+#### Infinite-scroll failure statesWhen the fixture is too short for the observer to fire, call the real load-morediff --git a/.agents/acceptance/references/agent-gateway.md b/.agents/acceptance/references/agent-gateway.mdindex 37be4d98250..ca73cac24a0 100644--- a/.agents/acceptance/references/agent-gateway.md+++ b/.agents/acceptance/references/agent-gateway.md@@ -37,10 +37,18 @@ local JWT β `auth_success` β full local loop..agents/acceptance/scripts/agent-gateway/local-gateway-setup.sh# 2. Start the worker (separate terminal) β http://localhost:8787+# 8787 is a shared default: the sibling `device-gateway/` repo's worker uses it+# too, and another session may already own it. Check first, and take your own+# port rather than restarting someone else's worker β `.dev.vars` is shared, so+# regenerating it against YOUR JWKS breaks whoever is running on it.+# lsof -nP -iTCP:8787 -sTCP:LISTEN # inspect the owning process path+# GATEWAY_PORT=8788 .../local-gateway-setup.sh && bunx wrangler dev --port 8788+# Back `agent-gateway/.dev.vars` up before regenerating it, and restore at teardown.cd ../agent-gateway && bun run devcurl -s -o /dev/null -w '%{http_code}\n' http://localhost:8787/health # β 200# 3. Decisive check β does the local gateway accept the app's JWT?+# (add GATEWAY_WS=ws://localhost:<port> when not on 8787)node .agents/acceptance/scripts/agent-gateway/local-gateway-probe.mjs# β RECV: {"type":"auth_success"} β feasiblediff --git a/.agents/acceptance/scripts/agent-gateway/local-gateway-probe.mjs b/.agents/acceptance/scripts/agent-gateway/local-gateway-probe.mjsindex 642ebe6d4ac..2647167e5a8 100644--- a/.agents/acceptance/scripts/agent-gateway/local-gateway-probe.mjs+++ b/.agents/acceptance/scripts/agent-gateway/local-gateway-probe.mjs@@ -25,18 +25,44 @@ import { importJWK, SignJWT } from 'jose';const WS_BASE = process.env.GATEWAY_WS || 'ws://localhost:8787';+// A dotenv-style `KEY=value` line. Only usable when the value is unquoted JSON.const fromFile = (p) => {if (!p || !existsSync(p)) return '';- const m = readFileSync(p, 'utf8').match(/^JWKS_KEY=(.*)$/m);- return m ? m[1].trim().replaceAll(/^['"]|['"]$/g, '') : '';+ const m = readFileSync(p, 'utf8').match(/^(?:export\s+)?JWKS_KEY=(.*)$/m);+ const raw = m ? m[1].trim().replaceAll(/^['"]|['"]$/g, '') : '';+ // `init-dev-env.sh write` emits `export KEY=%q`, i.e. SHELL-escaped JSON.+ // Regex-lifting that yields a string JSON.parse cannot read, so reject it+ // here and let the raw-JWKS source below answer instead β a crash inside+ // JSON.parse reads as a broken probe rather than a wrong key source.+ try {+ JSON.parse(raw);+ return raw;+ } catch {+ return '';+ }+};+// The managed agent-testing flow persists the key as raw JSON, not as an env+// line; that file is the only source in this flow that survives a round trip.+const fromJwksFile = (p) => {+ if (!p || !existsSync(p)) return '';+ const raw = readFileSync(p, 'utf8').trim();+ try {+ JSON.parse(raw);+ return raw;+ } catch {+ return '';+ }};+const repoFile = (rel) => new URL(`../../../../${rel}`, import.meta.url).pathname;const jwksRaw =process.env.JWKS_KEY?.trim() ||fromFile(process.env.JWKS_SOURCE) ||- fromFile(new URL('../../../../.records/env/gateway.env', import.meta.url).pathname);+ fromJwksFile(process.env.JWKS_SOURCE) ||+ fromJwksFile(repoFile('.records/env/agent-testing-jwks.json')) ||+ fromFile(repoFile('.records/env/gateway.env'));if (!jwksRaw) {console.error(- 'β no JWKS_KEY found β export JWKS_KEY, or set JWKS_SOURCE=<env file>, or create .records/env/gateway.env',+ 'β no JWKS_KEY found β export JWKS_KEY, or set JWKS_SOURCE=<env file | jwks json>, or run `init-dev-env.sh env` to generate .records/env/agent-testing-jwks.json',);process.exit(1);}diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex b28de426c94..f1f31cd7480 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -6,6 +6,7 @@ import { isFullAccessApiKey } from '@lobechat/const/apiKeyScope';import { parse } from '@lobechat/conversation-flow';import type { ExecAgentResult, TaskCurrentActivity, TaskStatusResult } from '@lobechat/types';import {+ CreateThreadWithMessageSchema,entityIdPattern,LocalHeterogeneousAgentTypeSchema,RequestTrigger,@@ -895,6 +896,13 @@ const ExecAgentSchema = zworkingDirectoryConfig: workingDirConfigSchema.optional(),}).optional(),+ /**+ * Branch this run into a new thread (subtopic) under the resolved topic.+ * The gateway path never calls `aiChat.sendMessageInServer`, so this is+ * the only way the composer's "start a new subtopic" intent reaches the+ * server β without it the turn lands on the topic's main spine.+ */+ newThread: CreateThreadWithMessageSchema.optional(),/*** Group orchestration role of the run, stamped onto the assistant* message's `metadata.orchestrationRole` so the supervisor/member@@ -2066,6 +2074,9 @@ export const aiAgentRouter = router({messageIds: [...existingMessageIds,parentMessageId,+ // A new subtopic branches off an existing message β authorize that+ // anchor too, or a caller could fork a thread off someone else's turn.+ appContext?.newThread?.sourceMessageId,resumeApproval?.parentMessageId,// Every batch target is authorized too β a caller must not be able to// slip a message it doesn't own into the list behind an owned anchor.diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.tsindex 80984b9f014..280ff2cd190 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts@@ -1973,6 +1973,34 @@ describe('AgentRuntimeService', () => {expect(result).toEqual(stubMessages);});+ it('scopes the snapshot to the run thread when the operation is a subtopic run', async () => {+ // Regression: without `threadId` the snapshot is the topic's MAIN+ // conversation, and the client writes it into the thread's bucket at+ // step_start / agent_runtime_end β wiping the turn the run just produced,+ // so a freshly created subtopic renders the main conversation instead.+ const queryMessages = vi.fn().mockResolvedValue([]);+ stubMessageService(service, queryMessages);++ await service.queryUiMessages({+ metadata: { agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' },+ } as any);++ expect(queryMessages).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agt_1', threadId: 'thd_1', topicId: 'tpc_1' }),+ );+ });++ it('leaves threadId unset for a main-conversation run', async () => {+ const queryMessages = vi.fn().mockResolvedValue([]);+ stubMessageService(service, queryMessages);++ await service.queryUiMessages({+ metadata: { agentId: 'agt_1', topicId: 'tpc_1' },+ } as any);++ expect(queryMessages.mock.calls[0][0].threadId).toBeUndefined();+ });+it('returns undefined when agentId or topicId is missing (skips empty-array push)', async () => {const queryMessages = vi.fn();stubMessageService(service, queryMessages);diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex 9f49538b2a8..60cf89fabf7 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -1095,6 +1095,11 @@ export class AgentRuntimeService {// standard branch (`groupId IS NULL`) and returns ZERO group messages, so// the step_start uiMessages snapshot would be empty and clobber the client.const groupId: string | undefined = agentState?.metadata?.groupId;+ // threadId scopes a subtopic run. Without it the snapshot is the topic's+ // MAIN conversation, and the client writes that into the thread's bucket at+ // step_start / agent_runtime_end β wiping the turn the run just produced, so+ // the subtopic panel falls back to showing the main conversation.+ const threadId: string | undefined = agentState?.metadata?.threadId ?? undefined;if (!agentId || !topicId) return undefined;try {@@ -1102,6 +1107,7 @@ export class AgentRuntimeService {agentId,groupId,skipWorks: options?.skipWorks,+ threadId,topicId,});} catch (error) {diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.newThread.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.newThread.test.tsnew file mode 100644index 00000000000..9f5447445cb--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.newThread.test.ts@@ -0,0 +1,275 @@+import { ThreadType } from '@lobechat/types';+import type * as ModelBankModule from 'model-bank';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AiAgentService } from '../index';++// Use vi.hoisted to ensure mock functions are available before vi.mock runs+const { mockMessageCreate, mockSpineMessageId, mockThreadCreate } = vi.hoisted(() => ({+ mockMessageCreate: vi.fn(),+ mockSpineMessageId: vi.fn(),+ mockThreadCreate: vi.fn(),+}));++// Mock trusted client to avoid server-side env access+vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(() => ({+ create: mockMessageCreate,+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),+ getLatestSpineMessageId: mockSpineMessageId,+ query: vi.fn().mockResolvedValue([]),+ update: vi.fn().mockResolvedValue({}),+ })),+}));++// Mock AgentModel+vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(() => ({+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ queryAgents: vi.fn().mockResolvedValue([]),+ })),+}));++// Mock AgentService+vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(() => ({+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ })),+}));++// Mock PluginModel+vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(() => ({+ query: vi.fn().mockResolvedValue([]),+ })),+}));++// Mock TopicModel+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(() => ({+ appendRunningOperationChild: vi.fn().mockResolvedValue(true),+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(undefined),+ updateMetadata: vi.fn().mockResolvedValue(undefined),+ })),+}));++// Mock ThreadModel+vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(() => ({+ create: mockThreadCreate,+ findById: vi.fn(),+ update: vi.fn(),+ })),+}));++// Mock ChatGroupModel β execAgent resolves the operation's group context when+// appContext.groupId is set (SubAgent task scenario). An empty roster makes+// buildGroupAgentContext return undefined, so the run proceeds without a group.+vi.mock('@/database/models/chatGroup', () => ({+ ChatGroupModel: vi.fn().mockImplementation(() => ({+ findById: vi.fn().mockResolvedValue(undefined),+ getGroupAgentsWithMeta: vi.fn().mockResolvedValue([]),+ })),+}));++// Mock AgentRuntimeService+vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(() => ({+ createOperation: vi.fn().mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ }),+ })),+}));++// Mock MarketService (for getLobehubSkillManifests)+vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(() => ({+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ })),+}));++// Mock ComposioService (for getComposioManifests)+vi.mock('@/server/services/composio', () => ({+ ComposioService: vi.fn().mockImplementation(() => ({+ getComposioManifests: vi.fn().mockResolvedValue([]),+ })),+}));++// Mock FileService+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(() => ({+ uploadFromUrl: vi.fn(),+ })),+}));++// Mock Mecha modules+vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),+}));++// Mock deviceGateway+vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ isConfigured: false,+ queryDeviceList: vi.fn().mockResolvedValue([]),+ },+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++// Mock model-bank+vi.mock('model-bank', async (importOriginal) => {+ const actual = await importOriginal<typeof ModelBankModule>();+ return {+ ...actual,+ LOBE_DEFAULT_MODEL_LIST: [+ {+ abilities: { functionCall: true, video: false, vision: true },+ id: 'gpt-4',+ providerId: 'openai',+ },+ ],+ };+});++describe('AiAgentService.execAgent - appContext.newThread', () => {+ let service: AiAgentService;+ const mockDb = {} as any;+ const userId = 'test-user-id';++ const newThread = { sourceMessageId: 'msg-source', type: ThreadType.Continuation } as const;++ const messageCall = (role: 'user' | 'assistant') =>+ mockMessageCreate.mock.calls.find((call) => call[0].role === role);++ beforeEach(() => {+ vi.clearAllMocks();+ mockMessageCreate.mockClear();+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });+ mockSpineMessageId.mockReset().mockResolvedValue(undefined);+ mockThreadCreate.mockReset().mockResolvedValue({ id: 'thread-new' });++ service = new AiAgentService(mockDb, userId);+ });++ afterEach(() => {+ mockMessageCreate.mockClear();+ });++ it('creates the thread and persists the whole turn inside it', async () => {+ // Regression: the gateway send path skips `aiChat.sendMessageInServer`, so+ // `newThread` is the only carrier for the composer's "start a new subtopic"+ // intent. Dropping it persisted the turn onto the topic's main spine β the+ // subtopic collapsed back into the main chat and never reached the sidebar.+ const result = await service.execAgent({+ agentId: 'agent-1',+ appContext: { newThread, topicId: 'topic-1' },+ prompt: 'Test prompt',+ });++ expect(mockThreadCreate).toHaveBeenCalledWith({+ parentThreadId: undefined,+ sourceMessageId: 'msg-source',+ title: undefined,+ topicId: 'topic-1',+ type: ThreadType.Continuation,+ });+ expect(result.createdThreadId).toBe('thread-new');+ expect(messageCall('user')![0]).toMatchObject({ threadId: 'thread-new', topicId: 'topic-1' });+ expect(messageCall('assistant')![0]).toMatchObject({+ threadId: 'thread-new',+ topicId: 'topic-1',+ });+ });++ it('anchors the first turn on the branch point instead of the topic spine', async () => {+ // The new thread is empty, so the spine lookup would return the TOPIC's head+ // (or nothing) and fork the turn off the wrong node.+ mockSpineMessageId.mockResolvedValue('msg-topic-head');++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { newThread, topicId: 'topic-1' },+ prompt: 'Test prompt',+ });++ expect(messageCall('user')![0].parentId).toBe('msg-source');+ });++ it('ignores newThread when the run already targets an existing thread', async () => {+ const result = await service.execAgent({+ agentId: 'agent-1',+ appContext: { newThread, threadId: 'thread-existing', topicId: 'topic-1' },+ prompt: 'Test prompt',+ });++ expect(mockThreadCreate).not.toHaveBeenCalled();+ expect(result.createdThreadId).toBeUndefined();+ expect(messageCall('user')![0]).toMatchObject({ threadId: 'thread-existing' });+ });++ it('rejects a subtopic with no parent topic rather than silently dropping it', async () => {+ await expect(+ service.execAgent({+ agentId: 'agent-1',+ appContext: { newThread },+ prompt: 'Test prompt',+ }),+ ).rejects.toThrow('appContext.newThread requires an existing appContext.topicId');++ expect(mockThreadCreate).not.toHaveBeenCalled();+ expect(mockMessageCreate).not.toHaveBeenCalled();+ });++ it('fails loudly when the thread row could not be created', async () => {+ // `ThreadModel.create` swallows insert conflicts and returns undefined.+ // Falling through would persist the turn to the main spine β the exact bug.+ mockThreadCreate.mockResolvedValue(undefined);++ await expect(+ service.execAgent({+ agentId: 'agent-1',+ appContext: { newThread, topicId: 'topic-1' },+ prompt: 'Test prompt',+ }),+ ).rejects.toThrow('Failed to create thread on topic topic-1');++ expect(mockMessageCreate).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex f3f7e4af628..333a1376540 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -420,6 +420,13 @@ interface InternalExecAgentParams extends ExecAgentParams {* set by the callSubAgent thread-run path, never client-passable.*/chatConfigOverride?: Partial<LobeAgentChatConfig> | null;+ /**+ * Thread `execAgent` materialised from `appContext.newThread` for THIS turn.+ * Internal-only: set by the wrapper after it creates the row, never+ * client-passable. Tells the turn its thread is brand new, so the first+ * message anchors on the branch point instead of a (non-existent) spine head.+ */+ createdThreadId?: string;/** Cron job ID that triggered this execution (if trigger is 'cron') */cronJobId?: string;/** Disable only local-system while preserving other tools. Useful for signal-only evals. */@@ -1371,7 +1378,17 @@ export class AiAgentService {* β ServerMechaModule.ContextEngineering(input, config, messages)* β AgentRuntimeService.createOperation(...)*/- async execAgent(params: InternalExecAgentParams): Promise<ExecAgentResult> {+ async execAgent(inputParams: InternalExecAgentParams): Promise<ExecAgentResult> {+ // Creating the thread here (rather than inside the turn) means a run that+ // asked for one is already a thread run by the time the reservation check+ // below reads `appContext.threadId` β same isolation as a follow-up inside+ // an existing thread.+ const { createdThreadId, params } = await this.resolveNewThread(inputParams);+ // The client needs the id back to pivot its optimistic `_new` thread bucket+ // and refresh the sidebar; every return path below must carry it.+ const withCreatedThread = (result: ExecAgentResult): ExecAgentResult =>+ createdThreadId ? { ...result, createdThreadId } : result;+const topicId = params.appContext?.topicId;const interventionReservationId = params.approvalResolutionRequestId? deriveAgentInterventionContinuationOperationId({@@ -1400,7 +1417,7 @@ export class AiAgentService {// operation owns `runningOperation` (for example callAgent/callSubAgent),// so making them wait for the topic-start claim deadlocks the child start.if (!topicId || (params.appContext?.threadId && !isInterventionThreadStart)) {- return this.execAgentWithApprovalRollback(params);+ return withCreatedThread(await this.execAgentWithApprovalRollback(params));}const reserved = await acquireTopicStartReservation({@@ -1420,7 +1437,7 @@ export class AiAgentService {}try {- return await this.execAgentWithApprovalRollback(params);+ return withCreatedThread(await this.execAgentWithApprovalRollback(params));} finally {await this.topicModel.releaseTaskCallbackReservation(topicId, reservationId);}@@ -1458,6 +1475,65 @@ export class AiAgentService {}}+ /**+ * Materialise an `appContext.newThread` intent into a real thread row.+ *+ * The composer stages a subtopic client-side and the non-gateway send path+ * creates it inside `sendMessageInServer` (`newThread`). The gateway path+ * never makes that call, so the intent arrives here instead β without this+ * the turn would persist onto the topic's main spine, no thread row would+ * exist, and the subtopic would silently collapse back into the main+ * conversation.+ *+ * Returns the params to run with: `appContext.threadId` rebound to the new+ * thread so every downstream read (message writes, history queries, operation+ * context) lands inside it. A no-op for every caller that doesn't ask for one.+ */+ private async resolveNewThread(params: InternalExecAgentParams): Promise<{+ createdThreadId?: string;+ params: InternalExecAgentParams;+ }> {+ const { appContext } = params;+ const newThread = appContext?.newThread;++ // `threadId` wins: that is a follow-up inside a thread that already exists,+ // and creating a second row would orphan the earlier turns.+ if (!newThread || appContext?.threadId) return { params };++ // A subtopic branches off a persisted message, so its topic always exists by+ // the time the send reaches here. Refusing is better than silently creating+ // a thread on a topic this run is about to mint under a different id.+ if (!appContext?.topicId) {+ throw new Error('appContext.newThread requires an existing appContext.topicId');+ }++ const thread = await this.threadModel.create({+ parentThreadId: newThread.parentThreadId,+ sourceMessageId: newThread.sourceMessageId,+ title: newThread.title,+ topicId: appContext.topicId,+ type: newThread.type,+ });++ // `ThreadModel.create` swallows insert conflicts and returns undefined.+ // Falling through would persist the turn to the main spine β exactly the+ // failure this path exists to prevent β so fail loudly instead.+ if (!thread) {+ throw new Error(`Failed to create thread on topic ${appContext.topicId}`);+ }++ log('execAgent: created thread %s on topic %s', thread.id, appContext.topicId);++ return {+ createdThreadId: thread.id,+ params: {+ ...params,+ appContext: { ...appContext, threadId: thread.id },+ createdThreadId: thread.id,+ },+ };+ }+private async execAgentWithReservation(params: InternalExecAgentParams,approvalClaim: {@@ -1475,6 +1551,7 @@ export class AiAgentService {appContext,autoStart = true,botContext,+ createdThreadId,clientIp,userAgent,deviceId: requestedDeviceId,@@ -2543,6 +2620,12 @@ export class AiAgentService {const resolveUserMessageParentId = async () => {if (runFromHistory) return undefined;if (parentMessageId) return parentMessageId;+ // A thread created for THIS turn is empty, so there is no spine head to+ // anchor on. Its branch point is the source message β the same anchor the+ // non-gateway path keeps for a brand-new thread. Without it the first turn+ // persists as a second root and the renderer's parentId walk emits it out+ // of order.+ if (createdThreadId) return appContext?.newThread?.sourceMessageId;const threadId = appContext?.threadId ?? null;const spineId = await this.messageModel.getLatestSpineMessageId({ threadId, topicId });diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 4bdd8bb4c97..bb2102a1e0b 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1632,7 +1632,8 @@"textSelection.added": "Added to conversation context","textSelection.title": "Message selection","thread.closeSubagentThread": "Hide Detail",- "thread.divider": "Subtopic",+ "thread.dividerContinuation": "Forked here, inheriting the main chat context so far",+ "thread.dividerStandalone": "Forked here, inheriting only the message above","thread.openSubagentThread": "View Detail","thread.subagentMetrics.modelLabel": "Model","thread.subagentMetrics.tokens": "{{count}} tokens",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 9f0b64222f4..c66fdf8b342 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1632,7 +1632,8 @@"textSelection.added": "ε·²ζ·»ε ε°ε―Ήθ―δΈδΈζ","textSelection.title": "ζΆζ―ιεΊ","thread.closeSubagentThread": "ιθθ―¦ζ ",- "thread.divider": "εθ―ι’",+ "thread.dividerContinuation": "δ»ζ€ζΆζ―εεοΌε·²η»§ζΏθ³ζ€ηδΈ»ε―Ήθ―δΈδΈζ",+ "thread.dividerStandalone": "δ»ζ€ζΆζ―εεοΌδ» η»§ζΏδΈζΉθΏζ‘ζΆζ―","thread.openSubagentThread": "ζ₯ηθ―¦ζ ","thread.subagentMetrics.modelLabel": "樑ε","thread.subagentMetrics.tokens": "{{count}} tokens",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 0c342301ab0..030c444c2ab 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1883,7 +1883,8 @@ export default {'taskList.view.list': 'List','taskList.viewAll': 'View all','thread.closeSubagentThread': 'Hide Detail',- 'thread.divider': 'Subtopic',+ 'thread.dividerContinuation': 'Forked here, inheriting the main chat context so far',+ 'thread.dividerStandalone': 'Forked here, inheriting only the message above','thread.openSubagentThread': 'View Detail','thread.subagentMetrics.modelLabel': 'Model','thread.subagentMetrics.toolCalls_one': '{{count}} tool call',diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 1274b7d18a8..1b00d617ab4 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -1,4 +1,5 @@import type { LobeAgentChatConfig } from '../agent/chatConfig';+import type { CreateThreadWithMessageParams } from '../aiChat';import type { WorkingDirConfig } from '../device';import type { TaskDetail, UIChatMessage } from '../message';import type { ChatTopic } from '../topic';@@ -123,6 +124,19 @@ export interface ExecAgentAppContext {* recursive sub-agent dispatch.*/isSubAgent?: boolean;+ /**+ * Branch this run into a NEW thread (subtopic) under `topicId`, persisting the+ * turn there instead of on the topic's main spine.+ *+ * Same intent the non-gateway send path expresses as `newThread` on+ * `aiChat.sendMessageInServer`. The gateway path skips that call entirely, so+ * without carrying it here the subtopic silently collapses back into the main+ * conversation and no thread row is ever created.+ *+ * Ignored when `threadId` is already set β that is a follow-up inside an+ * existing thread, which needs no new row.+ */+ newThread?: CreateThreadWithMessageParams;/*** Orchestration role of the agent for this group run. `'supervisor'` for the* group's coordinating agent (execGroupAgent), `'member'` for delegated members@@ -295,6 +309,8 @@ export interface ExecAgentResult {autoStarted: boolean;/** Timestamp when operation was created */createdAt: string;+ /** The thread created for this run when `appContext.newThread` was supplied. */+ createdThreadId?: string;/** Error message if operation failed to start */error?: string;/** Status message */diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsxindex 5a5dc598f54..1fcf3c3cdea 100644--- a/src/features/Conversation/ChatList/index.tsx+++ b/src/features/Conversation/ChatList/index.tsx@@ -1,5 +1,6 @@'use client';+import type { UIChatMessage } from '@lobechat/types';import { Flexbox } from '@lobehub/ui';import type { ReactNode } from 'react';import { memo, useCallback, useMemo } from 'react';@@ -54,6 +55,13 @@ export interface ChatListProps {* Disable the actions bar for all messages (e.g., in share page)*/disableActionsBar?: boolean;+ /**+ * Optional visibility filter applied to the rendered list only. Data flows+ * (fetch cache, AI context assembly, message counts) are untouched β used+ * e.g. by the thread portal to collapse inherited main-chat history down to+ * the fork message.+ */+ filterItem?: (message: UIChatMessage) => boolean;/*** Optional content rendered as the last item inside the virtualized list β* scrolls with the messages instead of being pinned to the viewport bottom.@@ -87,6 +95,7 @@ const ChatList = memo<ChatListProps>(({defaultWorkflowExpandLevel,disableActionsBar,+ filterItem,footerSlot,headerSlot,welcome,@@ -126,8 +135,12 @@ const ChatList = memo<ChatListProps>(isValidating: messagesSWR.isValidating,mutate: messagesSWR.mutate,});- const displayMessages = useConversationStore(dataSelectors.displayMessages);- const displayMessageIds = useConversationStore(dataSelectors.displayMessageIds);+ const allDisplayMessages = useConversationStore(dataSelectors.displayMessages);+ const displayMessages = useMemo(+ () => (filterItem ? allDisplayMessages.filter(filterItem) : allDisplayMessages),+ [allDisplayMessages, filterItem],+ );+ const displayMessageIds = useMemo(() => displayMessages.map((m) => m.id), [displayMessages]);const overlayHeight = useConversationStore(inputSelectors.chatInputOverlayHeight);const latestMessageId = displayMessageIds.at(-1);diff --git a/src/features/Portal/Thread/Chat/ThreadDivider/index.tsx b/src/features/Portal/Thread/Chat/ThreadDivider/index.tsxindex adbbb5221f3..60cc4267ba0 100644--- a/src/features/Portal/Thread/Chat/ThreadDivider/index.tsx+++ b/src/features/Portal/Thread/Chat/ThreadDivider/index.tsx@@ -1,17 +1,38 @@-import { Icon } from '@lobehub/ui';-import { Tag } from '@lobehub/ui/base-ui';+import { type IThreadType, ThreadType } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';import { Divider } from 'antd';+import { cssVar } from 'antd-style';import { GitBranch } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-const ThreadDivider = memo(() => {+interface ThreadDividerProps {+ threadType?: IThreadType;+}++/**+ * Sits under the fork message β the only main-chat message rendered in the+ * thread portal β and states what context the thread carries: a standalone+ * thread inherits just that message, everything else continues with the main+ * chat history up to it.+ */+const ThreadDivider = memo<ThreadDividerProps>(({ threadType }) => {const { t } = useTranslation('chat');return (<div style={{ padding: '0 20px' }}><Divider style={{ margin: 0, padding: '20px 0' }}>- <Tag icon={<Icon icon={GitBranch} />}>{t('thread.divider')}</Tag>+ <Flexbox+ horizontal+ align={'center'}+ gap={6}+ style={{ color: cssVar.colorTextDescription, fontSize: 12 }}+ >+ <Icon icon={GitBranch} size={12} />+ {threadType === ThreadType.Standalone+ ? t('thread.dividerStandalone')+ : t('thread.dividerContinuation')}+ </Flexbox></Divider></div>);diff --git a/src/features/Portal/Thread/Chat/index.tsx b/src/features/Portal/Thread/Chat/index.tsxindex b91e48dc299..38f8bd32f82 100644--- a/src/features/Portal/Thread/Chat/index.tsx+++ b/src/features/Portal/Thread/Chat/index.tsx@@ -1,5 +1,6 @@'use client';+import { type IThreadType, type UIChatMessage } from '@lobechat/types';import { Flexbox } from '@lobehub/ui';import { memo, Suspense, useCallback, useMemo } from 'react';@@ -35,48 +36,67 @@ import { useThreadActionsBarConfig } from './useThreadActionsBarConfig';*/interface ThreadChatContentProps {composerWritable: boolean;+ /** The message this thread forked from β its anchor in the main conversation. */+ forkMessageId?: string;isHeterogeneousAgent: boolean;readOnly: boolean;+ threadType?: IThreadType;}const ThreadChatContent = memo<ThreadChatContentProps>(- ({ composerWritable, isHeterogeneousAgent, readOnly }) => {+ ({ composerWritable, forkMessageId, isHeterogeneousAgent, readOnly, threadType }) => {const inputMode = getThreadInputMode({isExternallyOwnedThread: readOnly,isHeterogeneousAgent,});const displayMessages = useConversationStore(conversationSelectors.displayMessages);- const threadSourceInfo = useMemo(() => {- let sourceMessageIndex = -1;- let sourceMessageId: string | undefined;+ // The portal knows its own fork point (`threadStartMessageId` while the+ // thread is being created, `thread.sourceMessageId` once it exists), so take+ // it from there rather than deriving it from the list. Deriving it as "the+ // last message without a threadId" breaks for the ~2s optimistic window+ // after send: the just-sent rows have no threadId yet either (the thread row+ // does not exist), so the scan walked past the fork point onto the assistant+ // placeholder. Kept as a fallback for callers that have neither.+ const sourceMessageId = useMemo(+ () => forkMessageId ?? displayMessages.findLast((msg) => !msg.threadId)?.id,+ [forkMessageId, displayMessages],+ );- for (const [i, msg] of displayMessages.entries()) {- if (!msg.threadId) {- sourceMessageIndex = i;- sourceMessageId = msg.id;- }- }+ // Render the fork message and everything after it β the inherited main chat+ // above it is one click away and re-rendering it here just duplicates it.+ // The data layer keeps the full history, so AI context inheritance is+ // unchanged. Cutting by position (rather than by `threadId`) is what keeps+ // the user's own message visible during the optimistic window.+ const visibleIds = useMemo(() => {+ if (!sourceMessageId) return;+ const forkIndex = displayMessages.findIndex((msg) => msg.id === sourceMessageId);+ // Anchor not in this list (a bucket swap mid-flight): show everything+ // rather than blanking the panel.+ if (forkIndex < 0) return;+ return new Set(displayMessages.slice(forkIndex).map((msg) => msg.id));+ }, [displayMessages, sourceMessageId]);- return { sourceMessageId, sourceMessageIndex };- }, [displayMessages]);+ const filterItem = useCallback(+ (msg: UIChatMessage) => !visibleIds || visibleIds.has(msg.id),+ [visibleIds],+ );const itemContent = useCallback((index: number, id: string) => {- const enableThreadDivider = threadSourceInfo.sourceMessageId === id;- const isParentMessage = index <= threadSourceInfo.sourceMessageIndex;+ const isSourceMessage = id === sourceMessageId;return (<MessageIteminPortalThread- disableEditing={readOnly || isParentMessage}- endRender={enableThreadDivider ? <ThreadDivider /> : undefined}+ disableEditing={readOnly || isSourceMessage}+ endRender={isSourceMessage ? <ThreadDivider threadType={threadType} /> : undefined}id={id}index={index}/>);},- [threadSourceInfo.sourceMessageId, threadSourceInfo.sourceMessageIndex, readOnly],+ [sourceMessageId, readOnly, threadType],);return (@@ -93,7 +113,7 @@ const ThreadChatContent = memo<ThreadChatContentProps>(style={{ overflowX: 'hidden', overflowY: 'auto', position: 'relative' }}width={'100%'}>- <ChatList itemContent={itemContent} />+ <ChatList filterItem={filterItem} itemContent={itemContent} /></Flexbox></Suspense>{composerWritable && inputMode === 'heterogeneous' && <HeterogeneousChatInput />}@@ -101,6 +121,11 @@ const ThreadChatContent = memo<ThreadChatContentProps>(<ChatInputleftActions={['typo', 'voiceDictation']}rightActions={['voiceMessage', 'contextWindow']}+ // A subtopic runs on the conversation it forked from: mode, device,+ // working directory and approval all come from there and are not+ // separately settable here. Rendering the bar anyway put a row of+ // controls under the panel that only restated the parent's state.+ showControlBar={false}/>)}</>@@ -262,8 +287,10 @@ const ThreadChat = memo(() => {><ThreadChatContentcomposerWritable={composerTarget.writable}+ forkMessageId={threadStartMessageId ?? portalThread?.sourceMessageId ?? undefined}isHeterogeneousAgent={isHeterogeneousAgent}readOnly={!composerTarget.writable}+ threadType={isCreatingNewThread ? newThreadMode : portalThread?.type}/></ConversationProvider>);diff --git a/src/store/chat/slices/agentRun/actions/dispatch/newThreadIntent.test.ts b/src/store/chat/slices/agentRun/actions/dispatch/newThreadIntent.test.tsnew file mode 100644index 00000000000..a2513b2c969--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/dispatch/newThreadIntent.test.ts@@ -0,0 +1,53 @@+import { ThreadType } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { resolveNewThreadIntent } from './newThreadIntent';++describe('resolveNewThreadIntent', () => {+ const stagedSubtopic = {+ agentId: 'agt_1',+ isNew: true,+ scope: 'thread' as const,+ sourceMessageId: 'msg_1',+ threadType: ThreadType.Continuation,+ topicId: 'tpc_1',+ };++ it('reads the intent off a staged subtopic context', () => {+ expect(resolveNewThreadIntent(stagedSubtopic)).toEqual({+ sourceMessageId: 'msg_1',+ type: ThreadType.Continuation,+ });+ });++ it('returns nothing for a follow-up inside an existing thread', () => {+ // Re-creating the thread here would orphan every turn already inside it.+ expect(+ resolveNewThreadIntent({+ agentId: 'agt_1',+ scope: 'thread',+ threadId: 'thd_1',+ topicId: 'tpc_1',+ }),+ ).toBeUndefined();+ });++ it('returns nothing for a plain main-conversation send', () => {+ expect(resolveNewThreadIntent({ agentId: 'agt_1', topicId: 'tpc_1' })).toBeUndefined();+ });++ it.each([['sourceMessageId'], ['threadType']])(+ 'returns nothing when a staged subtopic is missing %s',+ (field) => {+ expect(resolveNewThreadIntent({ ...stagedSubtopic, [field]: undefined })).toBeUndefined();+ },+ );++ it('ignores a new-TOPIC send that is not scoped to a thread', () => {+ // `isNew` alone means "creating a topic"; only `scope: 'thread'` stages a+ // subtopic. Branching on `isNew` would fork every first message into a thread.+ expect(+ resolveNewThreadIntent({ agentId: 'agt_1', isNew: true, sourceMessageId: 'msg_1' }),+ ).toBeUndefined();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/dispatch/newThreadIntent.ts b/src/store/chat/slices/agentRun/actions/dispatch/newThreadIntent.tsnew file mode 100644index 00000000000..8af4f123818--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/dispatch/newThreadIntent.ts@@ -0,0 +1,32 @@+import type {+ ChatThreadType,+ ConversationContext,+ CreateThreadWithMessageParams,+} from '@lobechat/types';++/**+ * Read a "start a new subtopic" intent off a conversation context.+ *+ * The composer stages a subtopic entirely client-side β `scope: 'thread'` plus+ * `isNew`, with no thread row yet β and the server materialises it as part of+ * the send. Both transports need the same intent (`sendMessageInServer.newThread`+ * for the client runtime, `execAgentTask.appContext.newThread` for the gateway),+ * so they read it from here rather than each deriving it: when only one of them+ * did, gateway sends silently persisted the turn onto the topic's main spine and+ * the subtopic collapsed back into the main conversation.+ *+ * Returns undefined for every other context, including a follow-up inside a+ * thread that already exists (`threadId` set, `isNew` false).+ */+export const resolveNewThreadIntent = (+ context: ConversationContext,+): CreateThreadWithMessageParams | undefined => {+ const { isNew, scope, sourceMessageId, threadType } = context;++ // `sourceMessageId` is the branch point and `threadType` decides whether the+ // parent context carries over β a staged thread missing either is not+ // actionable, so treat it as a plain send rather than guessing.+ if (!isNew || scope !== 'thread' || !sourceMessageId || !threadType) return undefined;++ return { sourceMessageId, type: threadType as ChatThreadType };+};diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 2fe3ead2ee0..1de47360463 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -8,7 +8,6 @@ import { chainCompressContext } from '@lobechat/prompts';import type {ChatAudioItem,ChatImageItem,- ChatThreadType,ChatTopicMetadata,ChatVideoItem,ConversationContext,@@ -62,6 +61,7 @@ import {} from '@/store/chat/selectors';import { selectRuntimeType } from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';import { executeDirectMention } from '@/store/chat/slices/agentRun/actions/dispatch/directMentionExecutor';+import { resolveNewThreadIntent } from '@/store/chat/slices/agentRun/actions/dispatch/newThreadIntent';import { buildRunLifecycle } from '@/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle';import type { RunScope } from '@/store/chat/slices/agentRun/actions/lifecycle/types';import {@@ -273,6 +273,38 @@ export class ConversationLifecycleActionImpl {};};+ /**+ * Land a thread the server created for this send: record it on the operation,+ * pivot the portal from the staged `isNew` thread to the persisted one, and+ * refresh the sidebar's nested list. Shared by both send transports β the+ * gateway path creates the thread through `execAgentTask.appContext.newThread`+ * and the client path through `sendMessageInServer.newThread`, but everything+ * downstream of "the row now exists" is identical.+ */+ #syncCreatedThread = (+ operationId: string,+ createdThreadId: string,+ sourceMessageId?: string,+ ): void => {+ this.#get().updateOperationMetadata(operationId, { createdThreadId });++ // When the active portal view is already the Thread surface (the+ // main-page "create subtopic" flow staged it before sending), pivot it+ // from `isNew` β persisted thread id. Otherwise the thread was started+ // by a panel-hosted ConversationProvider (e.g. FloatingChatPanel inside+ // the Document portal) and we must NOT push a Thread view β doing so+ // would cover the host view the user is still reading.+ const currentPortalViewType = chatPortalSelectors.currentViewType(this.#get());+ if (currentPortalViewType === PortalViewType.Thread) {+ this.#get().openThreadInPortal(createdThreadId, sourceMessageId);+ } else {+ this.#get().syncThreadInPortal(createdThreadId, sourceMessageId);+ }++ // Refresh threads list to update the sidebar+ void Promise.resolve(this.#get().refreshThreads()).catch(console.error);+ };+sendMessage = async ({message,editorData: inputEditorData,@@ -346,15 +378,9 @@ export class ConversationLifecycleActionImpl {// Use context from params (required)// If creating new thread (isNew + scope='thread'), threadId will be created by serverconst isCreatingNewThread = context.isNew && context.scope === 'thread';- // Build newThread params for server from new context format- // Only create newThread if we have both sourceMessageId and threadType- const newThread =- isCreatingNewThread && context.sourceMessageId && context.threadType- ? {- sourceMessageId: context.sourceMessageId,- type: context.threadType as ChatThreadType,- }- : undefined;+ // Shared with the gateway transport so both send paths materialise a staged+ // subtopic the same way.+ const newThread = resolveNewThreadIntent(context);if (!ownerAgentId) {onPreflightFailure?.();@@ -1680,6 +1706,11 @@ export class ConversationLifecycleActionImpl {});const cancelledAfterPersistence = abortController.signal.aborted;+ // Record created threadId in operation metadata+ if (result.createdThreadId) {+ this.#syncCreatedThread(operationId, result.createdThreadId, context.sourceMessageId);+ }+// Topic title: gateway-created topics had no LLM-summarized// title. executeGatewayAgent has already replaced messages + switched to// the new topic, so the shared hook reads the persisted conversation from@@ -1696,7 +1727,17 @@ export class ConversationLifecycleActionImpl {void sendRunLifecycle.afterUserMessagePersisted({assistantMessageId: result.assistantMessageId,- context: { ...operationContext, topicId: result.topicId },+ context: {+ ...operationContext,+ // The turn was persisted inside the thread the server just+ // created, so the lifecycle must read that bucket β not the+ // topic's main spine β when it loads the conversation.+ ...(result.createdThreadId && {+ isNew: false,+ threadId: result.createdThreadId,+ }),+ topicId: result.topicId,+ },isCreateNewTopic: willCreateNewTopic,operationId,runId: operationId,@@ -1714,6 +1755,7 @@ export class ConversationLifecycleActionImpl {return {assistantMessageId: result.assistantMessageId,+ createdThreadId: result.createdThreadId,userMessageId: result.userMessageId,};} catch (e) {@@ -1892,23 +1934,7 @@ export class ConversationLifecycleActionImpl {// Record created threadId in operation metadataif (data.createdThreadId) {- this.#get().updateOperationMetadata(operationId, { createdThreadId: data.createdThreadId });-- // When the active portal view is already the Thread surface (the- // main-page "create subtopic" flow staged it before sending), pivot it- // from `isNew` β persisted thread id. Otherwise the thread was started- // by a panel-hosted ConversationProvider (e.g. FloatingChatPanel inside- // the Document portal) and we must NOT push a Thread view β doing so- // would cover the host view the user is still reading.- const currentPortalViewType = chatPortalSelectors.currentViewType(this.#get());- if (currentPortalViewType === PortalViewType.Thread) {- this.#get().openThreadInPortal(data.createdThreadId, context.sourceMessageId);- } else {- this.#get().syncThreadInPortal(data.createdThreadId, context.sourceMessageId);- }-- // Refresh threads list to update the sidebar- this.#get().refreshThreads();+ this.#syncCreatedThread(operationId, data.createdThreadId, context.sourceMessageId);}// Create final context with updated topicId/threadId from server responsediff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex ccd9f516f39..07dad443c1f 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -42,6 +42,7 @@ import {} from '@/store/user/selectors';import { isTrpcErrorCode } from '@/utils/trpcError';+import { resolveNewThreadIntent } from '../../dispatch/newThreadIntent';import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';import type { RunScope } from '../../lifecycle/types';import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEventHandler';@@ -531,6 +532,11 @@ export class GatewayActionImpl {// adopted it up front so the streamed messages land in the on-screen// bucket) while the topic still has no server row.const isCreateNewTopic = !executionContext.topicId;+ // "Start a new subtopic": the composer stages the thread client-side and the+ // server materialises it as part of this run. Without forwarding the intent+ // the turn persists onto the topic's main spine and the subtopic collapses+ // back into the main chat.+ const newThread = resolveNewThreadIntent(executionContext);const taskId =executionContext.viewedTask?.type === 'detail'? executionContext.viewedTask.taskId@@ -623,6 +629,7 @@ export class GatewayActionImpl {}),groupId: executionContext.groupId,...(initialTopicMetadata && { initialTopicMetadata }),+ ...(newThread && { newThread }),// Forward the group orchestration role so the server can stamp it onto// the assistant message metadata. Without this the gateway-created// supervisor turn loses its role on the step_start snapshot / refetch@@ -676,10 +683,44 @@ export class GatewayActionImpl {// Keep execution identity separate from the conversation bucket that owns// the streamed messages. They differ for callAgent/sub-agent runs.- const resolvedExecutionContext = { ...executionContext, topicId: result.topicId };- const resolvedMessageContext = { ...messageContext, topicId: result.topicId };+ // Pivot the optimistic `thread_..._new` bucket onto the persisted thread the+ // server just created: with `threadId` set, `messageMapKey` ignores `isNew`+ // and both contexts resolve to the real thread key.+ const resolveThread = <T extends ConversationContext>(context: T): T =>+ result.createdThreadId+ ? { ...context, isNew: false, threadId: result.createdThreadId }+ : context;+ const resolvedExecutionContext = resolveThread({+ ...executionContext,+ topicId: result.topicId,+ });+ const resolvedMessageContext = resolveThread({ ...messageContext, topicId: result.topicId });this.#get().moveVoiceMessages(messageContext, resolvedMessageContext);+ if (result.createdThreadId) {+ // Attachments picked in the subtopic composer were staged under the+ // `_new` key; carry them over so the next turn in the thread still sees+ // them (mirrors the new-topic handoff below).+ getFileStoreState().moveChatContextSelections(+ messageMapKey(messageContext),+ messageMapKey(resolvedMessageContext),+ );++ // Seed the persisted-thread bucket from the server, exactly as the+ // new-topic branch below does. The Thread portal pivots to this key the+ // moment `portalThreadId` is set, and its own fetch resolves against a+ // thread that did not exist yet β so without this the panel renders the+ // parent context alone and the turn the user just sent is invisible until+ // something else revalidates. `execAgentTask` has already persisted both+ // rows by the time it returns, so this read is authoritative.+ try {+ const messages = await messageService.getMessages(resolvedMessageContext);+ this.#get().replaceMessages(messages, { context: resolvedMessageContext });+ } catch {+ /* non-critical */+ }+ }+if (!isCreateNewTopic && cancelledAfterPersistence) {try {const messages = await messageService.getMessages(resolvedMessageContext);