🤯 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
🔥 refactor: remove the Better Coding Experience lab and make its features default (#23725)
Bryan4fb987307031
diff --git a/apps/cli/src/commands/hetero/dispatchedModes.ts b/apps/cli/src/commands/hetero/dispatchedModes.tsindex edef2928138..25cfa90b55c 100644--- a/apps/cli/src/commands/hetero/dispatchedModes.ts+++ b/apps/cli/src/commands/hetero/dispatchedModes.ts@@ -5,7 +5,7 @@ import type { ResolvedPrompt } from './prompt';type SpawnOptions = Parameters<typeof spawnAgent>[0];/**- * The Better Coding Experience modes the dispatch envelope carried, as spawn+ * The run modes the dispatch envelope carried, as spawn* options for the agent they belong to: Claude Code's permission mode, and the* Codex Plan switch (collaboration mode).*/diff --git a/apps/cli/src/commands/hetero/index.ts b/apps/cli/src/commands/hetero/index.tsindex 122d71230ba..f471c28ee86 100644--- a/apps/cli/src/commands/hetero/index.ts+++ b/apps/cli/src/commands/hetero/index.ts@@ -1076,7 +1076,7 @@ const exec = async (options: ExecOptions): Promise<void> => {// input (live steer / background tasks).liveInput: options.type === 'claude-code' || options.type === 'antigravity',operationId,- // Better Coding Experience: Claude Code permission mode, Codex Plan switch.+ // Claude Code permission mode, Codex Plan switch....dispatchedModeSpawnOptions(options.type, resolved),uploadImage,};diff --git a/apps/cli/src/commands/hetero/prompt.ts b/apps/cli/src/commands/hetero/prompt.tsindex 3298ec0387b..1075e7d95a8 100644--- a/apps/cli/src/commands/hetero/prompt.ts+++ b/apps/cli/src/commands/hetero/prompt.ts@@ -104,14 +104,14 @@ const coerceJsonPrompt = (export interface ResolvedPrompt {/**- * Codex Plan switch (Better Coding Experience lab): the collaboration mode+ * Codex Plan switch: the collaboration mode* a native Codex run sends on every turn.*/collaborationMode?: CodexCollaborationMode;/** Human-readable description for the empty-input check. */describe: () => string;/**- * Claude Code permission mode (Better Coding Experience lab) carried by the+ * Claude Code permission mode carried by the* dispatch envelope. An older `lh` ignores it and keeps allowing everything.*/permissionMode?: HeteroPermissionMode;diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.liveInput.test.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.liveInput.test.tsindex af4dc47696d..c8574fbf6a5 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.liveInput.test.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.liveInput.test.ts@@ -32,8 +32,7 @@ vi.mock('@/utils/logger', () => ({const line = (message: Record<string, unknown>) => `${JSON.stringify(message)}\n`;/**- * A local Claude Code CLI run in Queue mode, or with the Better Coding- * Experience lab off: nothing is steered into it. Its stdin must still+ * A local Claude Code CLI run in Queue mode: nothing is steered into it. Its stdin must still* stay open, as under `lh hetero exec`.*/const startQueueModeRun = async () => {diff --git a/apps/desktop/src/main/controllers/heterogeneousAgentPermission.ts b/apps/desktop/src/main/controllers/heterogeneousAgentPermission.tsindex 4dc4c1ec3e1..eed7062fa68 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentPermission.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentPermission.ts@@ -18,7 +18,7 @@ import type { HeteroPermissionMode } from '@lobechat/types';import { isHeteroPermissionMode } from '@lobechat/types';/*- * Claude Code permission modes on this machine (Better Coding Experience lab).+ * Claude Code permission modes on this machine.* The CLI asks over stdio (`--permission-prompt-tool stdio`, see the driver),* the SDK through `canUseTool`; both raise their cards on the run's* AskUserBridge, so the renderer answers them like any other question carddiff --git a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts b/apps/desktop/src/main/controllers/heterogeneousAgentSession.tsindex 15a966f65f7..8177acf3e83 100644--- a/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts+++ b/apps/desktop/src/main/controllers/heterogeneousAgentSession.ts@@ -64,7 +64,7 @@ export interface SendPromptParams {/** Assistant row this run streams into — recorded so recovery can scope to its branch. */assistantMessageId?: string;/**- * (Codex, Better Coding Experience lab) The Plan switch: the collaboration+ * (Codex) The Plan switch: the collaboration* mode every native app-server turn sends. Absent sends none.*/collaborationMode?: CodexCollaborationMode;@@ -77,9 +77,9 @@ export interface SendPromptParams {*/operationId: string;/**- * (Claude Code, Better Coding Experience lab) Permission mode the run starts- * in; Claude Code then asks before acting as the mode requires and each- * request raises a card. Absent: every action is allowed, as before the lab.+ * (Claude Code) Permission mode the run starts in; Claude Code then asks+ * before acting as the mode requires and each request raises a card.+ * Absent (an older renderer): every action is allowed.*/permissionMode?: HeteroPermissionMode;prompt: string;diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts b/apps/desktop/src/main/modules/heterogeneousAgent/types.tsindex 673f9e033c9..1e39a0b6bce 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/types.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/types.ts@@ -45,7 +45,7 @@ export interface HeterogeneousAgentBuildPlanParams {*/mcpConfigPath?: string;/**- * (Claude Code) Better Coding Experience permission mode. Absent: every+ * (Claude Code) Permission mode. Absent: every* action is allowed.*/permissionMode?: HeteroPermissionMode;diff --git a/apps/server/src/routers/lambda/__tests__/work.topicPullRequests.test.ts b/apps/server/src/routers/lambda/__tests__/work.topicPullRequests.test.tsindex 04ef64c6130..e4a563635d0 100644--- a/apps/server/src/routers/lambda/__tests__/work.topicPullRequests.test.ts+++ b/apps/server/src/routers/lambda/__tests__/work.topicPullRequests.test.ts@@ -35,7 +35,6 @@ vi.mock('@/database/models/work', () => ({vi.mock('@/database/models/topic', () => ({ TopicModel: Model }));vi.mock('@/server/services/workRegistration', async (importOriginal) => ({...(await importOriginal<any>()),- isBetterCodingExperienceEnabled: vi.fn(async () => true),linkTopicPullRequest: mocks.linkTopicPullRequest,setTopicPullRequestDismissed: mocks.setTopicPullRequestDismissed,}));diff --git a/apps/server/src/routers/lambda/aiAgent/hetero.control.test.ts b/apps/server/src/routers/lambda/aiAgent/hetero.control.test.tsindex b144c1d5b74..22b81371a9e 100644--- a/apps/server/src/routers/lambda/aiAgent/hetero.control.test.ts+++ b/apps/server/src/routers/lambda/aiAgent/hetero.control.test.ts@@ -64,7 +64,7 @@ beforeEach(() => {mocks.getRedisServiceClient.mockResolvedValue(createHeteroControlFakeRedis());mocks.operation = mainRun;mocks.takeHeteroSteer.mockResolvedValue(undefined);- mocks.readFollowUpMode.mockResolvedValue('legacy');+ mocks.readFollowUpMode.mockResolvedValue('steer');});describe('waitHeteroSteer and the Follow-up behavior', () => {@@ -86,14 +86,14 @@ describe('waitHeteroSteer and the Follow-up behavior', () => {expect(mocks.takeHeteroSteer).not.toHaveBeenCalled();});- it('asks for a merged steer in Steer mode', async () => {+ it('takes a steer for the live session in Steer mode', async () => {mocks.readFollowUpMode.mockResolvedValue('steer');await caller.waitHeteroSteer({ blockMs: 1, operationId: 'op-1' });expect(mocks.takeHeteroSteer).toHaveBeenCalledWith(expect.anything(),- expect.objectContaining({ mode: 'steer', operationId: 'op-1' }),+ expect.objectContaining({ operationId: 'op-1' }),);});});diff --git a/apps/server/src/routers/lambda/aiAgent/hetero.ts b/apps/server/src/routers/lambda/aiAgent/hetero.tsindex cf82a703a9f..13717a9fd6e 100644--- a/apps/server/src/routers/lambda/aiAgent/hetero.ts+++ b/apps/server/src/routers/lambda/aiAgent/hetero.ts@@ -629,7 +629,7 @@ export const heteroRouter = router({if (scope) await renewHeteroSteers(operationId);// Queue mode leaves the follow-ups to the run end; read once per poll.- const followUpMode = scope ? await readFollowUpMode(ctx.serverDB, ctx.userId) : 'legacy';+ const followUpMode = scope ? await readFollowUpMode(ctx.serverDB, ctx.userId) : undefined;const deadline = Date.now() + blockMs;for (;;) {@@ -649,7 +649,6 @@ export const heteroRouter = router({acceptsImageAttachments,acceptsImages,agentId: operation.agentId,- mode: followUpMode,operationId,scope,});diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.tsindex 6441e5fc898..a26b1708673 100644--- a/apps/server/src/routers/lambda/work.ts+++ b/apps/server/src/routers/lambda/work.ts@@ -23,7 +23,7 @@ import { createCanvasStorageService, isOwnCanvasManifestKey } from '@/server/serimport { deleteCanvas } from '@/server/services/canvas/delete';import {AgentWorkRunError,- isBetterCodingExperienceEnabled,+ createShellPullRequestLinking,linkPushedPullRequests,linkTopicPullRequest,listTopicPullRequestsWithStatus,@@ -31,7 +31,6 @@ import {registerShellWorksForLocalRun,resolveAgentWorkFile,resolveAgentWorkRun,- resolveShellPullRequestLinking,setTopicPullRequestDismissed,} from '@/server/services/workRegistration';@@ -461,7 +460,7 @@ export const workRouter = router({anchorMessageId: input.anchorMessageId,messageIds: input.messageIds,messageModel: ctx.messageModel,- pullRequestLinking: await resolveShellPullRequestLinking({+ pullRequestLinking: createShellPullRequestLinking({db: ctx.serverDB,topicId: input.topicId,userId: ctx.userId,@@ -473,7 +472,7 @@ export const workRouter = router({}),),- // Better Coding Experience: the GitHub pull requests a topic's Work rows+ // The GitHub pull requests a topic's Work rows// link, with the GitHub App's state where an installation tracks the repo.listTopicPullRequests: workProcedure.input(z.object({ topicId: z.string().min(1) }))@@ -540,7 +539,7 @@ export const workRouter = router({};}),- // Better Coding Experience: link the pull requests a `git push` tool call+ // Link the pull requests a `git push` tool call// updated, right after it ran. The push itself is re-read from the persisted// tool message; see `linkPushedPullRequests` for what the device may add.linkPushedPullRequests: skillWorkProcedureWrite@@ -576,7 +575,7 @@ export const workRouter = router({}),),- // Better Coding Experience: keep a PR on the topic itself — found on the+ // Keep a PR on the topic itself — found on the// topic's own branch at run end (`branch`), or pasted by the person// (`manual`). A topic link only drives the topic's PR lists: unlike a Work// row it is never read by the SCM links, so a client-named PR cannot make a@@ -601,9 +600,6 @@ export const workRouter = router({if (!parsed) {throw new TRPCError({ code: 'BAD_REQUEST', message: 'Not a GitHub pull request URL' });}- if (!(await isBetterCodingExperienceEnabled(ctx.serverDB, ctx.userId))) {- return { identifier: parsed.identifier, linked: false };- }const linked = await linkTopicPullRequest(ctx.topicModel, input.topicId, {...(input.headRefName ? { headRefName: input.headRefName } : {}),identifier: parsed.identifier,@@ -616,7 +612,7 @@ export const workRouter = router({return { identifier: parsed.identifier, linked };}),- // Better Coding Experience: remove a PR from the topic's lists (or bring it+ // Remove a PR from the topic's lists (or bring it// back). Its Work rows stay; only the topic's view of them changes.setTopicPullRequestDismissed: workProcedure.use(withScopedPermission('topic:update'))diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.tsindex 2910c62882e..de362d1e353 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/steerQueue.test.ts@@ -36,7 +36,7 @@ describe('server-side steer queue in the step loop', () => {steerQueueLength.mockResolvedValue(0);steerQueueSeal.mockResolvedValue(undefined);steerQueueUnseal.mockResolvedValue(undefined);- readFollowUpMode.mockResolvedValue('legacy');+ readFollowUpMode.mockResolvedValue('steer');});describe('Follow-up behavior: Queue', () => {diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.test.tsindex 064f3fc27fa..aab022f2f9b 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.test.ts@@ -15,7 +15,7 @@ const resolve = (topicMetadata: Record<string, unknown> | undefined, heteroTypedescribe('resolveDispatchCollaborationMode', () => {beforeEach(() => {- preference.lab = { enableBetterCodingExperience: true, enableCodexAppServer: true };+ preference.lab = { enableCodexAppServer: true };});it('sends nothing for a topic that never turned Plan on, or another agent', async () => {@@ -23,16 +23,14 @@ describe('resolveDispatchCollaborationMode', () => {await expect(resolve({ heteroPlanMode: true }, 'claude-code')).resolves.toBeUndefined();});- it('sends the switch, off included, with both labs on', async () => {+ it('sends the switch, off included, with the app-server lab on', async () => {await expect(resolve({ heteroPlanMode: true })).resolves.toBe('plan');await expect(resolve({ heteroPlanMode: false })).resolves.toBe('default');});- it('sends nothing with either lab off', async () => {- for (const lab of [{ enableCodexAppServer: true }, { enableBetterCodingExperience: true }]) {- preference.lab = lab;- await expect(resolve({ heteroPlanMode: true })).resolves.toBeUndefined();- }+ it('sends nothing with the app-server lab off', async () => {+ preference.lab = {};+ await expect(resolve({ heteroPlanMode: true })).resolves.toBeUndefined();});});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.tsindex dbd99cf772d..d9bf371af69 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/codexCollaboration.ts@@ -8,11 +8,10 @@ import type { LobeChatDatabase } from '@/database/type';const log = debug('lobe-server:hetero-dispatch:codex-collaboration');/**- * The collaboration mode a dispatched Codex run sends (Better Coding Experience- * Plan switch), before the device's runtime is known: only with both labs on- * (Better Coding Experience and the Codex app-server) and a topic that turned- * Plan on at least once; otherwise none, exactly as before the lab. Codex keeps- * the mode on the thread, so once used it is sent on every turn.+ * The collaboration mode a dispatched Codex run sends (the Plan switch), before+ * the device's runtime is known: only with the Codex app-server lab on and a+ * topic that turned Plan on at least once; otherwise none. Codex keeps the+ * mode on the thread, so once used it is sent on every turn.** A failed preference read sends no mode rather than guessing.*/@@ -26,7 +25,7 @@ export const resolveDispatchCollaborationMode = async (if (!mode) return;try {const lab = (await new UserModel(db, userId).getUserPreference())?.lab;- return lab?.enableBetterCodingExperience && lab?.enableCodexAppServer ? mode : undefined;+ return lab?.enableCodexAppServer ? mode : undefined;} catch (error) {log('Reading the lab preference of %s failed: %O', userId, error);}diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.test.tsindex f38360c4c07..78439b9a09d 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.test.ts@@ -1,52 +1,29 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';import { resolveDispatchPermissionMode } from './permissionMode';-const getUserPreference = vi.hoisted(() => vi.fn());--vi.mock('@/database/models/user', () => ({- UserModel: vi.fn(function () {- return { getUserPreference };- }),-}));--const db = {} as any;-describe('resolveDispatchPermissionMode', () => {- beforeEach(() => {- getUserPreference.mockReset();- });-- it('starts Claude Code in the topic mode when the lab is on', async () => {- getUserPreference.mockResolvedValue({ lab: { enableBetterCodingExperience: true } });- await expect(- resolveDispatchPermissionMode(db, 'u', {+ it('starts Claude Code in the topic mode, bypassPermissions by default', () => {+ expect(+ resolveDispatchPermissionMode({heteroType: 'claude-code',topicMetadata: { heteroPermissionMode: 'plan' },}),- ).resolves.toBe('plan');- await expect(- resolveDispatchPermissionMode(db, 'u', { heteroType: 'claude-code', topicMetadata: {} }),- ).resolves.toBe('bypassPermissions');+ ).toBe('plan');+ expect(resolveDispatchPermissionMode({ heteroType: 'claude-code', topicMetadata: {} })).toBe(+ 'bypassPermissions',+ );+ expect(+ resolveDispatchPermissionMode({ heteroType: 'claude-code', topicMetadata: undefined }),+ ).toBe('bypassPermissions');});- it('sends no mode with the lab off, for other agents, or when the read fails', async () => {- getUserPreference.mockResolvedValue({ lab: {} });- await expect(- resolveDispatchPermissionMode(db, 'u', {- heteroType: 'claude-code',+ it('sends no mode for other agents', () => {+ expect(+ resolveDispatchPermissionMode({+ heteroType: 'codex',topicMetadata: { heteroPermissionMode: 'plan' },}),- ).resolves.toBeUndefined();-- getUserPreference.mockResolvedValue({ lab: { enableBetterCodingExperience: true } });- await expect(- resolveDispatchPermissionMode(db, 'u', { heteroType: 'codex', topicMetadata: {} }),- ).resolves.toBeUndefined();-- getUserPreference.mockRejectedValue(new Error('db down'));- await expect(- resolveDispatchPermissionMode(db, 'u', { heteroType: 'claude-code', topicMetadata: {} }),- ).resolves.toBeUndefined();+ ).toBeUndefined();});});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.tsindex fc642ec0d7e..3e7177ea28e 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/permissionMode.ts@@ -1,36 +1,19 @@import type { ChatTopicMetadata, HeteroPermissionMode } from '@lobechat/types';import { DEFAULT_HETERO_PERMISSION_MODE, isHeteroPermissionMode } from '@lobechat/types';-import debug from 'debug';--import { UserModel } from '@/database/models/user';-import type { LobeChatDatabase } from '@/database/type';--const log = debug('lobe-server:hetero-dispatch:permission-mode');/**- * The Claude Code permission mode a dispatched run starts in, or undefined to- * allow every action as before the Better Coding Experience lab.+ * The Claude Code permission mode a dispatched run starts in; undefined for+ * other agents.*- * Only for Claude Code with the run owner's lab on. The topic carries the mode- * (the composer's chip writes it, and Claude Code's own switches are written- * back), defaulting to `bypassPermissions`. A failed preference read keeps the- * pre-lab behavior rather than starting a run that asks.+ * The topic carries the mode (the composer's chip writes it, and Claude Code's+ * own switches are written back), defaulting to `bypassPermissions`.*/-export const resolveDispatchPermissionMode = async (- db: LobeChatDatabase,- userId: string,- params: { heteroType: string; topicMetadata: ChatTopicMetadata | null | undefined },-): Promise<HeteroPermissionMode | undefined> => {+export const resolveDispatchPermissionMode = (params: {+ heteroType: string;+ topicMetadata: ChatTopicMetadata | null | undefined;+}): HeteroPermissionMode | undefined => {if (params.heteroType !== 'claude-code') return;- try {- const preference = await new UserModel(db, userId).getUserPreference();- if (!preference?.lab?.enableBetterCodingExperience) return;- } catch (error) {- log('Reading the lab preference of %s failed: %O', userId, error);- return;- }-const mode = params.topicMetadata?.heteroPermissionMode;return isHeteroPermissionMode(mode) ? mode : DEFAULT_HETERO_PERMISSION_MODE;};diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.tsindex 1e37d61a254..80de2a4277e 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts@@ -202,16 +202,16 @@ export const prepareHeteroRun = async (traceHeteroStage('topic', () => deps.topicModel.findById(topicId)),]);const topicRepos: string[] = topic?.metadata?.repos ?? [];- const permissionModePromise = resolveDispatchPermissionMode(deps.db, deps.userId, {+ const permissionMode = resolveDispatchPermissionMode({heteroType,topicMetadata: topic?.metadata,- }).then(async (mode) => {- // An `lh` that never reports the mode back is flagged when the run ends.- await expectPermissionModeReport(deps.topicModel, { mode, operationId, topicId }).catch(- (error) => log('execAgent: permission mode report marker failed: %O', error),- );- return mode;});+ // An `lh` that never reports the mode back is flagged when the run ends.+ const permissionModeReportPromise = expectPermissionModeReport(deps.topicModel, {+ mode: permissionMode,+ operationId,+ topicId,+ }).catch((error) => log('execAgent: permission mode report marker failed: %O', error));const collaborationModePromise = resolveDispatchCollaborationMode(deps.db, deps.userId, {heteroType,@@ -395,6 +395,7 @@ export const prepareHeteroRun = async (): undefined;+ await permissionModeReportPromise;const heteroParams = {agentType: heteroType,assistantMessageId,@@ -412,7 +413,7 @@ export const prepareHeteroRun = async (imageList: heteroImageList,jwt: operationJwt,operationId,- permissionMode: await permissionModePromise,+ permissionMode,// The CLI receives only the request: `/goal` is already in the system// context, and Claude Code's own `/goal` command would otherwise take it.// Non-image attachments have no content block a CLI accepts, so they ridediff --git a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.tsindex ce2409b8320..5c6482312b8 100644--- a/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts+++ b/apps/server/src/services/aiAgent/pipeline/newTopicMetadata.ts@@ -24,7 +24,7 @@ export interface NewTopicMetadataInput {/*** The worktree the composer created for this topic on its first send- * (Better Coding Experience "New worktree"), when it was cut from the project+ * ("New worktree"), when it was cut from the project* directory the topic is born in. The project directory still names the* source; the worktree is where the topic runs, so it must survive the* project override below.@@ -104,7 +104,7 @@ export const buildNewTopicMetadata = ({...(openedBy && { openedBy }),taskId,...(webhookThread && { webhook: webhookThread }),- // Claude Code permission mode the composer chip showed (Better Coding Experience).+ // Claude Code permission mode the composer chip showed....(initialTopicMeta?.heteroPermissionMode && {heteroPermissionMode: initialTopicMeta.heteroPermissionMode,}),diff --git a/apps/server/src/services/aiAgent/steerQueue/followUpMode.test.ts b/apps/server/src/services/aiAgent/steerQueue/followUpMode.test.tsindex 75efb5f0d4a..73f08763ed4 100644--- a/apps/server/src/services/aiAgent/steerQueue/followUpMode.test.ts+++ b/apps/server/src/services/aiAgent/steerQueue/followUpMode.test.ts@@ -2,15 +2,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { readFollowUpMode } from './followUpMode';-const mocks = vi.hoisted(() => ({ getUserPreference: vi.fn(), getUserSettings: vi.fn() }));+const mocks = vi.hoisted(() => ({ getUserSettings: vi.fn() }));vi.mock('@/database/models/user', () => ({UserModel: vi.fn().mockImplementation(function () {- return { getUserPreference: mocks.getUserPreference, getUserSettings: mocks.getUserSettings };+ return { getUserSettings: mocks.getUserSettings };}),}));const db = {} as any;-const lab = (enabled: boolean) => ({ lab: { enableBetterCodingExperience: enabled } });beforeEach(() => {vi.clearAllMocks();@@ -18,30 +17,19 @@ beforeEach(() => {});describe('readFollowUpMode', () => {- it('keeps the legacy behavior while the lab is off, without reading settings', async () => {- mocks.getUserPreference.mockResolvedValue(lab(false));- mocks.getUserSettings.mockResolvedValue({ general: { followUpBehavior: 'queue' } });-- await expect(readFollowUpMode(db, 'user-1')).resolves.toBe('legacy');- expect(mocks.getUserSettings).not.toHaveBeenCalled();- });-- it('defaults to steer with the lab on', async () => {- mocks.getUserPreference.mockResolvedValue(lab(true));-+ it('defaults to steer', async () => {await expect(readFollowUpMode(db, 'user-1')).resolves.toBe('steer');});- it('reads the stored setting with the lab on', async () => {- mocks.getUserPreference.mockResolvedValue(lab(true));+ it('reads the stored setting', async () => {mocks.getUserSettings.mockResolvedValue({ general: { followUpBehavior: 'queue' } });await expect(readFollowUpMode(db, 'user-1')).resolves.toBe('queue');});- it('falls back to the legacy behavior when the read fails', async () => {- mocks.getUserPreference.mockRejectedValue(new Error('db down'));+ it('falls back to steer when the read fails', async () => {+ mocks.getUserSettings.mockRejectedValue(new Error('db down'));- await expect(readFollowUpMode(db, 'user-1')).resolves.toBe('legacy');+ await expect(readFollowUpMode(db, 'user-1')).resolves.toBe('steer');});});diff --git a/apps/server/src/services/aiAgent/steerQueue/followUpMode.ts b/apps/server/src/services/aiAgent/steerQueue/followUpMode.tsindex 9048773485c..05d9fe1bea4 100644--- a/apps/server/src/services/aiAgent/steerQueue/followUpMode.ts+++ b/apps/server/src/services/aiAgent/steerQueue/followUpMode.ts@@ -1,5 +1,5 @@-import type { FollowUpBehavior, FollowUpMode, UserGeneralConfig } from '@lobechat/types';-import { resolveFollowUpMode } from '@lobechat/types';+import type { FollowUpBehavior, UserGeneralConfig } from '@lobechat/types';+import { DEFAULT_FOLLOW_UP_BEHAVIOR } from '@lobechat/types';import debug from 'debug';import { UserModel } from '@/database/models/user';@@ -8,31 +8,25 @@ import type { LobeChatDatabase } from '@/database/type';const log = debug('lobe-server:steer-queue:mode');/**- * The run owner's Follow-up behavior (Settings → Chat, under the Better Coding- * Experience lab): what the follow-ups queued behind their run do.+ * The run owner's Follow-up behavior (Settings → Chat): what the follow-ups+ * queued behind their run do.** - `steer`: join the running turn, merged into one message per join.* - `queue`: wait for the run to end and start one turn each.- * - `legacy`: the lab is off, so the behavior from before the setting.** Read when a queue has entries, so a change applies at the next decision- * point. A read that fails falls back to `legacy`, which is what every run did- * before the setting existed.+ * point. A read that fails falls back to the default, `steer`.*/export const readFollowUpMode = async (db: LobeChatDatabase,userId: string,-): Promise<FollowUpMode> => {+): Promise<FollowUpBehavior> => {try {- const model = new UserModel(db, userId);- const preference = await model.getUserPreference();- if (!preference?.lab?.enableBetterCodingExperience) return 'legacy';-- const settings = await model.getUserSettings();+ const settings = await new UserModel(db, userId).getUserSettings();const general = settings?.general as UserGeneralConfig | undefined;- return resolveFollowUpMode(true, general?.followUpBehavior as FollowUpBehavior | undefined);+ return general?.followUpBehavior ?? DEFAULT_FOLLOW_UP_BEHAVIOR;} catch (error) {log('Reading the follow-up behavior of %s failed: %O', userId, error);- return 'legacy';+ return DEFAULT_FOLLOW_UP_BEHAVIOR;}};diff --git a/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts b/apps/server/src/services/aiAgent/steerQueue/hetero.test.tsindex 3c051b21f1a..17041bc1d0b 100644--- a/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts+++ b/apps/server/src/services/aiAgent/steerQueue/hetero.test.ts@@ -127,20 +127,8 @@ describe('canSteerHeteroRun', () => {});describe('takeHeteroSteer', () => {- it('hands out the first follow-up and returns the rest to the queue', async () => {- mocks.drain.mockResolvedValue([followUp('a', 1), followUp('b', 2)]);-- await expect(take()).resolves.toEqual({ content: 'prompt a', messageId: 'msg-a' });-- // `b` goes back; `a` stays in the leased batch until Claude Code picks it up.- const [, drained, returned] = mocks.settle.mock.calls[0];- expect(returned).toEqual(['b']);- expect(mocks.deliveries.get('msg-a')).toContain(`"drainId":"${drained}"`);- });-- describe('Steer mode', () => {- const steer = () =>- takeHeteroSteer(ctx, { agentId: 'agt-1', mode: 'steer', operationId: 'op-1', scope });+ describe('merging', () => {+ const steer = take;it('merges every leading follow-up that can join into one message', async () => {mocks.drain.mockResolvedValue([@@ -222,7 +210,6 @@ describe('takeHeteroSteer', () => {acceptsImageAttachments: true,acceptsImages: true,agentId: 'agt-1',- mode: 'steer',operationId: 'op-1',scope,});@@ -284,7 +271,7 @@ describe('takeHeteroSteer', () => {const image = { id: 'file_1', url: 'https://bucket.example.com/files/1.png?X-Amz-Signature=s' };it('hands them over with the text when the session takes images', async () => {- mocks.drain.mockResolvedValue([followUp('a', 1, { prompt: pasted }), followUp('b', 2)]);+ mocks.drain.mockResolvedValue([followUp('a', 1, { prompt: pasted })]);mocks.resolveInlineImages.mockResolvedValue([image]);await expect(@@ -292,7 +279,6 @@ describe('takeHeteroSteer', () => {).resolves.toEqual({ content: pasted, imageList: [image], messageId: 'msg-a' });expect(mocks.resolveInlineImages).toHaveBeenCalledWith(ctx, pasted);- expect(mocks.settle.mock.calls[0][2]).toEqual(['b']);expect(mocks.deliveries.has('msg-a')).toBe(true);});diff --git a/apps/server/src/services/aiAgent/steerQueue/hetero.ts b/apps/server/src/services/aiAgent/steerQueue/hetero.tsindex 6314d3ab98c..4de8b988002 100644--- a/apps/server/src/services/aiAgent/steerQueue/hetero.ts+++ b/apps/server/src/services/aiAgent/steerQueue/hetero.ts@@ -1,4 +1,4 @@-import type { AgentSenderMetadata, ChatImageItem, FollowUpMode } from '@lobechat/types';+import type { AgentSenderMetadata, ChatImageItem } from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';import debug from 'debug';@@ -43,7 +43,7 @@ export interface HeteroSteerDelivery {drainId: string;editorData?: unknown;entryId: string;- /** Every follow-up merged into this delivery, when there were several (Steer mode). */+ /** Every follow-up merged into this delivery, when there were several. */entryIds?: string[];fileIds?: string[];groupId?: string;@@ -136,9 +136,8 @@ const fitsSession = (entry: QueuedFollowUp, acceptsImages: boolean | undefined)* attachment, a tool selection…) stops the take, and it and everything behind* it wait for the run to end.*- * In Steer mode (`mode: 'steer'`) every leading follow-up that can join, from- * one author, goes as one merged message; otherwise one goes per delivery.- * Either way the agent reads it when it is ready (Claude Code: at its next+ * Every leading follow-up that can join, from one author, goes as one merged+ * message. The agent reads it when it is ready (Claude Code: at its next* tool boundary), so a running tool is never cut short.** Images pasted into the body go along as `imageList` when the session takes@@ -154,13 +153,11 @@ export const takeHeteroSteer = async (acceptsImageAttachments?: boolean;acceptsImages?: boolean;agentId: string | null;- mode?: FollowUpMode;operationId: string;scope: SteerQueueScope;},): Promise<HeteroSteerMessage | undefined> => {const { acceptsImageAttachments, acceptsImages, agentId, operationId, scope } = params;- const merging = params.mode === 'steer';const drained = await drainOwnFollowUps(ctx, scope, operationId);if (drained.entries.length === 0) return;@@ -191,7 +188,7 @@ export const takeHeteroSteer = async (fitsSession(entry, acceptsImages);const firstHeld = drained.entries.findIndex((entry) => !canGo(entry));const ready = firstHeld === -1 ? drained.entries : drained.entries.slice(0, firstHeld);- const candidates = merging ? takeSameSenderFollowUps(ready).taken : ready.slice(0, 1);+ const candidates = takeSameSenderFollowUps(ready).taken;// Resolve only the files this poll could deliver. The metadata lookup checks// file ownership without parsing documents that must wait for another turn.@@ -236,12 +233,7 @@ export const takeHeteroSteer = async (}}const rest = drained.entries.filter((entry) => !joining.includes(entry));- await returnFollowUps(- scope,- drained,- rest,- merging ? 'waits for the next join' : 'delivered one at a time',- );+ await returnFollowUps(scope, drained, rest, 'waits for the next join');const messageId = queuedUserMessageId(ctx.userId, joining, request);diff --git a/apps/server/src/services/aiAgent/steerQueue/index.test.ts b/apps/server/src/services/aiAgent/steerQueue/index.test.tsindex 4cc1d81ee41..ded0605c090 100644--- a/apps/server/src/services/aiAgent/steerQueue/index.test.ts+++ b/apps/server/src/services/aiAgent/steerQueue/index.test.ts@@ -179,7 +179,7 @@ describe('startQueuedFollowUp', () => {assertCanUseAgentRunConversation.mockResolvedValue(undefined);startComposerRun.mockResolvedValue({ operationId: 'op-2' });findMessageById.mockResolvedValue(undefined);- readFollowUpMode.mockResolvedValue('legacy');+ readFollowUpMode.mockResolvedValue('steer');});it('starts only the oldest follow-up in Queue mode; the rest wait for that turn to end', async () => {diff --git a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts b/apps/server/src/services/heterogeneousAgent/sandboxRunner.tsindex 6ce10c746db..2550f9dfc46 100644--- a/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts+++ b/apps/server/src/services/heterogeneousAgent/sandboxRunner.ts@@ -43,7 +43,7 @@ export interface SandboxRunParams {jwt: string;marketService: MarketService;operationId: string;- /** Claude Code permission mode (Better Coding Experience lab). */+ /** Claude Code permission mode. */permissionMode?: HeteroPermissionMode;prompt: string;/** GitHub repos to clone before running the agent (e.g. ['owner/repo', ...]). */diff --git a/apps/server/src/services/workRegistration/index.ts b/apps/server/src/services/workRegistration/index.tsindex e730c3df11d..cfe04a6d300 100644--- a/apps/server/src/services/workRegistration/index.ts+++ b/apps/server/src/services/workRegistration/index.ts@@ -32,11 +32,7 @@ export {type LocalRunShellWorksResult,registerShellWorksForLocalRun,} from './localRunWorkRegistration';-export {- isBetterCodingExperienceEnabled,- resolveShellPullRequestLinking,- type ShellPullRequestLinking,-} from './pullRequestLinking';+export { createShellPullRequestLinking, type ShellPullRequestLinking } from './pullRequestLinking';export {registerWorksForOperation,type RegisterWorksForOperationParams,diff --git a/apps/server/src/services/workRegistration/localRunWorkRegistration.ts b/apps/server/src/services/workRegistration/localRunWorkRegistration.tsindex 15e7e76b63c..a755ca7d1d1 100644--- a/apps/server/src/services/workRegistration/localRunWorkRegistration.ts+++ b/apps/server/src/services/workRegistration/localRunWorkRegistration.ts@@ -54,7 +54,7 @@ export const registerShellWorksForLocalRun = async (params: {anchorMessageId: string;messageIds: string[];messageModel: MessageModel;- /** Better Coding Experience pull request linking; see `registerShellWorks`. */+ /** Pull request linking; see `registerShellWorks`. */pullRequestLinking?: ShellPullRequestLinking;topicId: string;workModel: WorkModel;diff --git a/apps/server/src/services/workRegistration/pullRequestLinking.ts b/apps/server/src/services/workRegistration/pullRequestLinking.tsindex 5d9a0749c0d..d38f54ac444 100644--- a/apps/server/src/services/workRegistration/pullRequestLinking.ts+++ b/apps/server/src/services/workRegistration/pullRequestLinking.ts@@ -1,12 +1,7 @@-import debug from 'debug';-import { ScmChangeRequestModel } from '@/database/models/scm';-import { UserModel } from '@/database/models/user';import type { WorkModel } from '@/database/models/work';import type { LobeChatDatabase } from '@/database/type';-const log = debug('lobe-server:pull-request-linking');-/** A pull request a `git push` updated, as the GitHub App last reported it. */export interface PushedPullRequest {headRef: string | null;@@ -18,8 +13,9 @@ export interface PushedPullRequest {/*** What the shell Work scan needs to tie pull requests to a topic beyond- * `gh pr create|edit` (Better Coding Experience). Present only while the lab- * is on for the run's user, so a scan without it behaves exactly as before.+ * `gh pr create|edit`: a `git push` of a branch with an open PR, and numbered+ * `gh pr ready|merge` runs. A scan without it (a share visitor's run, fenced+ * off from the creator's topics) registers only what the commands name.*/export interface ShellPullRequestLinking {/** Open pull requests of `repoFullName` headed by one of `branches`. */@@ -31,20 +27,6 @@ export interface ShellPullRequestLinking {listTopicPullRequestIds: () => Promise<string[]>;}-/** `users.preference.lab.enableBetterCodingExperience`, false when unreadable. */-export const isBetterCodingExperienceEnabled = async (- db: LobeChatDatabase,- userId: string,-): Promise<boolean> => {- try {- const preference = await new UserModel(db, userId).getUserPreference();- return preference?.lab?.enableBetterCodingExperience === true;- } catch (error) {- log('Failed to read the Better Coding Experience preference: %O', error);- return false;- }-};-/*** Pull request lookups for one topic's scan. The push lookup reads* `scm_change_requests` — the GitHub App's webhook-fed rows — under the same@@ -83,11 +65,3 @@ export const createShellPullRequestLinking = (params: {(await params.workModel.listTopicPullRequests(params.topicId)).map((item) => item.identifier),};};--/** {@link createShellPullRequestLinking} when the lab is on for `userId`, else undefined. */-export const resolveShellPullRequestLinking = async (- params: Parameters<typeof createShellPullRequestLinking>[0],-): Promise<ShellPullRequestLinking | undefined> =>- (await isBetterCodingExperienceEnabled(params.db, params.userId))- ? createShellPullRequestLinking(params)- : undefined;diff --git a/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.test.tsindex b7223da4aed..84e70c80383 100644--- a/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { MessageModel } from '@/database/models/message';+import type * as WorkModule from '@/database/models/work';import { WorkModel } from '@/database/models/work';import { redeployFileWork, registerWorksForOperation } from './registerWorksForOperation';@@ -52,7 +53,9 @@ vi.mock('@/database/models/message', () => ({}),}));-vi.mock('@/database/models/work', () => ({+vi.mock('@/database/models/work', async (importOriginal) => ({+ // The push scanner parses git's own report with the real parser.+ parseGitPushResult: (await importOriginal<typeof WorkModule>()).parseGitPushResult,WorkModel: vi.fn(function () {return {fillAgentWorkCost: mockFillAgentWorkCost,@@ -813,6 +816,8 @@ describe('registerWorksForOperation · shell github works', () => {toolName: 'command_execution',topicId: 'topic-1',}),+ // Pull request linking: numbered `gh pr ready|merge` look up the topic's PRs.+ expect.objectContaining({ pullRequestLifecycle: true }),);// Hetero runs never pass callLlmFinalizer → the anchor is stamped here.expect(mockUpdateMessage).toHaveBeenCalledWith('msg-assistant', {@@ -863,6 +868,7 @@ describe('registerWorksForOperation · shell github works', () => {toolIdentifier: 'claude-code',toolName: 'Bash',}),+ expect.objectContaining({ pullRequestLifecycle: true }),);});diff --git a/apps/server/src/services/workRegistration/registerWorksForOperation.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.tsindex a9262e76564..18c0e6e530c 100644--- a/apps/server/src/services/workRegistration/registerWorksForOperation.ts+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.ts@@ -23,7 +23,7 @@ import { MarketService } from '@/server/services/market';import { createSandboxService } from '@/server/services/sandbox';import { UNEXECUTED_INTERVENTION_STATUSES } from './constants';-import { resolveShellPullRequestLinking } from './pullRequestLinking';+import { createShellPullRequestLinking } from './pullRequestLinking';import { resolveRunWorkAccessScope, type ShareVisitorWorkIdentity } from './shareWorkScope';import { registerShellWorks } from './shellWorkRegistration';@@ -447,7 +447,7 @@ export const registerWorksForOperation = async (// links pull requests into them.const pullRequestLinking = params.agentShareVisitor? undefined- : await resolveShellPullRequestLinking({+ : createShellPullRequestLinking({db: serverDB,topicId,userId,diff --git a/apps/server/src/services/workRegistration/shellWorkRegistration.ts b/apps/server/src/services/workRegistration/shellWorkRegistration.tsindex 7a8e83e7828..8ce048340ee 100644--- a/apps/server/src/services/workRegistration/shellWorkRegistration.ts+++ b/apps/server/src/services/workRegistration/shellWorkRegistration.ts@@ -151,8 +151,8 @@ export const registerShellWorks = async (params: {cumulativeUsage: WorkVersionCumulativeUsage | null;operationId: string;/**- * Better Coding Experience pull request linking; omitted (lab off) the scan- * registers exactly what it always did.+ * Pull request linking; omitted (a share visitor's run) the scan registers+ * only what the commands name.*/pullRequestLinking?: ShellPullRequestLinking;records: ShellWorkScanRecord[];diff --git a/apps/server/src/services/workRegistration/shellWorkScanners/github.ts b/apps/server/src/services/workRegistration/shellWorkScanners/github.tsindex 3a792e3945d..1f87c0deddf 100644--- a/apps/server/src/services/workRegistration/shellWorkScanners/github.ts+++ b/apps/server/src/services/workRegistration/shellWorkScanners/github.ts@@ -1,8 +1,8 @@import type { ShellWorkScanner } from './types';/**- * github issue/PR Works from `gh issue|pr create/edit` runs — plus, under the- * Better Coding Experience lab, numbered `gh pr ready|merge` runs. Parsing reuses+ * github issue/PR Works from `gh issue|pr create/edit` runs — plus, when the+ * scan carries pull request linking, numbered `gh pr ready|merge` runs. Parsing reuses* the github skill's gh-CLI normalizer (via* `workModel.registerShellGithubResult` → `normalizeGithubShellToolResult`),* so identity lands on the same `owner/repo#number` Work row asdiff --git a/apps/server/src/services/workRegistration/shellWorkScanners/githubPush.ts b/apps/server/src/services/workRegistration/shellWorkScanners/githubPush.tsindex 464279eae20..21982724343 100644--- a/apps/server/src/services/workRegistration/shellWorkScanners/githubPush.ts+++ b/apps/server/src/services/workRegistration/shellWorkScanners/githubPush.ts@@ -4,7 +4,7 @@ import type { ShellWorkScanner } from './types';/*** A `git push` to a branch that already has an open pull request links that- * pull request to the topic (Better Coding Experience only). The branch and+ * pull request to the topic. The branch and* repository come from git's own push report; which pull request the branch* heads comes from the GitHub App's rows — never from the agent's text — so a* push links nothing in a repository no installation tracks (the client'sdiff --git a/apps/server/src/services/workRegistration/shellWorkScanners/types.ts b/apps/server/src/services/workRegistration/shellWorkScanners/types.tsindex 2f77f798ea5..4f1dfecc643 100644--- a/apps/server/src/services/workRegistration/shellWorkScanners/types.ts+++ b/apps/server/src/services/workRegistration/shellWorkScanners/types.ts@@ -32,7 +32,7 @@ export interface ShellWorkScanner {cumulativeUsage: WorkVersionCumulativeUsage | null;data: { command: string; exitCode?: number; output?: string };messageId: string;- /** Present when the lab is on; see {@link ShellPullRequestLinking}. */+ /** Absent for a share visitor's run; see {@link ShellPullRequestLinking}. */pullRequestLinking?: ShellPullRequestLinking;rootOperationId: string;threadId: string | null;@@ -49,8 +49,8 @@ export interface ShellWorkScanner {workModel: WorkModel;}) => Promise<unknown | null>;/**- * Runs only when the scan carries {@link ShellPullRequestLinking} (the- * Better Coding Experience lab is on); without it the scanner is skipped.+ * Runs only when the scan carries {@link ShellPullRequestLinking}; without+ * it (a share visitor's run) the scanner is skipped.*/requiresPullRequestLinking?: boolean;}diff --git a/apps/server/src/services/workRegistration/topicPullRequests.test.ts b/apps/server/src/services/workRegistration/topicPullRequests.test.tsindex b9cac75a2a6..a7264ac93bb 100644--- a/apps/server/src/services/workRegistration/topicPullRequests.test.ts+++ b/apps/server/src/services/workRegistration/topicPullRequests.test.ts@@ -2,18 +2,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { linkPushedPullRequests, listTopicPullRequestsWithStatus } from './topicPullRequests';-const { getUserPreference, listByIdentities, listOpenByHeadRefs } = vi.hoisted(() => ({- getUserPreference: vi.fn(),+const { listByIdentities, listOpenByHeadRefs } = vi.hoisted(() => ({listByIdentities: vi.fn(),listOpenByHeadRefs: vi.fn(),}));-vi.mock('@/database/models/user', () => ({- UserModel: vi.fn(function () {- return { getUserPreference };- }),-}));-vi.mock('@/database/models/scm', () => ({ScmChangeRequestModel: { listByIdentities, listOpenByHeadRefs },}));@@ -246,18 +239,9 @@ describe('linkPushedPullRequests', () => {beforeEach(() => {vi.clearAllMocks();- getUserPreference.mockResolvedValue({ lab: { enableBetterCodingExperience: true } });listOpenByHeadRefs.mockResolvedValue([]);});- it('does nothing while the lab is off', async () => {- getUserPreference.mockResolvedValue({ lab: {} });- const models = createModels();-- expect(await link(models)).toEqual({ status: 'skipped' });- expect(models.messageModel.findToolMessageIdByToolCallId).not.toHaveBeenCalled();- });-it('prefers the GitHub App rows for the pushed branch', async () => {listOpenByHeadRefs.mockResolvedValue([{diff --git a/apps/server/src/services/workRegistration/topicPullRequests.ts b/apps/server/src/services/workRegistration/topicPullRequests.tsindex e8de15f278c..501010ef546 100644--- a/apps/server/src/services/workRegistration/topicPullRequests.ts+++ b/apps/server/src/services/workRegistration/topicPullRequests.ts@@ -17,10 +17,7 @@ import { parseGitPushResult, type WorkModel } from '@/database/models/work';import type { LobeChatDatabase } from '@/database/type';import { SCM_MAX_WAKES } from '@/server/services/scm/limits';-import {- createShellPullRequestLinking,- isBetterCodingExperienceEnabled,-} from './pullRequestLinking';+import { createShellPullRequestLinking } from './pullRequestLinking';import { readShellCommandRecord } from './shellWorkRegistration';import { parsePullRequestUrl } from './topicPullRequestLinks';@@ -171,8 +168,7 @@ export type LinkPushedPullRequestsResult =const PULL_URL_RE = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)\/?$/i;/**- * Link the pull requests a `git push` updated, right after the push (Better- * Coding Experience). The server re-reads the push from the persisted tool+ * Link the pull requests a `git push` updated, right after the push. The server re-reads the push from the persisted tool* message — the client only names which call it was — and takes the* repository and branches from git's own report. Which pull request heads the* branch comes from, in order:@@ -193,10 +189,6 @@ export const linkPushedPullRequests = async (params: {workModel: WorkModel;workspaceId?: string | null;}): Promise<LinkPushedPullRequestsResult> => {- if (!(await isBetterCodingExperienceEnabled(params.db, params.userId))) {- return { status: 'skipped' };- }-const messageId = await params.messageModel.findToolMessageIdByToolCallId(params.toolCallId);if (!messageId) return { status: 'pending' };const [record] = await params.messageModel.listMessagePluginsByIds({diff --git a/apps/server/src/services/worktreeCleanup/index.ts b/apps/server/src/services/worktreeCleanup/index.tsindex 368e9cc2c17..849edcae168 100644--- a/apps/server/src/services/worktreeCleanup/index.ts+++ b/apps/server/src/services/worktreeCleanup/index.ts@@ -27,7 +27,7 @@ const log = debug('lobe-server:worktree-cleanup');/*** Automatic cleanup of the worktrees the app created for a conversation- * (Better Coding Experience "New worktree"), mirroring how Claude Desktop+ * ("New worktree"), mirroring how Claude Desktop* tidies a session's worktree when it is archived:** - archiving a topic (status `completed`) or moving it to the recycle bindiff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 4ac9a50480d..2f55577db89 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1837,10 +1837,8 @@"inputQueue.edit": "Edit","inputQueue.enqueueRejected": "Queue is full. Try again after the current run finishes.","inputQueue.queuedHint": "Sends when the current step finishes",- "inputQueue.queuedMergeHint": "Merged and sent when the current step finishes","inputQueue.queuedOneByOneHint": "Sent one at a time after the current run finishes","inputQueue.queuedRunEndHint": "Sends when the current run finishes",- "inputQueue.queuedRunEndMergeHint": "Merged and sent when the current run finishes","inputQueue.sendNow": "Send now (interrupts current run)","inputQueue.sendNowFailed": "Couldn’t interrupt the current run. Try again.","inputQueue.steerDeliveryUnknownHint": "Couldn’t confirm the agent got this. Send it again or delete it",diff --git a/locales/en-US/device.json b/locales/en-US/device.jsonindex 81aa057a593..95818e1f22b 100644--- a/locales/en-US/device.json+++ b/locales/en-US/device.json@@ -94,7 +94,6 @@"workingDirectory.foldersEmpty": "No subfolders. You can select this folder.","workingDirectory.foldersLoadFailed": "Could not load folders. Check the device connection and folder permissions, then retry or enter a path manually.","workingDirectory.foldersLoading": "Loading folders…",- "workingDirectory.ghMissing": "Install and log in to the GitHub CLI (`gh`) to see linked pull requests","workingDirectory.home": "Home folder","workingDirectory.loadMoreFolders": "Load more folders","workingDirectory.lockedWorktree": "locked",@@ -121,7 +120,6 @@"workingDirectory.pathNotDirectory": "This path is not a directory","workingDirectory.pathNotExist": "This path doesn't exist on the device","workingDirectory.placeholder": "Enter directory path, e.g. /Users/name/projects",- "workingDirectory.prTooltipWithExtra": "{{title}} (+{{count}} more open PR on this branch)","workingDirectory.preparingSwitch": "Switching to {{branch}}…","workingDirectory.preparingWorktree": "Creating worktree…","workingDirectory.prunableWorktree": "prunable",diff --git a/locales/en-US/labs.json b/locales/en-US/labs.jsonindex db4c2dcba6c..7a15d2ebd49 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -10,8 +10,6 @@"features.artifactDeployment.title": "Artifact Deployments","features.assistantMessageGroup.desc": "Group agent messages and their tool call results together for display","features.assistantMessageGroup.title": "Agent Message Grouping",- "features.betterCodingExperience.desc": "A set of experiments that improve how agents write, run and review code with you.",- "features.betterCodingExperience.title": "Better Coding Experience","features.claudeCodeSdk.desc": "Run Claude Code sessions through the Claude Agent SDK instead of spawning the CLI. Enables richer streaming and session control.","features.claudeCodeSdk.title": "Claude Code SDK Runtime","features.codexAppServer.desc": "Run Codex through App Server on desktop or a connected device for interactive questions and native turn control. Applies to subsequent runs.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 37d010aefdd..4a8668b04cc 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1837,10 +1837,8 @@"inputQueue.edit": "编辑","inputQueue.enqueueRejected": "队列已满。请在当前运行完成后再试。","inputQueue.queuedHint": "当前步骤完成后发送",- "inputQueue.queuedMergeHint": "当前步骤完成后合并发送","inputQueue.queuedOneByOneHint": "当前运行完成后逐条发送","inputQueue.queuedRunEndHint": "当前运行完成后发送",- "inputQueue.queuedRunEndMergeHint": "当前运行完成后合并发送","inputQueue.sendNow": "立即发送(中断当前运行)","inputQueue.sendNowFailed": "没能中断当前运行,请重试","inputQueue.steerDeliveryUnknownHint": "无法确认助理是否收到。可以重新发送或删除",diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.jsonindex 26906470df4..73d0cf76c40 100644--- a/locales/zh-CN/device.json+++ b/locales/zh-CN/device.json@@ -94,7 +94,6 @@"workingDirectory.foldersEmpty": "没有子文件夹,可以选择当前文件夹。","workingDirectory.foldersLoadFailed": "无法加载文件夹,请检查设备连接和目录权限后重试,或手动输入路径。","workingDirectory.foldersLoading": "正在加载文件夹…",- "workingDirectory.ghMissing": "安装并登录 GitHub CLI(gh)即可显示关联的 Pull Request","workingDirectory.home": "主目录","workingDirectory.loadMoreFolders": "加载更多文件夹","workingDirectory.lockedWorktree": "locked",@@ -121,7 +120,6 @@"workingDirectory.pathNotDirectory": "该路径不是一个目录","workingDirectory.pathNotExist": "该设备上不存在此路径","workingDirectory.placeholder": "输入目录路径,如 /Users/name/projects",- "workingDirectory.prTooltipWithExtra": "{{title}}(此分支还有 {{count}} 个开放 PR)","workingDirectory.preparingSwitch": "正在切换到 {{branch}}…","workingDirectory.preparingWorktree": "正在创建工作树…","workingDirectory.prunableWorktree": "prunable",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex 94f5d402939..d378718cfbf 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -10,8 +10,6 @@"features.artifactDeployment.title": "Artifact 部署","features.assistantMessageGroup.desc": "将代理消息及其工具调用结果组合在一起显示","features.assistantMessageGroup.title": "代理消息分组",- "features.betterCodingExperience.desc": "一组实验功能,改进智能体与你一起写代码、运行和审查代码的体验。",- "features.betterCodingExperience.title": "更好的编码体验","features.claudeCodeSdk.desc": "通过 Claude Agent SDK 运行 Claude Code 会话,替代 CLI 进程方式,提供更丰富的流式输出与会话控制。","features.claudeCodeSdk.title": "Claude Code SDK 运行时","features.codexAppServer.desc": "通过桌面端或已连接设备的 App Server 运行 Codex,支持交互提问与原生回合控制。对后续运行生效。",diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsxindex 4ef2c573ea7..56379a24ad2 100644--- a/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Intervention/AskUserQuestion/index.tsx@@ -119,7 +119,7 @@ const AskUserQuestionIntervention = memo<BuiltinInterventionProps<AskUserQuestioAskUserQuestionIntervention.displayName = 'CCAskUserQuestionIntervention';/**- * A Claude Code permission request (Better Coding Experience) carries a+ * A Claude Code permission request carries a* `claudeCodePermission` detail beside the AskUserQuestion-shaped question:* it gets its own card, which never counts down — Claude Code waits.*/diff --git a/packages/builtin-tool-claude-code/src/client/Intervention/PermissionRequest/index.tsx b/packages/builtin-tool-claude-code/src/client/Intervention/PermissionRequest/index.tsxindex 6686eeb4b4f..998f5d4834c 100644--- a/packages/builtin-tool-claude-code/src/client/Intervention/PermissionRequest/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Intervention/PermissionRequest/index.tsx@@ -55,8 +55,7 @@ const previewOf = (input: Record<string, unknown> | undefined) => {};/**- * Claude Code asking before it acts (Better Coding Experience permission- * modes): a tool it wants to run, entering plan mode, or the plan it wants+ * Claude Code asking before it acts (permission modes): a tool it wants to run, entering plan mode, or the plan it wants* approved. The buttons are Claude Code's own options; a denial or "keep* planning" carries the note the user typed, so Claude knows what to do* instead. Never times out: Claude Code waits until the user answers or stopsdiff --git a/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx b/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsxindex 93e923d4686..251553b2373 100644--- a/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx+++ b/packages/builtin-tool-claude-code/src/client/Render/AskUserQuestion/index.tsx@@ -43,7 +43,7 @@ const AskUserQuestion = memo<AskUserQuestion.displayName = 'CCAskUserQuestion';/**- * Claude Code's permission requests (Better Coding Experience) ride the same+ * Claude Code's permission requests ride the same* AskUserQuestion-shaped card every review surface understands; their extra* `claudeCodePermission` detail gets the dedicated result instead.*/diff --git a/packages/database/src/models/work/githubToolResult.ts b/packages/database/src/models/work/githubToolResult.tsindex b9eda813805..9cff90f35d2 100644--- a/packages/database/src/models/work/githubToolResult.ts+++ b/packages/database/src/models/work/githubToolResult.ts@@ -534,8 +534,7 @@ const parseGhSegment = (segment: string[], lifecycle: boolean): ParsedGhCommand/** Options for the shell-surface gh normalizer; both are off for the github skill. */export interface GithubShellNormalizeOptions {/**- * Also register `gh pr ready <n>` / `gh pr merge <n>` (Better Coding- * Experience): touching a pull request by number ties it to the conversation.+ * Also register `gh pr ready <n>` / `gh pr merge <n>`: touching a pull request by number ties it to the conversation.*/pullRequestLifecycle?: boolean;/**diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.tsindex 20f440c0626..7bf9ab9959a 100644--- a/packages/device-gateway-client/src/types.ts+++ b/packages/device-gateway-client/src/types.ts@@ -350,7 +350,7 @@ export interface AgentRunRequestMessage {*/claudeCodeEntrypoint?: string;/**- * Codex Plan switch (Better Coding Experience lab), forwarded into the same+ * Codex Plan switch, forwarded into the same* envelope. Sent only to a device advertising `codex-collaboration-mode-v1`.*/collaborationMode?: CodexCollaborationMode;@@ -377,7 +377,7 @@ export interface AgentRunRequestMessage {* older deployments safely degrade to a fresh retry without recovery history.*//**- * Claude Code permission mode (Better Coding Experience lab), forwarded into+ * Claude Code permission mode, forwarded into* the `lh hetero exec` input envelope. Absent: every action is allowed.*/permissionMode?: HeteroPermissionMode;diff --git a/packages/heterogeneous-agents/src/claudeCodePermission/args.ts b/packages/heterogeneous-agents/src/claudeCodePermission/args.tsindex 7e532921cc6..85a8b1b0133 100644--- a/packages/heterogeneous-agents/src/claudeCodePermission/args.ts+++ b/packages/heterogeneous-agents/src/claudeCodePermission/args.ts@@ -19,8 +19,8 @@ export const isRunningAsRoot = (): boolean => process.getuid?.() === 0;* Claude Code permission flags for one spawn, shared by every CLI host* (desktop IPC, `lh hetero exec`).*- * - No `mode` (Better Coding Experience lab off): every action is allowed, as- * before — `bypassPermissions`, or `acceptEdits` with the common tools+ * - No `mode` (a host that predates permission modes): every action is+ * allowed — `bypassPermissions`, or `acceptEdits` with the common tools* pre-approved as root. Nothing asks the host.* - With a `mode`: Claude Code asks the host over stdio* (`--permission-prompt-tool stdio`) whenever the mode wants a decision.diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.tsindex 94fe4f5f0fd..930d4aa3a1e 100644--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts@@ -97,7 +97,7 @@ interface ThreadNameSetParams {export interface CodexThreadTurnOptions {askUserBridge?: AskUserBridge;/**- * Codex Plan switch (Better Coding Experience): the collaboration mode every+ * Codex Plan switch: the collaboration mode every* native turn of this run sends. Omitted sends none, exactly as before. Codex* keeps the mode on the thread, so it stays until a turn sends another.*/diff --git a/packages/heterogeneous-agents/src/codexPlanMode/index.ts b/packages/heterogeneous-agents/src/codexPlanMode/index.tsindex ae41b53596c..3337fa2354e 100644--- a/packages/heterogeneous-agents/src/codexPlanMode/index.ts+++ b/packages/heterogeneous-agents/src/codexPlanMode/index.ts@@ -2,7 +2,7 @@ import type { ChatTopicMetadata, CodexCollaborationMode } from '@lobechat/types'import { isCodexCollaborationMode } from '@lobechat/types';/*- * Browser-safe slice of the Codex Plan switch (Better Coding Experience lab):+ * Browser-safe slice of the Codex Plan switch:* the mode report a native Codex run emits and the topic patch it maps to.* The thread logic lives in `codex/CodexThreadSession` (Node only).*/diff --git a/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts b/packages/heterogeneous-agents/src/protocol/execStdinPayload.tsindex cbafb99704c..48e2c000b0e 100644--- a/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts+++ b/packages/heterogeneous-agents/src/protocol/execStdinPayload.ts@@ -35,7 +35,7 @@ export interface HeteroExecImageRef {* resume failed and the CLI is starting the agent from scratch — so it carries* session-scoped context regardless of what the primary attempt got.*- * `permissionMode` (Claude Code, Better Coding Experience lab) rides the same+ * `permissionMode` (Claude Code) rides the same* envelope for the same reason: an `lh` that predates it unwraps `content` and* keeps allowing everything, rather than failing on an unknown flag. The* Codex Plan switch (`collaborationMode`) rides it for the same reason.diff --git a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.tsindex 63105d4c39b..c9daa53920a 100644--- a/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts+++ b/packages/heterogeneous-agents/src/spawn/claudeAgentSdkSession.ts@@ -209,9 +209,9 @@ export interface ClaudeAgentSdkSessionOptions {onStderr: (data: string) => Promise<void> | void;operationId: string;/**- * Better Coding Experience permission mode. With `askUserBridge`, Claude- * Code asks through `canUseTool` and each request raises a card; absent,- * every action is allowed as before the lab.+ * Claude Code permission mode. With `askUserBridge`, Claude Code asks+ * through `canUseTool` and each request raises a card; absent, every action+ * is allowed.*/permissionMode?: HeteroPermissionMode;/**diff --git a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts b/packages/heterogeneous-agents/src/spawn/spawnAgent.tsindex 711e2489623..dbb72a227f7 100644--- a/packages/heterogeneous-agents/src/spawn/spawnAgent.ts+++ b/packages/heterogeneous-agents/src/spawn/spawnAgent.ts@@ -118,10 +118,10 @@ export interface SpawnAgentOptions {operationId: string;/*** (Claude Code `liveInput` with an `askUserBridge`) The permission mode the- * Better Coding Experience lab picked. Claude Code then asks the host before- * acting as the mode requires, the bridge raises a card per request, and the- * mode Claude Code reports is emitted as `step_complete { phase:- * 'permission_mode' }`. Absent: every action is allowed, as before the lab.+ * topic picked. Claude Code then asks the host before acting as the mode+ * requires, the bridge raises a card per request, and the mode Claude Code+ * reports is emitted as `step_complete { phase: 'permission_mode' }`.+ * Absent: every action is allowed.*/permissionMode?: HeteroPermissionMode;/**diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 5115c284b45..9c4f39a16a7 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1135,9 +1135,7 @@ export default {'inputQueue.edit': 'Edit','inputQueue.enqueueRejected': 'Queue is full. Try again after the current run finishes.','inputQueue.queuedHint': 'Sends when the current step finishes',- 'inputQueue.queuedMergeHint': 'Merged and sent when the current step finishes','inputQueue.queuedRunEndHint': 'Sends when the current run finishes',- 'inputQueue.queuedRunEndMergeHint': 'Merged and sent when the current run finishes','inputQueue.queuedOneByOneHint': 'Sent one at a time after the current run finishes','inputQueue.steerDeliveryUnknownHint':'Couldn’t confirm the agent got this. Send it again or delete it',diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.tsindex 875f0fa8fed..d9b04a613b4 100644--- a/packages/locales/src/default/device.ts+++ b/packages/locales/src/default/device.ts@@ -79,8 +79,6 @@ export default {'workingDirectory.filesEmpty': 'No uncommitted changes','workingDirectory.filesLoading': 'Loading changes…','workingDirectory.filesModified': 'Modified',- 'workingDirectory.ghMissing':- 'Install and log in to the GitHub CLI (`gh`) to see linked pull requests','workingDirectory.newBranchPlaceholder': 'feature/new-branch-name','workingDirectory.newWorktreeLocation': 'Will be created at {{path}}','workingDirectory.noMatch': 'No matching directories',@@ -89,7 +87,6 @@ export default {'workingDirectory.pathNotDirectory': 'This path is not a directory','workingDirectory.pathNotExist': "This path doesn't exist on the device",'workingDirectory.placeholder': 'Enter directory path, e.g. /Users/name/projects',- 'workingDirectory.prTooltipWithExtra': '{{title}} (+{{count}} more open PR on this branch)','workingDirectory.topicPullRequestsTooltip':'{{title}} (+{{count}} more linked to this topic — click to see all)','workingDirectory.pullAction': 'Click to pull {{count}} commit(s) from {{upstream}}',@@ -185,7 +182,7 @@ export default {'workingDirectory.drive.drives.personal': 'Personal drive','workingDirectory.drive.rebuildInPersonal':'Private environment folders ({{names}}) are hidden here. Their owners can rebuild them on their personal drives.',- // Better Coding Experience: branch picked for a new topic, switched or forked on send.+ // Branch picked for a new topic, switched or forked on send.'workingDirectory.branchCheckedOutHere': 'Checked out here','workingDirectory.deviceOutdated':'The LobeHub app or lh CLI on this device is too old for this. Update it and try again.',diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex 898f020d6e7..56536449bb9 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -16,9 +16,6 @@ export default {'features.assistantMessageGroup.desc':'Group agent messages and their tool call results together for display','features.assistantMessageGroup.title': 'Agent Message Grouping',- 'features.betterCodingExperience.desc':- 'A set of experiments that improve how agents write, run and review code with you.',- 'features.betterCodingExperience.title': 'Better Coding Experience','features.claudeCodeSdk.desc':'Run Claude Code sessions through the Claude Agent SDK instead of spawning the CLI. Enables richer streaming and session control.','features.claudeCodeSdk.title': 'Claude Code SDK Runtime',diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 3b442919830..e615042d3e8 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -26,12 +26,11 @@ export * from './modelFacts';*/export const initialTopicMetadataSchema = z.object({/**- * Claude Code permission mode the composer chip showed (Better Coding- * Experience); the topic's first dispatched run starts in it.+ * Claude Code permission mode the composer chip showed; the topic's first dispatched run starts in it.*/heteroPermissionMode: z.enum(HETERO_PERMISSION_MODES).optional(),/**- * Codex Plan switch the composer showed (Better Coding Experience); the+ * Codex Plan switch the composer showed; the* topic's first native turn sends `plan` / `default` from it.*/heteroPlanMode: z.boolean().optional(),diff --git a/packages/types/src/device.test.ts b/packages/types/src/device.test.tsindex 6e2661f14b5..9611b84e824 100644--- a/packages/types/src/device.test.ts+++ b/packages/types/src/device.test.ts@@ -239,7 +239,7 @@ describe('deriveWorktreePath', () => {expect(deriveWorktreePath('/code/lobehub', '')).toBe('/code/lobehub');});- // Better Coding Experience names the folder after the branch's own name: the+ // The folder is named after the branch's own name: the// app's `lobehub/` namespace is dropped, every other name folds as before.describe('stripBranchPrefix', () => {const root = () => `/Users/me/.lobehub/worktrees/${key('/code/lobehub')}`;diff --git a/packages/types/src/heteroPermissionMode.ts b/packages/types/src/heteroPermissionMode.tsindex d7f0be86b34..d8d69ffd35c 100644--- a/packages/types/src/heteroPermissionMode.ts+++ b/packages/types/src/heteroPermissionMode.ts@@ -1,6 +1,5 @@/**- * Claude Code permission modes a topic can run in (Better Coding Experience- * lab). Claude Code also has `dontAsk`, which is deliberately not offered.+ * Claude Code permission modes a topic can run in. Claude Code also has `dontAsk`, which is deliberately not offered.** - `default`: ask before every edit and command.* - `acceptEdits`: edits run, commands still ask.diff --git a/packages/types/src/heteroPlanMode.ts b/packages/types/src/heteroPlanMode.tsindex e0a4eaccb17..7ec4d9db7f9 100644--- a/packages/types/src/heteroPlanMode.ts+++ b/packages/types/src/heteroPlanMode.ts@@ -1,7 +1,7 @@import { applyWorktreeModeDir } from './worktreeMode';/**- * Codex collaboration modes the Plan switch (Better Coding Experience lab)+ * Codex collaboration modes the Plan switch* moves a native Codex thread between. Plan is not a permission mode: Codex* keeps allowing every action either way.*/diff --git a/packages/types/src/ownedWorktree.ts b/packages/types/src/ownedWorktree.tsindex 3a67e698dfc..8d6584f8795 100644--- a/packages/types/src/ownedWorktree.ts+++ b/packages/types/src/ownedWorktree.ts@@ -2,8 +2,8 @@ import type { ChatTopicMetadata } from './topic';import type { WorkingDirConfig } from './workingDir';/**- * Worktrees a topic owns: the ones the app created for it (Better Coding- * Experience "New worktree" on the first send). Recorded on the topic's+ * Worktrees a topic owns: the ones the app created for it ("New worktree"+ * on the first send). Recorded on the topic's* metadata as `ownedWorktrees` and never rewritten by a later worktree change* — unlike `workingDirectoryConfig.git.autoCreated`, which is dropped as soon* as the topic moves to another checkout. Retiring the topic (archive ordiff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex f88c796cf69..ffb5120740f 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -257,7 +257,7 @@ export interface ChatTopicMetadata {*/heteroEffort?: HeterogeneousReasoningEffort;/**- * Claude Code permission mode of this topic (Better Coding Experience lab):+ * Claude Code permission mode of this topic:* what its next run starts in, and the mode Claude Code last reported, so a* switch Claude Code made itself (leaving plan mode) sticks.*/@@ -271,7 +271,7 @@ export interface ChatTopicMetadata {*/heteroPermissionModeReportPending?: string | null;/**- * Codex Plan switch of this topic (Better Coding Experience lab). Absent+ * Codex Plan switch of this topic. Absent* until the user first turns it on: such a topic sends no collaboration* mode at all. Once set, every native turn sends `plan` (true) or* `default` (false) explicitly. Codex keeps the mode on the thread, so only@@ -379,7 +379,7 @@ export interface ChatTopicMetadata {/** Measured dominant provider by token volume — see {@link ChatTopicMetadata.model}. */provider?: string;/**- * Better Coding Experience: PR links kept on the topic (found on its own+ * PR links kept on the topic (found on its own* branch, or linked by hand) and the PRs removed from its lists. Server-owned —* written only by the `work.*TopicPullRequest` endpoints, never by a client* metadata patch.diff --git a/packages/types/src/user/preference.test.ts b/packages/types/src/user/preference.test.tsindex c898b905efc..c971652134a 100644--- a/packages/types/src/user/preference.test.ts+++ b/packages/types/src/user/preference.test.ts@@ -27,4 +27,17 @@ describe('UserPreferenceSchema', () => {expect(parsed).toMatchObject({ workspace: { order: ['ws-2', 'ws-1'] } });});++ // Retired lab flags stay in stored preferences (no migration). A stored one+ // must not fail the parse — the display snapshot and `updatePreference` both+ // read the whole object — it is only dropped, with the live flags kept.+ it('drops a retired lab flag without rejecting the preference', () => {+ const result = UserPreferenceSchema.safeParse({+ lab: { enableCodexAppServer: true, enableRetiredExperiment: true },+ telemetry: null,+ });++ expect(result.success).toBe(true);+ expect(result.data?.lab).toEqual({ enableCodexAppServer: true });+ });});diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex ec9e3fb0f29..67b18723610 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -196,11 +196,6 @@ export const UserGuideSchema = z.object({export type UserGuide = z.infer<typeof UserGuideSchema>;export const UserLabSchema = z.object({- /**- * one switch for the experiments that improve how agents write and work with- * code; every coding-experience improvement reads this flag- */- enableBetterCodingExperience: z.boolean().optional(),/*** enable agent identity: give an agent its own mail address*/diff --git a/packages/types/src/user/settings/general.ts b/packages/types/src/user/settings/general.tsindex c5c5bf57498..d539dfcee9f 100644--- a/packages/types/src/user/settings/general.ts+++ b/packages/types/src/user/settings/general.ts@@ -7,20 +7,14 @@ export type AnimationMode = 'disabled' | 'agile' | 'elegant';export type InterfaceDensity = 'compact' | 'loose';/**- * What a message sent while the agent runs does (Better Coding Experience- * lab): `queue` waits for the run to end and sends one message per turn;- * `steer` joins the running turn at a point the agent picks.+ * What a message sent while the agent runs does: `queue` waits for the run to+ * end and sends one message per turn; `steer` joins the running turn at a+ * point the agent picks.*/export type FollowUpBehavior = 'queue' | 'steer';-/** The behavior in effect: `legacy` while the lab is off (the setting is not read). */-export type FollowUpMode = FollowUpBehavior | 'legacy';--/** Resolve the behavior in effect from the lab switch and the stored setting. */-export const resolveFollowUpMode = (- labEnabled: boolean | undefined,- setting: FollowUpBehavior | undefined,-): FollowUpMode => (labEnabled ? (setting ?? 'steer') : 'legacy');+/** The Follow-up behavior of a user who never picked one. */+export const DEFAULT_FOLLOW_UP_BEHAVIOR: FollowUpBehavior = 'steer';export interface UserGeneralConfig {animationMode?: AnimationMode;@@ -54,8 +48,7 @@ export interface UserGeneralConfig {*/expandWorkflowWhileStreaming?: boolean;/**- * Messages sent while the agent runs; read only with the Better Coding- * Experience lab on.+ * Messages sent while the agent runs.* @default 'steer'*/followUpBehavior?: FollowUpBehavior;diff --git a/packages/types/src/work.ts b/packages/types/src/work.tsindex 07ec0a95da1..b8729ea3cb1 100644--- a/packages/types/src/work.ts+++ b/packages/types/src/work.ts@@ -858,7 +858,7 @@ export interface TopicPullRequestsMeta {}/**- * One GitHub pull request linked to a topic (Better Coding Experience): by any+ * One GitHub pull request linked to a topic: by any* `work_versions` row of a `github_pull_request` Work with that `topicId`, or by* a topic link (branch match / by hand). A topic can carry several.*/diff --git a/packages/types/src/workingDir.ts b/packages/types/src/workingDir.tsindex e28db19bd4c..f1bbf931939 100644--- a/packages/types/src/workingDir.ts+++ b/packages/types/src/workingDir.ts@@ -74,7 +74,7 @@ export interface WorkingDirGitState {activeWorktree?: string;/*** True when {@link activeWorktree} was created by the app on the topic's- * first send (Better Coding Experience "New worktree"), not picked by the+ * first send ("New worktree"), not picked by the* user. Such a worktree belongs to this one conversation — the record a* later cleanup keys on. Ownership only: where a CLI session starts is* {@link WorkingDirConfig.sessionPath}, which outlives a later move.@@ -98,7 +98,7 @@ export interface WorkingDirGitState {isWorktree?: boolean;/*** A branch this conversation created — the worktree branch made on its first- * send (Better Coding Experience), or one its agent created+ * send, or one its agent created* (`git switch -c`, `git worktree add -b`). Only while the topic is on it does* the run end ask GitHub which PR the branch has: another branch may carry* someone else's PR.diff --git a/packages/types/src/worktreeMode.ts b/packages/types/src/worktreeMode.tsindex 2bc4bcaf292..ada17dc99a0 100644--- a/packages/types/src/worktreeMode.ts+++ b/packages/types/src/worktreeMode.ts@@ -1,5 +1,5 @@/**- * The per-directory "New worktree" switch of the Better Coding Experience lab.+ * The per-directory "New worktree" switch of the composer.** Remembered per workspace + user (the preference bucket it is stored in) and* per device + directory (the key). Deliberately NOT on the device's shareddiff --git a/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsxindex fd4e6709e8b..6fcdfdf45dc 100644--- a/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx@@ -3,17 +3,10 @@*/import type { ChatTopicMetadata } from '@lobechat/types';import { render, screen } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import MetaHoverCard from './MetaHoverCard';-const fetchTopicLinkedPullRequestMock = vi.hoisted(() => vi.fn());--vi.mock('@/store/chat', () => ({- useChatStore: (selector: (state: unknown) => unknown) =>- selector({ useFetchTopicLinkedPullRequest: fetchTopicLinkedPullRequestMock }),-}));-vi.mock('react-i18next', () => ({useTranslation: () => ({t: (key: string, values?: Record<string, string>) =>@@ -23,60 +16,15 @@ vi.mock('react-i18next', () => ({vi.mock('@/const/version', () => ({ isDesktop: false }));-const labMock = vi.hoisted(() => ({ betterCoding: false }));-vi.mock('@/store/user', () => ({- useUserStore: (selector: (state: unknown) => unknown) => selector({}),-}));-vi.mock('@/store/user/selectors', () => ({- labPreferSelectors: { enableBetterCodingExperience: () => labMock.betterCoding },-}));-vi.mock('@/features/ChatInput/ControlBar/DirIcon', () => ({default: ({ size }: { size?: number }) => <span data-size={size} data-testid="dir-icon" />,}));-afterEach(() => {- vi.clearAllMocks();- labMock.betterCoding = false;-});-describe('MetaHoverCard', () => {- it('re-fetches the linked PR state on mount (popover open) for the hovered topic', () => {- const metadata: ChatTopicMetadata = {- workingDirectory: '/repo',- workingDirectoryConfig: {- git: {- branch: 'fix/cold-hydration-cache-inject',- github: {- pullRequest: {- number: 17_392,- state: 'open',- title: 'keep the hydration gate up',- url: 'https://github.com/lobehub/lobehub/pull/17392',- },- pullRequestStatus: 'ok',- },- },- path: '/repo',- repoType: 'github',- },- };-- render(<MetaHoverCard metadata={metadata} title="Topic" topicId="topic-1" />);-- // The card mounts only while the hover popover is open, so wiring the SWR- // hook to the topic id is what turns "open the card" into a PR refresh —- // background topics otherwise keep their last persisted snapshot forever.- expect(fetchTopicLinkedPullRequestMock).toHaveBeenCalledWith('topic-1', metadata);- });-- it('still mounts the refresh hook when the topic has no git context', () => {+ it('renders nothing when the topic has no git context', () => {const { container } = render(<MetaHoverCard metadata={undefined} title="Topic" />);- // No git context → nothing renders, but the hook is still called- // unconditionally (rules of hooks); it no-ops via a null SWR key.expect(container).toBeEmptyDOMElement();- expect(fetchTopicLinkedPullRequestMock).toHaveBeenCalledWith(undefined, undefined);});it('shows persisted git context without the branch explanation note', () => {@@ -98,63 +46,4 @@ describe('MetaHoverCard', () => {expect(screen.getByText('repo-fix')).toBeInTheDocument();expect(screen.queryByText('metaCard.branchNote')).not.toBeInTheDocument();});-- it('renders the PR number ahead of the title so the ellipsis never eats it', () => {- const metadata: ChatTopicMetadata = {- workingDirectory: '/repo',- workingDirectoryConfig: {- git: {- branch: 'perf/active-scope-key',- github: {- pullRequest: {- ciStatus: 'success',- mergedAt: '2026-07-09T00:00:00.000Z',- number: 16_951,- state: 'closed',- title: 'perf(swr): persist activeScopeKey',- url: 'https://github.com/lobehub/lobehub/pull/16951',- },- },- },- path: '/repo',- repoType: 'git',- },- };-- render(<MetaHoverCard metadata={metadata} title="Topic" />);-- const link = screen.getByRole('link');- expect(link).toHaveAttribute('href', 'https://github.com/lobehub/lobehub/pull/16951');- expect(link).toHaveTextContent('metaCard.pr.merged · #16951 perf(swr): persist activeScopeKey');- expect(screen.getByTitle('#16951 perf(swr): persist activeScopeKey')).toBeInTheDocument();- });-- it('hides the branch-guessed PR under Better Coding Experience', () => {- const metadata: ChatTopicMetadata = {- workingDirectory: '/repo',- workingDirectoryConfig: {- git: {- branch: 'feat/x',- github: {- pullRequest: {- number: 42,- state: 'open',- title: 'guessed PR',- url: 'https://github.com/lobehub/lobehub/pull/42',- },- },- },- path: '/repo',- repoType: 'github',- },- };-- const { rerender } = render(<MetaHoverCard metadata={metadata} title="Topic" />);- expect(screen.getByText(/guessed PR/)).toBeInTheDocument();-- labMock.betterCoding = true;- rerender(<MetaHoverCard metadata={metadata} title="Topic 2" />);- expect(screen.queryByText(/guessed PR/)).not.toBeInTheDocument();- expect(screen.getByText('feat/x')).toBeInTheDocument();- });});diff --git a/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsx b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsxindex 1a1dc18a553..9fa8284ab6d 100644--- a/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.tsx@@ -7,17 +7,9 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import DirIcon from '@/features/ChatInput/ControlBar/DirIcon';-import { useChatStore } from '@/store/chat';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';import { densityVars } from '@/styles/densityVars';-import {- getCiVisual,- getPullRequestState,- getTopicMetaCard,- PR_STATE_VISUAL,-} from './metaCardData';+import { getTopicMetaCard } from './metaCardData';const styles = createStaticStyles(({ css }) => ({card: css`@@ -70,41 +62,17 @@ const styles = createStaticStyles(({ css }) => ({text-overflow: ellipsis;white-space: nowrap;`,- prLink: css`- cursor: pointer;-- margin-inline: -6px;- padding-block: 2px;- padding-inline: 6px;- border-radius: 6px;-- color: inherit;- text-decoration: none;-- /* antd's global a:hover outranks the color:inherit above, so without this the- row would turn link-blue; hovering should read as emphasis instead. */- &:hover {- color: ${cssVar.colorText};- background: ${cssVar.colorFillTertiary};- }- `,}));interface DetailRowProps {children: ReactNode;icon: typeof Clock;- iconColor?: string;title?: string;}-const DetailRow = memo<DetailRowProps>(({ icon, iconColor, title, children }) => (+const DetailRow = memo<DetailRowProps>(({ icon, title, children }) => (<div className={styles.row}>- <Icon- className={styles.rowIcon}- icon={icon}- size={15}- style={iconColor ? { color: iconColor } : undefined}- />+ <Icon className={styles.rowIcon} icon={icon} size={15} /><span className={styles.rowText} title={title}>{children}</span>@@ -117,31 +85,19 @@ interface MetaHoverCardProps {metadata: ChatTopicMetadata | undefined;time?: ReactNode;title: string;- /** Enables the open-time PR/CI refresh below; without it the card is a pure snapshot reader. */- topicId?: string;}/*** Codex-style hover detail card for a topic row: surfaces the persisted repo /- * branch / worktree / linked-PR / CI context on the right of the sidebar without- * cluttering the row itself.+ * branch / worktree context on the right of the sidebar without cluttering the+ * row itself.*/-const MetaHoverCard = memo<MetaHoverCardProps>(({ metadata, title, time, topicId }) => {+const MetaHoverCard = memo<MetaHoverCardProps>(({ metadata, title, time }) => {const { t } = useTranslation('topic');- // The card only mounts while the popover is open, so hosting the linked-PR- // SWR hook here re-fetches the persisted PR/CI snapshot exactly when the- // user is looking at it (the hook dedupes to once a minute per PR).- // ChatHydration runs the same hook for the active topic only — without this,- // a background topic's badge stays frozen on whatever was last persisted.- const useFetchTopicLinkedPullRequest = useChatStore((s) => s.useFetchTopicLinkedPullRequest);- useFetchTopicLinkedPullRequest(topicId, metadata);-- const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);- const card = getTopicMetaCard(metadata, { hideRecordedPullRequest: betterCoding });+ const card = getTopicMetaCard(metadata);if (!card) return null;- const { repoName, repoType, branch, detached, worktreeName, pullRequest } = card;- const ci = pullRequest ? getCiVisual(pullRequest.ciStatus) : undefined;+ const { repoName, repoType, branch, detached, worktreeName } = card;return (<div className={styles.card}>@@ -170,56 +126,6 @@ const MetaHoverCard = memo<MetaHoverCardProps>(({ metadata, title, time, topicId{worktreeName}</DetailRow>)}-- {pullRequest &&- (() => {- const prState = getPullRequestState(pullRequest);- const prVisual = PR_STATE_VISUAL[prState];- const prTitleAttr = pullRequest.title- ? `#${pullRequest.number} ${pullRequest.title}`- : `#${pullRequest.number}`;- const prInner = (- <>- <Icon- className={styles.rowIcon}- icon={prVisual.icon}- size={15}- style={{ color: prVisual.color }}- />- <span className={styles.rowText} title={prTitleAttr}>- <span style={{ color: prVisual.color, fontWeight: 500 }}>- {t(prVisual.labelKey)}- </span>- {/* The number leads the title: it is the stable identifier, and a- long title would otherwise push it past the ellipsis. */}- <span- style={{ color: cssVar.colorTextTertiary }}- >{` · #${pullRequest.number}`}</span>- {pullRequest.title ? ` ${pullRequest.title}` : ''}- </span>- </>- );- // Clickable when a url is persisted — opens the PR on GitHub in the- // system browser; older snapshots without a url stay a plain row.- return pullRequest.url ? (- <a- className={`${styles.row} ${styles.prLink}`}- href={pullRequest.url}- rel={'noreferrer'}- target={'_blank'}- >- {prInner}- </a>- ) : (- <div className={styles.row}>{prInner}</div>- );- })()}-- {ci && (- <DetailRow icon={ci.icon} iconColor={ci.color}>- {t(ci.labelKey)}- </DetailRow>- )}</div>);});diff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsxindex ada663bef41..9b06b15c379 100644--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx@@ -28,15 +28,7 @@ const electronTabMocks = vi.hoisted(() => ({addTab: vi.fn(),}));const topicMetaCardMock = vi.hoisted(() => ({- value: undefined as- | {- pullRequest?: {- ciStatus?: 'failure' | 'pending' | 'success' | 'unknown';- mergedAt?: string;- state: string;- };- }- | undefined,+ value: undefined as { branch?: string } | undefined,}));// Assertions key on the raw lucide displayName, which the real Icon does not@@ -147,9 +139,6 @@ vi.mock('@/store/user', () => ({useUserStore: (selector: (state: unknown) => unknown) => selector({}),}));vi.mock('@/store/user/selectors', () => ({- labPreferSelectors: {- enableBetterCodingExperience: () => false,- },userProfileSelectors: { userId: () => currentUserIdMock.value },}));vi.mock('@/hooks/useTopicOnlyMine', () => ({ useTopicOnlyMine: () => onlyMineMock.value }));@@ -197,18 +186,9 @@ vi.mock('./MetaHoverCard', () => ({}));vi.mock('./metaCardData', async (importOriginal) => {const actual = await importOriginal<typeof MetaCardData>();- const CiIcon = () => null;- CiIcon.displayName = 'CiIcon';- const PullRequestIcon = () => null;- PullRequestIcon.displayName = 'PullRequestIcon';return {...actual,- PR_STATE_VISUAL: {- ...actual.PR_STATE_VISUAL,- open: { color: '#0a0', icon: PullRequestIcon, labelKey: 'metaCard.pr.open' },- },- getCiVisual: () => ({ color: '#fa0', icon: CiIcon, labelKey: 'metaCard.ci.pending' }),// Defaults to undefined so TopicItem skips the hover Popover wrapper in tests.getTopicMetaCard: () => topicMetaCardMock.value,};@@ -560,17 +540,6 @@ describe('TopicItem active state', () => {});});- // The unread dot and the linked-PR marker compete for the same icon slot, and- // unread is one of the three `pending` attention states, so it has to win.- it('keeps the unread dot visible when the topic has a linked pull request', () => {- topicUnreadCompletedMock.value = true;- topicMetaCardMock.value = { pullRequest: { state: 'open' } };-- render(<TopicItem id="tpc_test" title="Topic" />);-- expect(screen.getByTestId('topic-unread-dot')).toBeInTheDocument();- });-/** @example A project row is not in the chat store, so only its own status says unread. */it('shows the unread dot for a project row whose own status is unread', () => {scopedTopicMock.value = { agentId: 'other-agent', agentName: 'Other Agent' };@@ -584,26 +553,11 @@ describe('TopicItem active state', () => {expect(screen.getByTestId('topic-unread-dot')).toBeInTheDocument();});- it('shows the pull request marker once the topic is no longer unread', () => {- topicMetaCardMock.value = { pullRequest: { state: 'open' } };-- render(<TopicItem id="tpc_test" title="Topic" />);-- expect(screen.queryByTestId('topic-unread-dot')).not.toBeInTheDocument();- expect(screen.getByTestId('topic-item-icon')).toBeInTheDocument();- });-describe('goal marker', () => {- it('marks a topic that has a goal, ahead of its pull request', () => {- topicMetaCardMock.value = { pullRequest: { state: 'open' } };-+ it('marks a topic that has a goal', () => {render(<TopicItem hasGoal id="tpc_test" title="Topic" />);expect(screen.getByLabelText('metaCard.goal')).toBeInTheDocument();- expect(screen.getByTestId('topic-item-icon')).not.toHaveAttribute(- 'data-icon',- 'PullRequestIcon',- );});it('keeps the execution status ahead of the goal marker', () => {@@ -612,46 +566,6 @@ describe('TopicItem active state', () => {expect(screen.queryByLabelText('metaCard.goal')).not.toBeInTheDocument();});});-- it('adds the CI status to the pull request marker', () => {- topicMetaCardMock.value = { pullRequest: { ciStatus: 'pending', state: 'open' } };-- render(<TopicItem id="tpc_test" title="Topic" />);-- expect(screen.getAllByTestId('topic-item-icon').map((icon) => icon.dataset.icon)).toEqual([- 'PullRequestIcon',- 'CiIcon',- ]);- });-- it.each([{ state: 'merged' }, { mergedAt: '2026-11-05T03:58:11Z', state: 'closed' }])(- 'uses the merged PR icon as the avatar badge for %o regardless of CI',- (pullRequest) => {- for (const ciStatus of ['pending', 'failure', 'success'] as const) {- topicMetaCardMock.value = { pullRequest: { ...pullRequest, ciStatus } };-- const { unmount } = render(<TopicItem id="tpc_test" title="Topic" userId="user-2" />);-- expect(- within(screen.getByTestId('creator-avatar'))- .getAllByTestId('topic-item-icon')- .map((icon) => icon.dataset.icon),- ).toEqual(['GitMerge']);- unmount();- }- },- );-- it.each([- ['scheduled', 'Clock'],- ['completed', 'CircleCheck'],- ] as const)('keeps the %s status above linked pull request metadata', (status, icon) => {- topicMetaCardMock.value = { pullRequest: { state: 'open' } };-- render(<TopicItem id="tpc_test" status={status} title="Topic" />);-- expect(screen.getByTestId('topic-item-icon')).toHaveAttribute('data-icon', icon);- });});// The mobile surface has no working sidebar (the desktop host of a topic'sdiff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsxindex 488f217a0a9..56c121a4bcf 100644--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx@@ -48,7 +48,7 @@ import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useUserStore } from '@/store/user';-import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';+import { userProfileSelectors } from '@/store/user/selectors';import { useTopicHoverPrefetch } from '../../hooks/topicHoverPrefetch/useTopicHoverPrefetch';import { markSidebarTopicActivation } from '../../hooks/useScrollActiveTopicIntoView';@@ -58,12 +58,7 @@ import { useTopicListScope } from '../../TopicListScope';import { useScopedTopic } from '../../useScopedTopics';import Actions from './Actions';import TopicItemContextMenu from './ContextMenu';-import {- getCiVisual,- getPullRequestState,- getTopicMetaCard,- PR_STATE_VISUAL,-} from './metaCardData';+import { getTopicMetaCard } from './metaCardData';import MetaHoverCard from './MetaHoverCard';// Base UI Popover plays an opacity/scale enter+exit transition driven by these@@ -80,32 +75,6 @@ const META_HOVER_CARD_STYLES = {};const styles = createStaticStyles(({ css }) => ({- ciBadge: css`- position: absolute;- inset-block-end: -3px;- inset-inline-end: -3px;-- display: flex;- align-items: center;- justify-content: center;-- width: 10px;- height: 10px;- border-radius: 50%;-- line-height: 0;-- background: ${cssVar.colorBgContainer};- `,- ciPending: css`- animation: ci-spin 1s linear infinite;-- @keyframes ci-spin {- to {- transform: rotate(360deg);- }- }- `,markerIcon: css`position: relative;display: inline-flex;@@ -421,11 +390,7 @@ const TopicItemRow = memo<TopicItemRowProps>(// Codex-style hover detail card: when the topic carries git context, hovering// the row reveals a card on the right with repo / branch / worktree / PR / CI —// keeping the row itself clean.- const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);- const metaCard = useMemo(- () => getTopicMetaCard(metadata, { hideRecordedPullRequest: betterCoding }),- [betterCoding, metadata],- );+ const metaCard = useMemo(() => getTopicMetaCard(metadata), [metadata]);// For default topic (no id)if (!id) {@@ -538,37 +503,6 @@ const TopicItemRow = memo<TopicItemRowProps>(</Tooltip>);}- // GitHub PR state marker (open=green, merged=purple, closed=red),- // like Codex. It is secondary metadata, so only an idle topic uses it- // as the leading icon.- if (metaCard?.pullRequest) {- const prState = getPullRequestState(metaCard.pullRequest);- const prVisual = PR_STATE_VISUAL[prState];- const ciStatus = metaCard.pullRequest.ciStatus;- const ciVisual = getCiVisual(ciStatus);- const showCiBadge =- prState !== 'merged' && ciStatus !== undefined && ciStatus !== 'unknown';- const tooltip = showCiBadge- ? `${t(prVisual.labelKey)} · ${t(ciVisual.labelKey)}`- : t(prVisual.labelKey);- return (- <Tooltip title={tooltip}>- <span className={styles.markerIcon}>- <Icon icon={prVisual.icon} size={'small'} style={{ color: prVisual.color }} />- {showCiBadge && (- <span className={styles.ciBadge}>- <Icon- className={ciStatus === 'pending' ? styles.ciPending : undefined}- icon={ciVisual.icon}- size={9}- style={{ color: ciVisual.color }}- />- </span>- )}- </span>- </Tooltip>- );- }if (metadata?.bot?.platform) {const ProviderIcon = getPlatformIcon(metadata.bot!.platform);if (ProviderIcon) {@@ -582,7 +516,7 @@ const TopicItemRow = memo<TopicItemRowProps>(// Workspace mode (creator resolvable): the creator's round avatar is the// primary visual and always leads the row; the row's own icon — execution- // status first, then identity icons (Discord / WeChat / PR marker) —+ // status first, then identity icons (Discord / WeChat) —// shrinks into a bottom-right corner badge. Personal mode keeps the// original layout untouched.const ownIconNode = statusIconNode ?? identityIconNode;@@ -669,7 +603,7 @@ const TopicItemRow = memo<TopicItemRowProps>({metaCard ? (<Popoverarrow={false}- content={<MetaHoverCard metadata={metadata} title={title} topicId={id} />}+ content={<MetaHoverCard metadata={metadata} title={title} />}mouseEnterDelay={0.8}placement={'right'}styles={META_HOVER_CARD_STYLES}diff --git a/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts b/src/features/AgentSidebar/Topic/List/Item/metaCardData.tsindex 0497fe0ce45..9829799f8ad 100644--- a/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts+++ b/src/features/AgentSidebar/Topic/List/Item/metaCardData.ts@@ -80,18 +80,12 @@ export const getCiVisual = (status?: DeviceGitPullRequestCiStatus): CiVisual =>};/**- * Read the git / worktree / linked-PR context off a topic's persisted+ * Read the git / worktree context off a topic's persisted* `workingDirectoryConfig`. Returns `undefined` when the topic carries no git- * context, so the caller can skip the hover card entirely (no probe).+ * context, so the caller can skip the hover card entirely (no probe). A topic's+ * PRs come from its Work rows, not from this snapshot.*/-export const getTopicMetaCard = (- metadata: ChatTopicMetadata | undefined,- /**- * Better Coding Experience: the recorded PR is a branch guess, which the lab- * no longer shows — a topic's PRs come from its Work rows instead.- */- options: { hideRecordedPullRequest?: boolean } = {},-) => {+export const getTopicMetaCard = (metadata: ChatTopicMetadata | undefined) => {const config = metadata?.workingDirectoryConfig;const git = config?.git;if (!git) return undefined;@@ -103,9 +97,6 @@ export const getTopicMetaCard = (return {branch: git.branch,detached: git.detached,- pullRequest: options.hideRecordedPullRequest- ? undefined- : (git.github?.pullRequest ?? undefined),repoName: sourcePath ? getWorkingDirectoryName(sourcePath) : undefined,repoType: getConfigRepoType(config),worktreeName: isWorktree && effectivePath ? getWorkingDirectoryName(effectivePath) : undefined,diff --git a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx b/src/features/ChatInput/ControlBar/BranchSwitcher.tsxindex a6f1b0f2377..a4b233e584c 100644--- a/src/features/ChatInput/ControlBar/BranchSwitcher.tsx+++ b/src/features/ChatInput/ControlBar/BranchSwitcher.tsx@@ -197,7 +197,7 @@ interface BranchSwitcherProps {/** Dropdown placement — the runtime bar opens upward, embedding panels open downward. */placement?: 'topLeft' | 'bottomLeft' | 'bottomRight';/**- * Pick-only mode (Better Coding Experience, before a topic's first send): a+ * Pick-only mode (before a topic's first send): a* click records `onSelect` instead of checking out — the send switches, or* forks a worktree — and the create / rename / delete actions and the* footer are gone. A branch another worktree holds is pickable too; the senddiff --git a/src/features/ChatInput/ControlBar/DraftGit/draftGitStore.ts b/src/features/ChatInput/ControlBar/DraftGit/draftGitStore.tsindex 129cecef3c4..3b2f242a5de 100644--- a/src/features/ChatInput/ControlBar/DraftGit/draftGitStore.ts+++ b/src/features/ChatInput/ControlBar/DraftGit/draftGitStore.ts@@ -24,8 +24,7 @@ export interface DraftGitTarget {}/**- * Before the first send, picking a branch only records it (Better Coding- * Experience): the checkout or worktree happens when the message is sent. The+ * Before the first send, picking a branch only records it: the checkout or worktree happens when the message is sent. The* pick lives here, per agent + device + directory, so it survives the switcher* closing but not a reload — it is a draft, never persisted.*/diff --git a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.tsindex 232b14fad9a..ece77a7033d 100644--- a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts+++ b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts@@ -77,14 +77,6 @@ const prompts = (): DraftGitSendPrompts & { [K in keyof DraftGitSendPrompts]: anshowProgress: vi.fn(() => () => {}),});-const setLab = (on: boolean) =>- useUserStore.setState({- preference: {- ...useUserStore.getState().preference,- lab: { enableBetterCodingExperience: on },- },- } as any);-const setWorktreeMode = (on: boolean) =>useUserStore.setState({preference: {@@ -101,7 +93,6 @@ beforeEach(() => {useDraftGitStore.setState({ selections: {}, targets: {} });useGitStatusStore.setState({ gitAheadBehindMap: {} });registerDraftGitTarget(target);- setLab(true);setWorktreeMode(false);vi.mocked(gitService.getGitBranch).mockResolvedValue({ branch: 'main' });vi.mocked(gitService.listGitWorktrees).mockResolvedValue([@@ -129,13 +120,6 @@ beforeEach(() => {});describe('prepareDraftGitSend — nothing to do', () => {- it('passes without touching git when the lab is off', async () => {- setLab(false);- pick('feat');- expect(await prepareDraftGitSend(context, { prompts: prompts(), t })).toEqual({ ok: true });- expect(gitService.getGitBranch).not.toHaveBeenCalled();- });-it('passes for an existing topic', async () => {pick('feat');const result = await prepareDraftGitSend(diff --git a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.tsindex 543e3323a1e..aa9aae9f2e1 100644--- a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts+++ b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts@@ -13,8 +13,6 @@ import { gitStatusKey } from '@/store/device/gitStatus/projection';import { getGitStatusStoreState } from '@/store/device/gitStatus/store';import { getElectronStoreState } from '@/store/electron';import { desktopStateSelectors } from '@/store/electron/selectors';-import { getUserStoreState } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';import { findWorktreeForBranch, getPathName } from '../worktreeHelpers';import {@@ -64,14 +62,13 @@ const PASS: DraftGitSendResult = { ok: true };const STOP: DraftGitSendResult = { ok: false };/**- * The directory the send acts on, when it should act at all: the lab is on and- * the send starts a new topic in an agent's composer that shows a git directory.+ * The directory the send acts on, when it should act at all: the send starts a+ * new topic in an agent's composer that shows a git directory.*/export const resolveDraftGitTarget = (context: Pick<ConversationContext, 'agentId' | 'groupId' | 'threadId' | 'topicId'>,editorData?: Record<string, any>,): DraftGitTarget | undefined => {- if (!labPreferSelectors.enableBetterCodingExperience(getUserStoreState())) return;if (context.topicId || context.groupId || context.threadId || !context.agentId) return;// A message that starts with a single `@Agent` runs that agent, on its own// device and directory: the composer's directory is not where it runs.diff --git a/src/features/ChatInput/ControlBar/GitStatus.tsx b/src/features/ChatInput/ControlBar/GitStatus.tsxindex f05c1818072..1cd60df27f5 100644--- a/src/features/ChatInput/ControlBar/GitStatus.tsx+++ b/src/features/ChatInput/ControlBar/GitStatus.tsx@@ -2,7 +2,7 @@ import type { WorkingDirGitState } from '@lobechat/types';import { Icon, toast, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { ArrowDownIcon, ArrowUpIcon, GitPullRequest, TriangleAlertIcon } from 'lucide-react';+import { ArrowDownIcon, ArrowUpIcon, TriangleAlertIcon } from 'lucide-react';import { memo, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -14,15 +14,11 @@ import {useFetchGitAheadBehind,useFetchGitBranch,useFetchGitDiffStats,- useFetchGitLinkedPR,useFetchGitWorktrees,useReviewPatches,} from '@/store/device';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';-import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';import BranchSwitcher from './BranchSwitcher';import { describeGitFailure } from './DraftGit/gitErrors';@@ -31,7 +27,6 @@ import { WorktreeToggle } from './DraftGit/WorktreeToggle';import { gitChipStyles } from './gitChipStyles';import StaleGitSnapshot from './StaleGitSnapshot';import TopicPullRequestChip from './TopicPullRequestChip';-import WorktreeSwitcher from './WorktreeSwitcher';const styles = stylex.create({aheadBehindStat: {@@ -51,7 +46,7 @@ const styles = stylex.create({textOverflow: 'ellipsis',whiteSpace: 'nowrap',},- // An existing topic's branch under Better Coding Experience: a label, not a control.+ // An existing topic's branch: a label, not a control.branchStatic: {cursor: 'default',backgroundColor: { 'default': null, ':hover': 'transparent' },@@ -100,10 +95,10 @@ interface GitStatusProps {/*** Git context persisted on the topic. Stands in for the live probe in two* cases: while the probe is still pending (no cached branch yet), it paints a- * read-only branch / PR chip so the cluster doesn't pop in once the read lands;+ * read-only branch chip so the cluster doesn't pop in once the read lands;* and when the probe finds no branch at `path` — which happens whenever the* recorded worktree directory has since been deleted — it keeps the branch /- * worktree / PR chips visible (read-only) instead of collapsing the whole+ * worktree chips visible (read-only) instead of collapsing the whole* cluster, so the bar agrees with the topic's meta hover card, which reads* this same snapshot and never probes.*/@@ -120,8 +115,6 @@ const GitStatus = memo<GitStatusProps>(const { t } = useTranslation('device');// Transport (Electron IPC vs device RPC) is decided inside the service; the// component just reads, identically for local and remote.- // Branch (cheap, refreshes promptly on dir switch) and the linked-PR lookup- // (expensive `gh` call, throttled) are deliberately separate cache entries.const {data: branchData,error: branchError,@@ -174,11 +167,10 @@ const GitStatus = memo<GitStatusProps>(!sourceWorktrees.some((worktree) => worktree.path === path && !worktree.prunable);const isStale =probeFoundNothing && (!!fallbackGit?.branch || (!!recordedWorktree && recordedWorktreeGone));- // Better Coding Experience: before a topic's first send the branch is only- // picked (the send switches or forks a worktree); an existing topic's- // branch is shown but no longer switched from here.- const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);- const isDraft = betterCoding && !topicId;+ // Before a topic's first send the branch is only picked (the send switches+ // or forks a worktree); an existing topic's branch is shown but not+ // switched from here.+ const isDraft = !topicId;const draft = useDraftBranch({agentId,currentBranch: detached ? undefined : branch,@@ -189,19 +181,11 @@ const GitStatus = memo<GitStatusProps>(sourcePath: sourcePath ?? path,});// The picked branch when it is not HEAD's: counts, pull and push follow it.- // When it is HEAD's they read HEAD, exactly as without the lab.+ // When it is HEAD's they read HEAD.const syncBranch =isDraft && draft.selectedBranch && draft.selectedBranch !== branch? draft.selectedBranch: undefined;- // Under the lab a topic's PRs come from its Work rows (TopicPullRequestChip):- // the branch → PR guess is not asked at all.- const { data: prData, mutate: mutatePR } = useFetchGitLinkedPR(- deviceId,- path,- syncBranch ?? branch,- isGithub && !betterCoding,- );// The remaining reads are all disabled once the directory is gone: nothing// below renders from them in that state, and the diff poll alone would keep// shelling out to git every 10s — one RPC round-trip per tick on a remote@@ -238,25 +222,6 @@ const GitStatus = memo<GitStatusProps>(const showRightPanel = useGlobalStore(systemStatusSelectors.showRightPanel);const workingSidebarTab = useGlobalStore((s) => s.status.workingSidebarTab);- // Until the linked-PR lookup answers for this branch, reuse the PR the topic- // recorded for the same branch so the PR chip doesn't pop in late.- const pullRequest = betterCoding- ? undefined- : prData !== undefined- ? prData.pullRequest- : isGithub &&- !syncBranch &&- (!branch || branch === fallbackGit?.branch) &&- fallbackGit?.github?.pullRequest- ? fallbackGit.github.pullRequest- : undefined;-- const handleOpenPr = useCallback(() => {- if (pullRequest?.url) {- openTrustedExternalUrl(pullRequest.url);- }- }, [pullRequest?.url]);-const handleToggleReview = useCallback(() => {if (showRightPanel && workingSidebarTab === 'review') {toggleRightPanel(false);@@ -268,23 +233,11 @@ const GitStatus = memo<GitStatusProps>(const refreshAfterSync = useCallback(async () => {await Promise.all([mutateBranch(),- mutatePR(),mutateReviewPatches(),mutateAheadBehind(),mutateWorktrees(),]);- }, [mutateBranch, mutatePR, mutateReviewPatches, mutateAheadBehind, mutateWorktrees]);-- // Flip the displayed branch instantly on checkout. No revalidate here — the- // switcher's onAfterCheckout reconciles once the checkout lands. The linked-PR- // hook is keyed by branch, so it re-keys to the new branch on its own (its- // cache starts empty there, hiding the stale PR until the lookup resolves).- const handleOptimisticCheckout = useCallback(- (nextBranch: string) => {- void mutateBranch({ branch: nextBranch, detached: false }, { revalidate: false });- },- [mutateBranch],- );+ }, [mutateBranch, mutateReviewPatches, mutateAheadBehind, mutateWorktrees]);const syncBusy = pulling || pushing;// Stale-first paints the last branch and its counts immediately, but@@ -372,13 +325,12 @@ const GitStatus = memo<GitStatusProps>(reviewPatches !== undefined ? liveDiffStats : (cachedDiffStats ?? liveDiffStats);const hasChanges = diffStats.files > 0;- // Better Coding Experience: the topic's linked PRs are server records, so- // they stay in the bar (with their last known state) even when the working- // directory cannot be read — an offline device, a deleted worktree.- const topicPullRequestChip =- betterCoding && topicId ? (- <TopicPullRequestChip deviceId={deviceId} path={path} topicId={topicId} />- ) : null;+ // The topic's linked PRs are server records, so they stay in the bar (with+ // their last known state) even when the working directory cannot be read —+ // an offline device, a deleted worktree.+ const topicPullRequestChip = topicId ? (+ <TopicPullRequestChip deviceId={deviceId} path={path} topicId={topicId} />+ ) : null;// Dead directory: the whole live cluster is unreachable, so hand off to the// snapshot renderer — it shows what the topic recorded and offers the one@@ -388,7 +340,7 @@ const GitStatus = memo<GitStatusProps>(<><StaleGitSnapshotagentId={agentId}- git={betterCoding ? { ...fallbackGit!, github: undefined } : fallbackGit!}+ git={fallbackGit!}isGithub={isGithub}path={path}sourcePath={sourcePath}@@ -400,7 +352,7 @@ const GitStatus = memo<GitStatusProps>(}if (!branch) {- // Probe still pending: paint the topic's recorded branch / PR read-only+ // Probe still pending: paint the topic's recorded branch read-only// (not the dead-directory snapshot — nothing is known to be gone yet).if (!probeSettled && fallbackGit?.branch) {return (@@ -411,21 +363,6 @@ const GitStatus = memo<GitStatusProps>(<span {...stylex.props(styles.branchLabel)}>{fallbackGit.branch}</span></div></div>- {pullRequest && (- <>- <div {...stylex.props(gitChipStyles.separator)} />- <Tooltip title={pullRequest.title}>- <div- {...stylex.props(gitChipStyles.prTrigger)}- role="button"- onClick={handleOpenPr}- >- <Icon icon={GitPullRequest} size={12} />- <span>#{pullRequest.number}</span>- </div>- </Tooltip>- </>- )}{topicPullRequestChip}</>);@@ -435,17 +372,6 @@ const GitStatus = memo<GitStatusProps>(const branchTooltip = detached ? t('workingDirectory.detachedHead', { sha: branch }) : branch;- const prTooltip = pullRequest- ? prData?.extraCount- ? t('workingDirectory.prTooltipWithExtra', {- count: prData.extraCount,- title: pullRequest.title,- })- : pullRequest.title- : prData?.ghMissing- ? t('workingDirectory.ghMissing')- : undefined;-const diffStatTooltip = hasChanges? t('workingDirectory.diffLineStatTooltip', {added: diffStats.additions,@@ -461,76 +387,42 @@ const GitStatus = memo<GitStatusProps>(const pushTargetExists = !!aheadBehind?.pushTargetExists;const branchTrigger = (- <div- {...stylex.props(gitChipStyles.trigger, betterCoding && !isDraft && styles.branchStatic)}- >+ <div {...stylex.props(gitChipStyles.trigger, !isDraft && styles.branchStatic)}><span {...stylex.props(styles.branchLabel)}>{(isDraft && draft.selectedBranch) || branch}</span></div>);- // The worktree menu is gone under the lab: a new topic forks its worktree- // on send instead (the toggle below), and an existing one keeps its own.- const hasWorktreeMenu = !betterCoding && worktrees.length > 0;-- const worktreeNode = hasWorktreeMenu ? (- <WorktreeSwitcher+ // No worktree menu: a new topic forks its worktree on send instead (the+ // toggle below), and an existing one keeps its own.+ const branchNode = !isDraft ? (+ // An existing topic stays on its branch; start a new topic to move.+ <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>+ ) : !pickersReady ? (+ // Hydrated from the last session: hold the checkout entry until this+ // session's branch AND worktree probes answer, so the switcher's "current"+ // branch and its worktree routing are not stale guesses.+ <Tooltip title={t('workingDirectory.branchConfirming')}>{branchTrigger}</Tooltip>+ ) : (+ // Local switches over IPC; a remote device switches over RPC (deviceId set).+ <BranchSwitcheragentId={agentId}currentBranch={branch}- detached={detached}deviceId={deviceId}- disabled={!pickersReady}isGithub={isGithub}+ open={switcherOpen}path={path}+ selection={{ branch: draft.selectedBranch, onSelect: draft.select }}sourcePath={sourcePath ?? path}topicId={topicId}worktrees={worktrees}- onWorktreesChange={mutateWorktrees}- />- ) : null;-- const branchNode =- betterCoding && !isDraft ? (- // An existing topic stays on its branch; start a new topic to move.- <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>- ) : detached && !isDraft ? (- // Detached HEAD → plain branch label (nothing to switch to).- <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>- ) : !pickersReady ? (- // Hydrated from the last session: hold the checkout entry until this- // session's branch AND worktree probes answer, so the switcher's "current"- // branch and its worktree routing are not stale guesses.- <Tooltip title={t('workingDirectory.branchConfirming')}>{branchTrigger}</Tooltip>- ) : (- // Local switches over IPC; a remote device switches over RPC (deviceId set).- <BranchSwitcher- agentId={agentId}- currentBranch={branch}- deviceId={deviceId}- isGithub={isGithub}- open={switcherOpen}- path={path}- selection={isDraft ? { branch: draft.selectedBranch, onSelect: draft.select } : undefined}- sourcePath={sourcePath ?? path}- topicId={topicId}- worktrees={worktrees}- onExternalRefresh={refreshAfterSync}- onOpenChange={setSwitcherOpen}- onOptimisticCheckout={handleOptimisticCheckout}- onAfterCheckout={() => {- void mutateBranch();- void mutatePR();- void mutateReviewPatches();- void mutateAheadBehind();- void mutateWorktrees();- }}- >- <Tooltip title={isDraft ? draft.selectedBranch || branchTooltip : branchTooltip}>- {branchTrigger}- </Tooltip>- </BranchSwitcher>- );+ onExternalRefresh={refreshAfterSync}+ onOpenChange={setSwitcherOpen}+ >+ <Tooltip title={draft.selectedBranch || branchTooltip}>{branchTrigger}</Tooltip>+ </BranchSwitcher>+ );const pullTooltip = pulling? t('workingDirectory.pullInProgress')@@ -627,29 +519,13 @@ const GitStatus = memo<GitStatusProps>(return (<><div {...stylex.props(gitChipStyles.separator)} />- {/* The worktree icon and the branch name name one thing — which checkout- * you're on — so they sit closer to each other than to their neighbours. */}- <div {...stylex.props(styles.branchGroup)}>- {worktreeNode}- {branchNode}- </div>+ <div {...stylex.props(styles.branchGroup)}>{branchNode}</div>{pullNode}{pushNode}{outdatedNode}{worktreeToggleNode}{diffNode}{topicPullRequestChip}- {pullRequest && (- <>- <div {...stylex.props(gitChipStyles.separator)} />- <Tooltip title={prTooltip}>- <div {...stylex.props(gitChipStyles.prTrigger)} role="button" onClick={handleOpenPr}>- <Icon icon={GitPullRequest} size={12} />- <span>#{pullRequest.number}</span>- </div>- </Tooltip>- </>- )}</>);},diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/index.tsxindex b7376c63550..82481b325e4 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/index.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/index.tsx@@ -87,7 +87,7 @@ interface PermissionModeSelectorProps {}/**- * The composer's Claude Code permission mode (Better Coding Experience lab).+ * The composer's Claude Code permission mode.* The chip names the mode the topic's run is in; when that is not the picked* one (root, an outdated `lh`), it says why.*/diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.test.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.test.tsindex 1bb5e05dc81..0d1b91b0a97 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.test.ts+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.test.ts@@ -59,7 +59,6 @@ describe('usePermissionMode', () => {useUserStore.setState({preference: {heteroPermissionModeDirs: [{ key: 'dev-1::/repo', mode: 'plan' }],- lab: { enableBetterCodingExperience: true },} as any,setHeteroPermissionModeDir: setDir,useFetchWorkspaceUserPreference: () => {},diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.tsindex b8b0c77c842..3a41837bbbb 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.ts+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/PermissionMode/usePermissionMode.ts@@ -103,7 +103,7 @@ export interface PermissionModeState {}/**- * The composer's Claude Code permission mode (Better Coding Experience lab).+ * The composer's Claude Code permission mode.** - An existing topic shows its own mode, which Claude Code's reports keep* current (leaving plan mode). Picking one writes it to the topic and, whilediff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/index.tsxindex 201175e469b..eb509f4dfe0 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/index.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/index.tsx@@ -32,7 +32,7 @@ interface PlanModeSwitchProps {}/**- * The composer's Codex Plan switch (Better Coding Experience lab). Not a+ * The composer's Codex Plan switch. Not a* permission mode: Codex keeps allowing every action; in plan it proposes a* plan instead of carrying the request out.*/diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/usePlanMode.ts b/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/usePlanMode.tsindex bfe2b4a4c82..95e58e19ce2 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/usePlanMode.ts+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/PlanMode/usePlanMode.ts@@ -81,7 +81,7 @@ export interface PlanModeState {}/**- * The composer's Codex Plan switch (Better Coding Experience lab).+ * The composer's Codex Plan switch.** - An existing topic shows its own `heteroPlanMode`; flipping it writes the* topic and, mid-run, tells the live thread, which takes it from the next turn.diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.test.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.test.tsxindex b5df5ed51b7..a030496cb48 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/index.test.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.test.tsx@@ -54,6 +54,13 @@ vi.mock('@/features/ChatInput/ControlBar/HeteroDeviceSwitcher', () => ({default: () => <div data-testid="hetero-device-switcher" />,}));+// The per-agent mode controls have their own tests; here they only take their slot.+vi.mock('./PermissionMode', () => ({+ default: () => <div data-testid="hetero-permission-mode" />,+}));+vi.mock('./PlanMode', () => ({+ default: () => <div data-testid="hetero-plan-mode" />,+}));vi.mock('@/features/AgentQuotaCalendar', () => ({openQuotaCalendarModal: vi.fn(),}));@@ -276,6 +283,25 @@ describe('HeteroControlBar', () => {expect(mockService.getCodexQuota).not.toHaveBeenCalled();});+ it('shows the permission mode chip for Claude Code and the Plan switch for Codex', () => {+ effectiveAgencyConfig.current = {+ executionTarget: 'local',+ heterogeneousProvider: { authMode: 'api', type: 'claude-code' },+ };+ const { unmount } = render(<HeteroControlBar />);+ expect(screen.getByTestId('hetero-permission-mode')).toBeTruthy();+ expect(screen.queryByTestId('hetero-plan-mode')).toBeNull();+ unmount();++ effectiveAgencyConfig.current = {+ executionTarget: 'local',+ heterogeneousProvider: { authMode: 'api', command: 'codex', type: 'codex' },+ };+ render(<HeteroControlBar />);+ expect(screen.getByTestId('hetero-plan-mode')).toBeTruthy();+ expect(screen.queryByTestId('hetero-permission-mode')).toBeNull();+ });+it('shows platform credits instead of Codex quota in API mode', () => {effectiveAgencyConfig.current = {boundDeviceId: 'personal-device',diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsxindex c4a732e1e45..1c617db7a9a 100644--- a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx@@ -24,8 +24,6 @@ import { resolveExecutionTarget } from '@/helpers/executionTarget';import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';import PermissionModeSelector from './PermissionMode';import PlanModeSwitch from './PlanMode';@@ -173,15 +171,14 @@ const HeteroControlBar = memo(() => {const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, { topicId });const heteroProvider = agencyConfig?.heterogeneousProvider;- const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);- // Claude Code under the lab picks how it asks before acting, per topic.+ // Claude Code picks how it asks before acting, per topic.const permissionModeChip =- betterCoding && heteroProvider?.type === 'claude-code' && agentId ? (+ heteroProvider?.type === 'claude-code' && agentId ? (<PermissionModeSelector agentId={agentId} topicId={topicId} />) : null;- // Codex under the lab gets a Plan switch beside its unchanged full access.+ // Codex gets a Plan switch beside its unchanged full access.const planModeSwitch =- betterCoding && heteroProvider?.type === 'codex' && agentId ? (+ heteroProvider?.type === 'codex' && agentId ? (<PlanModeSwitch agentId={agentId} topicId={topicId} />) : null;const executionTarget = resolveExecutionTarget(agencyConfig, {diff --git a/src/features/ChatInput/ControlBar/StagedBranchStatus.tsx b/src/features/ChatInput/ControlBar/StagedBranchStatus.tsxindex de478991e01..2352424329b 100644--- a/src/features/ChatInput/ControlBar/StagedBranchStatus.tsx+++ b/src/features/ChatInput/ControlBar/StagedBranchStatus.tsx@@ -5,12 +5,10 @@ import { Icon, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import { GitBranchIcon } from 'lucide-react';-import { memo, useCallback, useState } from 'react';+import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useFetchGitBranch } from '@/store/device';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';import BranchSwitcher from './BranchSwitcher';import { useDraftBranch } from './DraftGit/useDraftBranch';@@ -47,40 +45,31 @@ interface StagedBranchStatusProps {}/**- * The branch of the project directory a blank conversation is staged in, with- * an in-place checkout. Only the branch: the review, worktree and PR surfaces+ * The branch of the project directory a blank conversation is staged in. The+ * branch is only picked here; the first send switches to it, or forks a+ * worktree from it. Only the branch: the review, worktree and PR surfaces* of `GitStatus` act on the conversation's recorded directory, which does not* exist until the first send creates the topic.*/const StagedBranchStatus = memo<StagedBranchStatusProps>(({ agentId }) => {const { t } = useTranslation('device');const target = useStagedProjectGitTarget(agentId);- const { data, isConfirmed, mutate } = useFetchGitBranch(target?.deviceId, target?.path);+ const { data, isConfirmed } = useFetchGitBranch(target?.deviceId, target?.path);const [open, setOpen] = useState(false);- // Better Coding Experience: the branch is only picked here; the first send- // switches to it, or forks a worktree from it.- const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);const draft = useDraftBranch({agentId,currentBranch: data?.detached ? undefined : data?.branch,deviceId: target?.deviceId,- enabled: betterCoding && !!target,+ enabled: !!target,isGithub: !!target?.isGithub,path: target?.path ?? '',sourcePath: target?.path ?? '',});- const handleOptimisticCheckout = useCallback(- (branch: string) => {- void mutate({ branch, detached: false }, { revalidate: false });- },- [mutate],- );-const state = getStagedBranchState(data, isConfirmed);if (!target || state === 'hidden') return null;const branch = data!.branch!;- const label = (betterCoding && draft.selectedBranch) || branch;+ const label = draft.selectedBranch || branch;const trigger = (<div {...stylex.props(gitChipStyles.trigger)}>@@ -95,9 +84,7 @@ const StagedBranchStatus = memo<StagedBranchStatusProps>(({ agentId }) => {<span {...stylex.props(styles.branchIcon)}><Icon icon={GitBranchIcon} size={13} /></span>- {state === 'detached' && !betterCoding ? (- <Tooltip title={t('workingDirectory.detachedHead', { sha: branch })}>{trigger}</Tooltip>- ) : state === 'confirming' ? (+ {state === 'confirming' ? (<Tooltip title={t('workingDirectory.branchConfirming')}>{trigger}</Tooltip>) : (<BranchSwitcher@@ -107,27 +94,21 @@ const StagedBranchStatus = memo<StagedBranchStatusProps>(({ agentId }) => {isGithub={target.isGithub}open={open}path={target.path}+ selection={{ branch: draft.selectedBranch, onSelect: draft.select }}sourcePath={target.path}topicId={null}worktrees={NO_WORKTREES}- selection={- betterCoding ? { branch: draft.selectedBranch, onSelect: draft.select } : undefined- }- onAfterCheckout={() => void mutate()}onOpenChange={setOpen}- onOptimisticCheckout={handleOptimisticCheckout}><Tooltip title={label}>{trigger}</Tooltip></BranchSwitcher>)}</div>- {betterCoding && (- <WorktreeToggle- baseBranch={draft.selectedBranch}- keyDeviceId={draft.keyDeviceId}- path={target.path}- />- )}+ <WorktreeToggle+ baseBranch={draft.selectedBranch}+ keyDeviceId={draft.keyDeviceId}+ path={target.path}+ /></>);});diff --git a/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx b/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsxindex 7a5d19376d9..944a4d3b52f 100644--- a/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx+++ b/src/features/ChatInput/ControlBar/StaleGitSnapshot.tsx@@ -10,12 +10,10 @@ import {} from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { GitBranchIcon, GitForkIcon, GitPullRequest, RotateCcwIcon } from 'lucide-react';+import { GitBranchIcon, GitForkIcon, RotateCcwIcon } from 'lucide-react';import { memo, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';-import { openTrustedExternalUrl } from '@/utils/openTrustedExternalUrl';-import { gitChipStyles } from './gitChipStyles';import { resolveStaleSnapshot } from './staleSnapshot';import { useSwitchWorktree } from './useSwitchWorktree';@@ -61,9 +59,10 @@ interface StaleGitSnapshotProps {* Every live control (checkout, worktree switch, pull/push, diff review) needs a* directory that no longer exists, so none of them render. What remains is the* topic's own snapshot — the same one the sidebar meta hover card reads — plus- * the two things that still work without a local directory: opening the linked- * PR, and dropping the dead worktree override so the conversation falls back to- * its source repo. Without that second one the state is a dead end: the bar+ * the one thing that still works without a local directory: dropping the dead+ * worktree override so the conversation falls back to its source repo (the+ * topic's linked PRs stay beside it, from the server). Without it the state is+ * a dead end: the bar* explains why the branch is frozen but leaves no way out of it.*/const StaleGitSnapshot = memo<StaleGitSnapshotProps>(@@ -78,14 +77,11 @@ const StaleGitSnapshot = memo<StaleGitSnapshotProps>(topicId,});- const { explanation, isWorktree, label, pullRequest, reset, worktreePath } =- resolveStaleSnapshot({ git, path, sourcePath });-- const handleOpenPr = useCallback(() => {- if (pullRequest?.url) {- openTrustedExternalUrl(pullRequest.url);- }- }, [pullRequest?.url]);+ const { explanation, isWorktree, label, reset, worktreePath } = resolveStaleSnapshot({+ git,+ path,+ sourcePath,+ });const resetTarget = reset?.targetPath;const handleReset = useCallback(async () => {@@ -138,15 +134,6 @@ const StaleGitSnapshot = memo<StaleGitSnapshotProps>(</DropdownMenuPositioner></DropdownMenuPortal></DropdownMenuRoot>- {pullRequest && (- <>- <div {...stylex.props(gitChipStyles.separator)} />- <div {...stylex.props(gitChipStyles.prTrigger)} role="button" onClick={handleOpenPr}>- <Icon icon={GitPullRequest} size={12} />- <span>#{pullRequest.number}</span>- </div>- </>- )}</>);},diff --git a/src/features/ChatInput/ControlBar/TopicPullRequestChip.tsx b/src/features/ChatInput/ControlBar/TopicPullRequestChip.tsxindex 881ef34bbba..1ad5c53008d 100644--- a/src/features/ChatInput/ControlBar/TopicPullRequestChip.tsx+++ b/src/features/ChatInput/ControlBar/TopicPullRequestChip.tsx@@ -26,7 +26,7 @@ interface TopicPullRequestChipProps {}/**- * Better Coding Experience: the pull requests the agent's own commands linked+ * The pull requests the agent's own commands linked* to this topic. Shows the latest one still open (else the latest), plus how* many more; with more than one, a click lists them all. Nothing renders until* a PR is linked.diff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsxindex ca7b807fa17..e80e991880d 100644--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx@@ -1,9 +1,8 @@import { fireEvent, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { gitService } from '@/services/git';-import { useUserStore } from '@/store/user';import GitStatus from '../GitStatus';@@ -23,26 +22,28 @@ const deviceStoreMock = vi.hoisted(() => ({const gitHookMocks = vi.hoisted(() => ({mutateAheadBehind: vi.fn(),mutateBranch: vi.fn(),- mutatePR: vi.fn(),mutateReviewPatches: vi.fn(),mutateWorktrees: vi.fn(),setDiffStats: vi.fn(),useFetchGitAheadBehind: vi.fn(),useFetchGitBranch: vi.fn(),useFetchGitDiffStats: vi.fn(),- useFetchGitLinkedPR: vi.fn(),useReviewPatches: vi.fn(),useFetchGitWorktrees: vi.fn(),}));vi.mock('../BranchSwitcher', () => ({- default: ({ children }: { children: ReactNode }) => <>{children}</>,+ default: ({ children }: { children: ReactNode }) => (+ <span data-testid="branch-switcher">{children}</span>+ ),}));-vi.mock('../WorktreeSwitcher', () => ({- default: ({ disabled }: { disabled?: boolean }) => (- <span data-disabled={Boolean(disabled)} data-testid="worktree-switcher" />- ),+vi.mock('../DraftGit/useDraftBranch', () => ({+ useDraftBranch: () => ({ keyDeviceId: 'local', select: vi.fn(), selectedBranch: undefined }),+}));++vi.mock('../DraftGit/WorktreeToggle', () => ({+ WorktreeToggle: () => <span data-testid="worktree-toggle" />,}));vi.mock('../TopicPullRequestChip', () => ({@@ -67,7 +68,6 @@ vi.mock('@/store/device', () => ({useFetchGitAheadBehind: gitHookMocks.useFetchGitAheadBehind,useFetchGitBranch: gitHookMocks.useFetchGitBranch,useFetchGitDiffStats: gitHookMocks.useFetchGitDiffStats,- useFetchGitLinkedPR: gitHookMocks.useFetchGitLinkedPR,useReviewPatches: gitHookMocks.useReviewPatches,useFetchGitWorktrees: gitHookMocks.useFetchGitWorktrees,}));@@ -116,10 +116,6 @@ beforeEach(() => {isConfirmed: true,mutate: gitHookMocks.mutateBranch,});- gitHookMocks.useFetchGitLinkedPR.mockReturnValue({- data: { pullRequest: null },- mutate: gitHookMocks.mutatePR,- });gitHookMocks.useReviewPatches.mockReturnValue({data: {mode: 'unstaged',@@ -179,32 +175,6 @@ describe('GitStatus', () => {expect(globalStoreMock.openWorkingSidebar).toHaveBeenCalledWith('review');});- it('renders the linked GitHub PR number as a live display (no topic write)', async () => {- gitHookMocks.useFetchGitLinkedPR.mockReturnValue({- data: {- pullRequest: {- ciStatus: 'pending',- mergeStateStatus: 'CLEAN',- number: 123,- state: 'OPEN',- title: 'Improve worktree handling',- url: 'https://github.com/lobehub/lobehub/pull/123',- },- pullRequestStatus: 'ok',- },- mutate: gitHookMocks.mutatePR,- });-- render(<GitStatus isGithub agentId="agent-1" path="/repo" />);-- // Pure display: the chip shows the current branch's PR number. Persisting it- // onto the topic now happens at send time (see snapshotWorkingDirGit), so- // opening a topic must never mutate its stored branch/PR here.- await waitFor(() => {- expect(screen.getByText('#123')).toBeInTheDocument();- });- });-// The diff counts come from a separate read. Their persisted copy keeps the// composer cluster stable while that read is still in flight.it('paints the persisted change counts while the review patches load', () => {@@ -246,11 +216,9 @@ describe('GitStatus', () => {render(<GitStatus isGithub agentId="agent-1" path="/repo" sourcePath="/repo" />);- // The branch label still paints…+ // The branch label still paints, but the picker waits for confirmation.expect(screen.getByText('fix/remote-review')).toBeInTheDocument();- // …and the worktree entry stays mounted (removing it would shift the branch- // chip when it returns) but is inert until confirmation.- expect(screen.getByTestId('worktree-switcher')).toHaveAttribute('data-disabled', 'true');+ expect(screen.queryByTestId('branch-switcher')).not.toBeInTheDocument();const push = screen.getByText('2').closest('[role="button"]')!;const pull = screen.getByText('1').closest('[role="button"]')!;expect(push).toHaveAttribute('aria-disabled', 'true');@@ -306,7 +274,7 @@ describe('GitStatus', () => {// Review P1: the branch picker routes through the worktree list. A confirmed// branch alone must not enable a picker that still holds last session's// worktrees — it could point at a worktree removed externally.- it('keeps both pickers inert until the worktree list itself is confirmed', () => {+ it('keeps the branch picker inert until the worktree list itself is confirmed', () => {gitHookMocks.useFetchGitBranch.mockReturnValue({data: { branch: 'fix/remote-review', detached: false },isConfirmed: true,@@ -324,7 +292,8 @@ describe('GitStatus', () => {render(<GitStatus isGithub agentId="agent-1" path="/repo" sourcePath="/repo" />);// The trigger keeps its width (no layout jump) but cannot switch.- expect(screen.getByTestId('worktree-switcher')).toHaveAttribute('data-disabled', 'true');+ expect(screen.getByText('fix/remote-review')).toBeInTheDocument();+ expect(screen.queryByTestId('branch-switcher')).not.toBeInTheDocument();});describe('deleted working directory', () => {@@ -363,7 +332,7 @@ describe('GitStatus', () => {'data-branch','feat/task-list-subtask-nesting',);- expect(screen.queryByTestId('worktree-switcher')).not.toBeInTheDocument();+ expect(screen.queryByTestId('branch-switcher')).not.toBeInTheDocument();});// Worktrees picked from the bar were persisted without a branch. The dead@@ -436,24 +405,6 @@ describe('GitStatus', () => {});});- it('skips the linked-PR lookup, which has no directory to run `gh` in', () => {- render(- <GitStatus- isGithub- agentId="agent-1"- fallbackGit={fallbackGit}- path="/tmp/lobehub-wt-subtask"- />,- );-- expect(gitHookMocks.useFetchGitLinkedPR).toHaveBeenCalledWith(- undefined,- '/tmp/lobehub-wt-subtask',- undefined,- true,- );- });-it('does not flash the dead-directory snapshot while the probe is still pending', () => {gitHookMocks.useFetchGitBranch.mockReturnValue({data: undefined,@@ -499,7 +450,7 @@ describe('GitStatus', () => {undefined,false,);- // No branch either: the counts describe HEAD, as without the lab.+ // No branch either: the counts describe HEAD.expect(gitHookMocks.useFetchGitAheadBehind).toHaveBeenCalledWith(undefined,undefined,@@ -568,20 +519,17 @@ describe('GitStatus', () => {data: undefined,mutate: gitHookMocks.mutateBranch,});- gitHookMocks.useFetchGitLinkedPR.mockReturnValue({- data: undefined,- mutate: gitHookMocks.mutatePR,- });});// Regression: the bar rendered nothing until the branch probe answered, so- // the whole branch / PR cluster popped in after every reload even though the+ // the whole branch cluster popped in after every reload even though the// topic already carried a persisted git snapshot.- it('paints the persisted branch and PR snapshot instead of collapsing', () => {+ it('paints the persisted branch snapshot instead of collapsing', () => {render(<GitStatus isGithub agentId="agent-1" fallbackGit={fallbackGit} path="/repo" />);expect(screen.getByText('feat/stale-first')).toBeInTheDocument();- expect(screen.getByText('#42')).toBeInTheDocument();+ // A PR an older client recorded on the branch is never shown.+ expect(screen.queryByText('#42')).not.toBeInTheDocument();expect(screen.queryByTestId('stale-git-snapshot')).not.toBeInTheDocument();});@@ -592,122 +540,38 @@ describe('GitStatus', () => {});});- it('keeps the recorded PR chip while the linked-PR lookup for the same branch loads', () => {- gitHookMocks.useFetchGitLinkedPR.mockReturnValue({- data: undefined,- mutate: gitHookMocks.mutatePR,- });-- render(- <GitStatus- isGithub- agentId="agent-1"- path="/repo"- fallbackGit={{- branch: 'fix/remote-review',- github: {- pullRequest: { number: 7, state: 'OPEN', title: 'Remote review', url: 'https://x/7' },- },- }}- />,- );+ it('offers the branch picker on a new conversation once the reads are confirmed', () => {+ render(<GitStatus isGithub agentId="agent-1" path="/repo" sourcePath="/repo" />);- expect(screen.getByText('#7')).toBeInTheDocument();+ expect(screen.getByTestId('branch-switcher')).toHaveTextContent('fix/remote-review');+ expect(screen.getByTestId('worktree-toggle')).toBeInTheDocument();});- it('drops the recorded PR chip once the live branch differs from the snapshot', () => {- gitHookMocks.useFetchGitLinkedPR.mockReturnValue({- data: undefined,- mutate: gitHookMocks.mutatePR,- });-+ it("shows an existing topic's branch as a label, not a picker", () => {render(- <GitStatus- isGithub- agentId="agent-1"- path="/repo"- fallbackGit={{- branch: 'other-branch',- github: {- pullRequest: { number: 7, state: 'OPEN', title: 'Other', url: 'https://x/7' },- },- }}- />,+ <GitStatus isGithub agentId="agent-1" path="/repo" sourcePath="/repo" topicId="topic-1" />,);- expect(screen.queryByText('#7')).not.toBeInTheDocument();- });-- it('keeps branch switching visible when worktrees are available', () => {- gitHookMocks.useFetchGitWorktrees.mockReturnValue({- data: [- { branch: 'fix/remote-review', current: true, path: '/repo' },- { branch: 'canary', current: false, path: '/repo-canary' },- ],- isConfirmed: true,- mutate: gitHookMocks.mutateWorktrees,- });-- render(<GitStatus isGithub agentId="agent-1" path="/repo" sourcePath="/repo" />);-- expect(screen.getByTestId('worktree-switcher')).toHaveAttribute('data-disabled', 'false');expect(screen.getByText('fix/remote-review')).toBeInTheDocument();+ expect(screen.queryByTestId('branch-switcher')).not.toBeInTheDocument();+ expect(screen.queryByTestId('worktree-toggle')).not.toBeInTheDocument();});});-describe('GitStatus — Better Coding Experience pull requests', () => {- const setLab = (on: boolean) => {- const preference = useUserStore.getState().preference;- useUserStore.setState({- preference: { ...preference, lab: { ...preference.lab, enableBetterCodingExperience: on } },- });- };-- afterEach(() => setLab(false));-- it('shows the topic PR chip instead of the branch PR, and never asks gh for the branch', () => {- setLab(true);- gitHookMocks.useFetchGitLinkedPR.mockReturnValue({- data: {- pullRequest: { number: 77, state: 'OPEN', title: 'guessed', url: 'https://x/77' },- },- mutate: gitHookMocks.mutatePR,- });-+describe('GitStatus — topic pull requests', () => {+ it("shows the topic's PR chip", () => {render(<GitStatus isGithub agentId="agent-1" path="/repo" topicId="topic-1" />);- expect(gitHookMocks.useFetchGitLinkedPR).toHaveBeenCalledWith(- undefined,- '/repo',- 'fix/remote-review',- false,- );- expect(screen.queryByText('#77')).toBeNull();expect(screen.getByTestId('topic-pull-request-chip')).toHaveTextContent('topic-1');});it('shows no PR at all on a new conversation', () => {- setLab(true);-render(<GitStatus isGithub agentId="agent-1" path="/repo" topicId={null} />);expect(screen.queryByTestId('topic-pull-request-chip')).toBeNull();});- it('keeps the branch PR chip without the lab', () => {- gitHookMocks.useFetchGitLinkedPR.mockReturnValue({- data: { pullRequest: { number: 77, state: 'OPEN', title: 'branch', url: 'https://x/77' } },- mutate: gitHookMocks.mutatePR,- });-- render(<GitStatus isGithub agentId="agent-1" path="/repo" topicId="topic-1" />);-- expect(screen.getByText('#77')).toBeInTheDocument();- expect(screen.queryByTestId('topic-pull-request-chip')).toBeNull();- });-it('keeps the topic PR chip while the device cannot be read', () => {- setLab(true);deviceStoreMock.devices = [{ deviceId: 'device-1', online: false }];gitHookMocks.useFetchGitBranch.mockReturnValue({data: undefined,diff --git a/src/features/ChatInput/ControlBar/__tests__/staleSnapshot.test.ts b/src/features/ChatInput/ControlBar/__tests__/staleSnapshot.test.tsindex 69c31e910f0..dc26284a4c3 100644--- a/src/features/ChatInput/ControlBar/__tests__/staleSnapshot.test.ts+++ b/src/features/ChatInput/ControlBar/__tests__/staleSnapshot.test.ts@@ -8,26 +8,16 @@ import { resolveStaleSnapshot } from '../staleSnapshot';const deadWorktree = {activeWorktree: '/tmp/lobehub-wt-subtask',branch: 'feat/task-list-subtask-nesting',- github: {- pullRequest: {- number: 18_454,- state: 'OPEN',- title: 'PR #18454',- url: 'https://github.com/lobehub/lobehub/pull/18454',- },- pullRequestStatus: 'ok' as const,- },isWorktree: true,};describe('resolveStaleSnapshot', () => {- it('surfaces the recorded branch, worktree and linked PR', () => {+ it('surfaces the recorded branch and worktree', () => {const view = resolveStaleSnapshot({ git: deadWorktree, path: '/tmp/lobehub-wt-subtask' });expect(view.branch).toBe('feat/task-list-subtask-nesting');expect(view.worktreePath).toBe('/tmp/lobehub-wt-subtask');expect(view.isWorktree).toBe(true);- expect(view.pullRequest?.number).toBe(18_454);});it('labels the chip with the recorded branch', () => {diff --git a/src/features/ChatInput/ControlBar/staleSnapshot.ts b/src/features/ChatInput/ControlBar/staleSnapshot.tsindex 1136e4698d7..6d21280d5b0 100644--- a/src/features/ChatInput/ControlBar/staleSnapshot.ts+++ b/src/features/ChatInput/ControlBar/staleSnapshot.ts@@ -1,4 +1,4 @@-import type { DeviceGitLinkedPullRequest, WorkingDirGitState } from '@lobechat/types';+import type { WorkingDirGitState } from '@lobechat/types';import { getWorkingDirectoryName, isWorktreeCheckout } from '@/helpers/workingDirectoryPath';@@ -16,7 +16,6 @@ export interface StaleSnapshotView {isWorktree: boolean;/** What the chip shows: the recorded branch, else the dead checkout's name. */label: string;- pullRequest?: DeviceGitLinkedPullRequest;/*** Where "go back" lands, and whether it is offered at all. Present only when a* worktree override can be dropped — if the recorded SOURCE repo is itself the@@ -59,7 +58,6 @@ export const resolveStaleSnapshot = ({: { key: 'workingDirectory.staleSnapshot' },isWorktree,label: git.branch || getWorkingDirectoryName(worktreePath) || worktreePath,- pullRequest: git.github?.pullRequest ?? undefined,...(canReset? { reset: { name: getWorkingDirectoryName(sourcePath), targetPath: sourcePath! } }: {}),diff --git a/src/features/Conversation/ChatInput/QueueTray.test.tsx b/src/features/Conversation/ChatInput/QueueTray.test.tsxindex e6250bc3028..c7c01a71dfe 100644--- a/src/features/Conversation/ChatInput/QueueTray.test.tsx+++ b/src/features/Conversation/ChatInput/QueueTray.test.tsx@@ -53,7 +53,7 @@ describe('QueueTray', () => {render(<QueueTray />);expect(screen.getAllByText('inputQueue.deliveringHint').length).toBeGreaterThan(0);- expect(screen.queryByText('inputQueue.queuedHint')).toBeNull();+ expect(screen.queryByText('inputQueue.steerHint')).toBeNull();for (const label of actionLabels) expect(screen.queryByLabelText(label)).toBeNull();});@@ -63,7 +63,7 @@ describe('QueueTray', () => {setQueue([serverQueued()]);- expect(screen.getAllByText('inputQueue.queuedHint').length).toBeGreaterThan(0);+ expect(screen.getAllByText('inputQueue.steerHint').length).toBeGreaterThan(0);expect(screen.queryByText('inputQueue.deliveringHint')).toBeNull();for (const label of actionLabels) expect(screen.getByLabelText(label)).toBeTruthy();});@@ -73,8 +73,8 @@ describe('QueueTray', () => {render(<QueueTray />);// One waiting row: it sends on its own, not merged with the delivering one.- expect(screen.getAllByText('inputQueue.queuedHint').length).toBeGreaterThan(0);- expect(screen.queryByText('inputQueue.queuedMergeHint')).toBeNull();+ expect(screen.getAllByText('inputQueue.steerHint').length).toBeGreaterThan(0);+ expect(screen.queryByText('inputQueue.steerMergeHint')).toBeNull();for (const label of actionLabels) expect(screen.getAllByLabelText(label)).toHaveLength(1);});});diff --git a/src/features/Conversation/ChatInput/utils.test.ts b/src/features/Conversation/ChatInput/utils.test.tsindex 674800db228..77f450030c4 100644--- a/src/features/Conversation/ChatInput/utils.test.ts+++ b/src/features/Conversation/ChatInput/utils.test.ts@@ -92,35 +92,6 @@ describe('getQueuedHintKey by Follow-up behavior', () => {});});-describe('getQueuedHintKey', () => {- it('promises the next step boundary for the built-in runtime', () => {- expect(getQueuedHintKey({ count: 1, waitsForRunEnd: false })).toBe('inputQueue.queuedHint');- expect(getQueuedHintKey({ count: 2, waitsForRunEnd: false })).toBe(- 'inputQueue.queuedMergeHint',- );- });-- /**- * @example A follow-up is queued while a Claude Code run is still calling tools.- */- it('promises the end of the whole run for heterogeneous agents', () => {- // ROOT CAUSE:- //- // A Claude Code / Codex CLI turn cannot be handed back at a step boundary:- // the queue drains only once the CLI run ends. QueueTray still captioned- // the row "Sends when the current step finishes".- //- // Before: one caption for every runtime.- // After: heterogeneous agents say the follow-up waits for the current run.- expect(getQueuedHintKey({ count: 1, waitsForRunEnd: true })).toBe(- 'inputQueue.queuedRunEndHint',- );- expect(getQueuedHintKey({ count: 3, waitsForRunEnd: true })).toBe(- 'inputQueue.queuedRunEndMergeHint',- );- });-});-describe('toChatInputMessages', () => {it('preserves user, assistant, and tool messages with their real roles', () => {expect(toChatInputMessages(tokenMessages).map((message) => message.role)).toEqual([diff --git a/src/features/Conversation/ChatInput/utils.ts b/src/features/Conversation/ChatInput/utils.tsindex 57ec54a392c..cd79ecc9ed6 100644--- a/src/features/Conversation/ChatInput/utils.ts+++ b/src/features/Conversation/ChatInput/utils.ts@@ -1,7 +1,7 @@import { getSlicedMessages } from '@lobechat/context-engine';import type {ConversationContext,- FollowUpMode,+ FollowUpBehavior,OpenAIChatMessage,UIChatMessage,} from '@lobechat/types';@@ -89,12 +89,12 @@ export const createQueueSendNowGate = (): QueueSendNowGate => {*/export const getQueuedHintKey = ({count,- mode = 'legacy',+ mode,waitsForRunEnd,}: {count: number;- /** The Follow-up behavior in effect (`legacy` while its lab is off). */- mode?: FollowUpMode;+ /** The user's Follow-up behavior. */+ mode: FollowUpBehavior;waitsForRunEnd: boolean;}) => {const merged = count > 1;@@ -103,16 +103,9 @@ export const getQueuedHintKey = ({if (mode === 'queue')return merged ? 'inputQueue.queuedOneByOneHint' : 'inputQueue.queuedRunEndHint';// Steer: joins the running turn, unless this run cannot take one mid-run.- if (mode === 'steer') {- if (waitsForRunEnd)- return merged ? 'inputQueue.steerUnsupportedMergeHint' : 'inputQueue.steerUnsupportedHint';- return merged ? 'inputQueue.steerMergeHint' : 'inputQueue.steerHint';- }-if (waitsForRunEnd)- return merged ? 'inputQueue.queuedRunEndMergeHint' : 'inputQueue.queuedRunEndHint';-- return merged ? 'inputQueue.queuedMergeHint' : 'inputQueue.queuedHint';+ return merged ? 'inputQueue.steerUnsupportedMergeHint' : 'inputQueue.steerUnsupportedHint';+ return merged ? 'inputQueue.steerMergeHint' : 'inputQueue.steerHint';};const isSupportedChatInputMessage = (diff --git a/src/features/Conversation/Markdown/plugins/Link/PullRequestLinkToolbar.tsx b/src/features/Conversation/Markdown/plugins/Link/PullRequestLinkToolbar.tsxindex 54a2b2111fe..cadaa07e43c 100644--- a/src/features/Conversation/Markdown/plugins/Link/PullRequestLinkToolbar.tsx+++ b/src/features/Conversation/Markdown/plugins/Link/PullRequestLinkToolbar.tsx@@ -3,9 +3,6 @@ import { Link2 } from 'lucide-react';import { type ReactNode, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';-import { useConversationStore } from '../../../store';import { usePullRequestLink } from './usePullRequestLink';@@ -63,12 +60,11 @@ const Toolbar = ({};export const PullRequestLinkToolbar = (props: PullRequestLinkToolbarProps) => {- const enabled = useUserStore(labPreferSelectors.enableBetterCodingExperience);const topicId = useConversationStore(({ context, skipFetch }) =>skipFetch || context.topicShareId || context.agentShareId ? undefined : context.topicId,);- if (!enabled || !topicId) return props.children;+ if (!topicId) return props.children;return <Toolbar key={`${topicId}:${props.identifier}`} {...props} topicId={topicId} />;};diff --git a/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/index.tsxindex 745ea089a63..9e7efffe2a4 100644--- a/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/BackgroundTasks/index.tsx@@ -8,8 +8,6 @@ import { highlightMessageWhenScrollSettles } from '@/features/Portal/TopicCommenimport { useChatStore } from '@/store/chat';import { displayMessageSelectors } from '@/store/chat/selectors';import { getLocalBackgroundTaskStopper } from '@/store/chat/slices/agentRun/actions/transports/hetero/backgroundTasks';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';import { SectionHeader } from '../SectionHeader';import { sectionProps } from '../sectionStyles';@@ -44,10 +42,9 @@ const locate = ({ toolCallId }: BackgroundTaskItem) => {/*** Background tasks a Claude Code run started (`run_in_background` Bash,- * Monitor), Better Coding Experience only. Running ones all show; finished ones- * fold to the most recent few.+ * Monitor). Running ones all show; finished ones fold to the most recent few.*/-const BackgroundTasksBody = ({+export const BackgroundTasksSection = ({afterBreak,deviceId,outputReadable,@@ -109,10 +106,3 @@ const BackgroundTasksBody = ({</Flexbox>);};--/** Renders nothing unless the Better Coding Experience lab is on. */-export const BackgroundTasksSection = (props: BackgroundTasksSectionProps) => {- const enabled = useUserStore(labPreferSelectors.enableBetterCodingExperience);- if (!enabled) return null;- return <BackgroundTasksBody {...props} />;-};diff --git a/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestModal.tsx b/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestModal.tsxindex 05ab105c5e2..eaf41e442aa 100644--- a/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestModal.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestModal.tsx@@ -63,7 +63,7 @@ const LinkPullRequestContent = memo<LinkPullRequestContentProps>(({ onLink }) =>LinkPullRequestContent.displayName = 'LinkPullRequestContent';/**- * Better Coding Experience: link a PR the agent's commands never touched by+ * Link a PR the agent's commands never touched by* pasting its GitHub URL.*/export const openLinkPullRequestModal = (onLink: LinkPullRequestContentProps['onLink']) =>diff --git a/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestRow.tsx b/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestRow.tsxindex 8d395e868e4..af10d1f03df 100644--- a/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestRow.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/LinkPullRequestRow.tsx@@ -10,7 +10,7 @@ interface LinkPullRequestRowProps {onLink: (url: string) => Promise<string | undefined>;}-/** Better Coding Experience: the repository card's "Link a pull request" action. */+/** The repository card's "Link a pull request" action. */export const LinkPullRequestRow = memo<LinkPullRequestRowProps>(({ onLink }) => {const { t } = useTranslation('chat');diff --git a/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsxindex 58ee44ca72a..3e953fcf52d 100644--- a/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRow.tsx@@ -18,7 +18,7 @@ import { sectionStyles } from './sectionStyles';import { statusTint } from './statusTint';interface PullRequestRowProps {- /** Better Coding Experience: the row's "⋯" menu, after the CI pill. */+ /** The row's "⋯" menu, after the CI pill. */actions?: ReactNode;onClick: () => void;pullRequest: DeviceGitLinkedPullRequest;diff --git a/src/features/Conversation/WorkingSidebar/Overview/PullRequestRowMenu.tsx b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRowMenu.tsxindex 6b84db40b20..948e7aba684 100644--- a/src/features/Conversation/WorkingSidebar/Overview/PullRequestRowMenu.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/PullRequestRowMenu.tsx@@ -27,7 +27,7 @@ interface PullRequestRowMenuProps {view: TopicPullRequestView;}-/** Better Coding Experience: the "⋯" menu at the end of a topic's PR row. */+/** The "⋯" menu at the end of a topic's PR row. */const PullRequestRowMenu = ({ onDismiss, topicId, view }: PullRequestRowMenuProps) => {const { t } = useTranslation('chat');const router = useQueryRoute();diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsxindex 59e8077e4c9..6a5e772e0e8 100644--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx@@ -80,18 +80,18 @@ interface OverviewProps {/** Routes file / git RPCs; empty for "This device", which reads over IPC. */deviceId?: string;environmentAvailable: boolean;- /** Better Coding Experience: remove one of {@link pullRequests} from the topic. */+ /** Remove one of {@link pullRequests} from the topic. */onDismissPullRequest?: (pullRequest: TopicPullRequestView) => Promise<void>;- /** Better Coding Experience: link a PR by URL; resolves to its `owner/repo#n`. */+ /** Link a PR by URL; resolves to its `owner/repo#n`. */onLinkPullRequest?: (url: string) => Promise<string | undefined>;- /** Better Coding Experience: open one of {@link pullRequests}. */+ /** Open one of {@link pullRequests}. */onOpenPullRequest?: (pullRequest: TopicPullRequestView) => void;onOpenTab: (tab: string) => void;onRefreshPullRequest: () => Promise<unknown>;/** Parent-owned so the Overview row and the on-demand PR tab cannot disagree. */pullRequest?: DeviceGitLinkedPullRequest | null;/**- * Better Coding Experience: every PR the topic's Work rows link, listed+ * Every PR the topic's Work rows link, listed* under Changes in place of the single branch PR.*/pullRequests?: TopicPullRequestView[];@@ -293,7 +293,7 @@ const Overview = memo<OverviewProps>(/>);- // Better Coding Experience PRs are server records: they stay listed with+ // A topic's PRs are server records: they stay listed with// their last known state even when the working directory cannot be read.const topicPullRequestRows = pullRequests && (<>diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useLinkedPullRequest.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useLinkedPullRequest.test.tsdeleted file mode 100644index 01eb95a189c..00000000000--- a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useLinkedPullRequest.test.ts+++ /dev/null@@ -1,76 +0,0 @@-import { describe, expect, it } from 'vitest';--import { resolveLinkedPullRequest } from '../useLinkedPullRequest';--const pr = (number: number) => ({- number,- state: 'OPEN',- title: `PR ${number}`,- url: `u/${number}`,-});--const base = {- available: true,- branch: { branch: 'feat/x' },- branchConfirmed: true,- linkedPR: { pullRequest: pr(42), pullRequestStatus: 'ok' as const },- linkedPRConfirmed: true,-};--describe('resolveLinkedPullRequest', () => {- it('confirms a PR the live branch and lookup reads both answered', () => {- expect(resolveLinkedPullRequest(base)).toEqual({- confirmError: undefined,- confirmed: true,- pullRequest: pr(42),- });- });-- // Regression: after an external checkout between sessions the persisted- // branch + linked PR painted the old PR, and its close / merge actions were- // live before the device answered.- it('paints but does not confirm a PR from persisted rows', () => {- expect(resolveLinkedPullRequest({ ...base, branchConfirmed: false })).toEqual({- confirmError: undefined,- confirmed: false,- pullRequest: pr(42),- });- expect(resolveLinkedPullRequest({ ...base, linkedPRConfirmed: false }).confirmed).toBe(false);- });-- it('never confirms the topic snapshot stand-in', () => {- const result = resolveLinkedPullRequest({- ...base,- linkedPR: undefined,- linkedPRConfirmed: false,- snapshot: { branch: 'feat/x', github: { pullRequest: pr(7) } },- });- expect(result).toEqual({ confirmError: undefined, confirmed: false, pullRequest: pr(7) });- });-- it('lets a confirmed empty lookup hide the snapshot PR', () => {- const result = resolveLinkedPullRequest({- ...base,- linkedPR: { pullRequest: null, pullRequestStatus: 'ok' },- snapshot: { branch: 'feat/x', github: { pullRequest: pr(7) } },- });- expect(result).toEqual({ confirmError: undefined, confirmed: false, pullRequest: null });- });-- // Regression: a failed branch / linked-PR read left the persisted PR locked- // with no error and no retry in the PR pane.- it('reports the failed read that keeps the PR unconfirmed', () => {- const offline = new Error('device offline');- expect(- resolveLinkedPullRequest({ ...base, branchConfirmed: false, branchError: offline })- .confirmError,- ).toBe(offline);- expect(- resolveLinkedPullRequest({ ...base, linkedPRConfirmed: false, linkedPRError: offline })- .confirmError,- ).toBe(offline);- expect(- resolveLinkedPullRequest({ ...base, linkedPRError: offline }).confirmError,- ).toBeUndefined();- });-});diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.tsindex 02a44c0b333..b7dbc2b4e1b 100644--- a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/usePullRequestActions.test.ts@@ -128,9 +128,6 @@ describe('usePullRequestActions', () => {'aheadBehind','workingTreeStatus',]);- const matcher = mutate.mock.calls.find(([key]) => typeof key === 'function')?.[0];- expect(matcher(deviceKeys.gitLinkedPR('dev-1', '/repo', 'feat/x', 7))).toBe(true);- expect(matcher(deviceKeys.gitLinkedPR('dev-1', '/other', 'feat/x'))).toBe(false);});it('targets the confirmed PR and reports success even if the worktree disappeared', async () => {diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useSidebarPullRequests.test.ts b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useSidebarPullRequests.test.tsindex 5a10d827083..6a57db5e851 100644--- a/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useSidebarPullRequests.test.ts+++ b/src/features/Conversation/WorkingSidebar/PullRequest/__tests__/useSidebarPullRequests.test.ts@@ -7,10 +7,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { useSidebarPullRequests } from '../useSidebarPullRequests';const mocks = vi.hoisted(() => ({- betterCoding: true,- legacy: vi.fn(),linked: {- enabled: true,primary: undefined as any,probes: [] as any[],views: [] as any[],@@ -20,12 +17,6 @@ const mocks = vi.hoisted(() => ({refresh: vi.fn(),}));-vi.mock('@/store/user', () => ({- useUserStore: (selector: (s: unknown) => unknown) => selector({}),-}));-vi.mock('@/store/user/selectors', () => ({- labPreferSelectors: { enableBetterCodingExperience: () => mocks.betterCoding },-}));vi.mock('@/features/TopicPullRequests/useTopicPullRequests', () => ({useTopicPullRequests: () => mocks.linked,}));@@ -36,12 +27,6 @@ vi.mock('@/services/work', () => ({setTopicPullRequestDismissed: mocks.dismiss,},}));-vi.mock('../useLinkedPullRequest', () => ({- useLinkedPullRequest: (params: unknown) => {- mocks.legacy(params);- return { confirmed: true, pullRequest: { number: 1 }, refresh: vi.fn() };- },-}));const view = (number: number, extra: Record<string, unknown> = {}) => ({confirmed: true,@@ -60,8 +45,6 @@ const view = (number: number, extra: Record<string, unknown> = {}) => ({const PARAMS = {available: true,- gitPath: '/repo',- isGithub: true,topicId: 't1',workingDirectory: '/repo',};@@ -69,31 +52,12 @@ const PARAMS = {describe('useSidebarPullRequests', () => {beforeEach(() => {vi.clearAllMocks();- mocks.betterCoding = true;- mocks.linked = { enabled: true, primary: undefined, probes: [], views: [] };- });-- it('keeps the branch PR path untouched without the lab', () => {- mocks.betterCoding = false;- mocks.linked = { ...mocks.linked, enabled: false };- const { result } = renderHook(() => useSidebarPullRequests(PARAMS));-- expect(mocks.legacy).toHaveBeenCalledWith(PARAMS);- expect(result.current.pullRequest).toEqual({ number: 1 });- expect(result.current.pullRequests).toBeUndefined();- });-- it('never asks for the branch PR under the lab', () => {- renderHook(() => useSidebarPullRequests(PARAMS));-- expect(mocks.legacy).toHaveBeenCalledWith(- expect.objectContaining({ gitPath: undefined, isGithub: false, snapshot: undefined }),- );+ mocks.linked = { primary: undefined, probes: [], views: [] };});it('lists every linked PR and opens the picked one in the tab', () => {const views = [view(3), view(2), view(9, { localDetail: false })];- mocks.linked = { enabled: true, primary: views[0], probes: [], views };+ mocks.linked = { primary: views[0], probes: [], views };const { result } = renderHook(() => useSidebarPullRequests(PARAMS));expect(result.current.pullRequests).toHaveLength(3);@@ -111,7 +75,7 @@ describe('useSidebarPullRequests', () => {it('locks mutations until the PR is confirmed', () => {const views = [view(3, { confirmed: false })];- mocks.linked = { enabled: true, primary: views[0], probes: [], views };+ mocks.linked = { primary: views[0], probes: [], views };const { result } = renderHook(() => useSidebarPullRequests(PARAMS));expect(result.current.confirmed).toBe(false);@@ -121,7 +85,7 @@ describe('useSidebarPullRequests', () => {it('keeps a confirmed PR locked when the app cannot vouch for it', () => {const views = [view(3, { vouched: false })];- mocks.linked = { enabled: true, primary: views[0], probes: [], views };+ mocks.linked = { primary: views[0], probes: [], views };const { result } = renderHook(() => useSidebarPullRequests(PARAMS));expect(result.current.confirmed).toBe(false);@@ -129,7 +93,7 @@ describe('useSidebarPullRequests', () => {it('removes and links PRs on the topic, then refreshes its list', async () => {const views = [view(3)];- mocks.linked = { enabled: true, primary: views[0], probes: [], views };+ mocks.linked = { primary: views[0], probes: [], views };const { result } = renderHook(() => useSidebarPullRequests(PARAMS));await act(async () => {@@ -156,7 +120,7 @@ describe('useSidebarPullRequests', () => {it('rejects a link or removal the server did not save', async () => {const views = [view(3)];- mocks.linked = { enabled: true, primary: views[0], probes: [], views };+ mocks.linked = { primary: views[0], probes: [], views };mocks.link.mockResolvedValueOnce({ identifier: 'a/b#4', linked: false });mocks.dismiss.mockResolvedValueOnce({ updated: false });const { result } = renderHook(() => useSidebarPullRequests(PARAMS));@@ -170,7 +134,7 @@ describe('useSidebarPullRequests', () => {it('offers no link or removal before the conversation has a topic', () => {const views = [view(3)];- mocks.linked = { enabled: true, primary: views[0], probes: [], views };+ mocks.linked = { primary: views[0], probes: [], views };const { result } = renderHook(() => useSidebarPullRequests({ ...PARAMS, topicId: null }));expect(result.current.linkPullRequest).toBeUndefined();diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/useLinkedPullRequest.ts b/src/features/Conversation/WorkingSidebar/PullRequest/useLinkedPullRequest.tsdeleted file mode 100644index 7da8c08d548..00000000000--- a/src/features/Conversation/WorkingSidebar/PullRequest/useLinkedPullRequest.ts+++ /dev/null@@ -1,114 +0,0 @@-import type { DeviceGitLinkedPullRequest, WorkingDirGithubState } from '@lobechat/types';--import { type GitLinkedPRSummary } from '@/services/git';-import { useFetchGitBranch, useFetchGitLinkedPR } from '@/store/device';--/** The git context the topic recorded for the working directory. */-export interface PullRequestSnapshot {- branch?: string;- github?: WorkingDirGithubState;-}--interface ResolveLinkedPullRequestInput {- /** The working directory is readable here (local machine or a bound device). */- available: boolean;- branch?: { branch?: string; detached?: boolean };- branchConfirmed: boolean;- branchError?: unknown;- linkedPR?: GitLinkedPRSummary;- linkedPRConfirmed: boolean;- linkedPRError?: unknown;- snapshot?: PullRequestSnapshot;-}--/**- * The PR the sidebar shows for the working directory, and whether it may be- * acted on. Persisted rows and the topic snapshot are enough to paint the tab;- * only a PR that this session's branch read and linked-PR lookup both- * confirmed may be mutated — a stale row could otherwise close or merge a PR- * the repository has since moved off.- *- * `confirmError`: the failed read that keeps an unconfirmed PR locked, so the- * pane can say why and retry it.- */-export const resolveLinkedPullRequest = ({- available,- branch,- branchConfirmed,- branchError,- linkedPR,- linkedPRConfirmed,- linkedPRError,- snapshot,-}: ResolveLinkedPullRequestInput): {- confirmError: unknown;- confirmed: boolean;- pullRequest: DeviceGitLinkedPullRequest | null | undefined;-} => {- const snapshotPR =- !branch || (snapshot?.branch === branch.branch && !branch.detached)- ? snapshot?.github?.pullRequest- : undefined;- // A settled empty lookup supersedes the snapshot; failures may keep displaying it.- const pullRequest = available- ? linkedPR?.pullRequestStatus === 'ok'- ? linkedPR.pullRequest- : (linkedPR?.pullRequest ?? snapshotPR)- : undefined;- const confirmed =- !!pullRequest &&- branchConfirmed &&- linkedPRConfirmed &&- linkedPR?.pullRequest?.number === pullRequest.number;- const confirmError = confirmed- ? undefined- : (!branchConfirmed && branchError) || (!linkedPRConfirmed && linkedPRError) || undefined;- return { confirmError, confirmed, pullRequest };-};--/** Branch → linked PR for the Working Sidebar's PR tab. */-export const useLinkedPullRequest = ({- available,- deviceId,- gitPath,- isGithub,- snapshot,-}: {- available: boolean;- deviceId?: string;- /** Set only for a readable GitHub working directory. */- gitPath?: string;- isGithub: boolean;- snapshot?: PullRequestSnapshot;-}) => {- const {- data: branch,- error: branchError,- isConfirmed: branchConfirmed,- mutate: refreshBranch,- } = useFetchGitBranch(deviceId, gitPath);- const {- data: linkedPR,- error: linkedPRError,- isConfirmed: linkedPRConfirmed,- mutate: refresh,- } = useFetchGitLinkedPR(deviceId, gitPath, branch?.branch, isGithub);- return {- ...resolveLinkedPullRequest({- available,- branch,- branchConfirmed,- branchError,- linkedPR,- linkedPRConfirmed,- linkedPRError,- snapshot,- }),- /** Re-run the reads that confirm the PR (branch, then its linked PR). */- onRetryConfirm: () => {- void refreshBranch();- void refresh();- },- refresh,- };-};diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts b/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.tsindex ec32b8e44bc..03340cb6f24 100644--- a/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts+++ b/src/features/Conversation/WorkingSidebar/PullRequest/usePullRequestActions.ts@@ -82,13 +82,6 @@ export const usePullRequestActions = ({await Promise.allSettled([mutateDetail(),mutate(deviceKeys.gitPullRequestActivity(cacheDeviceId, readPath, number)),- mutate(- (key: unknown) =>- Array.isArray(key) &&- key[0] === deviceKeys.gitLinkedPR.root &&- key[1] === cacheDeviceId &&- key[2] === workingDirectory,- ),mutate((key: unknown) =>Array.isArray(key) &&diff --git a/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts b/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.tsindex 60b8048fdf8..2ccd5213987 100644--- a/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts+++ b/src/features/Conversation/WorkingSidebar/PullRequest/useSidebarPullRequests.ts@@ -5,10 +5,6 @@ import { linkManualPullRequest } from '@/features/TopicPullRequests/linkManualPuimport type { TopicPullRequestView } from '@/features/TopicPullRequests/pullRequestView';import { useTopicPullRequests } from '@/features/TopicPullRequests/useTopicPullRequests';import { workService } from '@/services/work';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';--import { type PullRequestSnapshot, useLinkedPullRequest } from './useLinkedPullRequest';export const toLinkedPullRequest = (view: TopicPullRequestView): DeviceGitLinkedPullRequest => ({...(view.ciStatus ? { ciStatus: view.ciStatus } : {}),@@ -21,10 +17,8 @@ export const toLinkedPullRequest = (view: TopicPullRequestView): DeviceGitLinked});/**- * The pull request(s) the Working Sidebar shows. Without Better Coding- * Experience: the PR linked to the working directory's branch, exactly as- * before. With it: every PR the topic's Work rows link (Overview lists them- * all), and the PR tab shows the one picked there — only among PRs the device+ * The pull request(s) the Working Sidebar shows: every PR the topic's Work+ * rows link (Overview lists them all), and the PR tab shows the one picked there — only among PRs the device* read in the working directory's own repository, since the pane reads that* number in that directory. Mutations stay locked until the GitHub App or this* session's device read confirmed the PR.@@ -32,17 +26,9 @@ export const toLinkedPullRequest = (view: TopicPullRequestView): DeviceGitLinkedexport const useSidebarPullRequests = (params: {available: boolean;deviceId?: string;- gitPath?: string;- isGithub: boolean;- snapshot?: PullRequestSnapshot;topicId?: string | null;workingDirectory?: string;}) => {- const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);- // The branch → PR guess is not even asked under the lab.- const legacy = useLinkedPullRequest(- betterCoding ? { ...params, gitPath: undefined, isGithub: false, snapshot: undefined } : params,- );const linked = useTopicPullRequests({deviceId: params.deviceId,path: params.available ? params.workingDirectory : undefined,@@ -81,17 +67,6 @@ export const useSidebarPullRequests = (params: {[topicId],);- if (!linked.enabled) {- return {- ...legacy,- dismissPullRequest: undefined,- linkPullRequest: undefined,- pickPullRequest: undefined,- probes: [],- pullRequests: undefined,- };- }-return {confirmError: undefined,// Mutations need a confirmed read AND a PR the app can vouch for.diff --git a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsxindex 6c50ac2cc9b..9d0f62db9a1 100644--- a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx+++ b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx@@ -42,23 +42,37 @@ const effectiveConfig = vi.hoisted(() => ({}));const platform = vi.hoisted(() => ({ isDesktop: true }));+/** The pull request the topic's Work rows link, as the sidebar reads it. */const linkedPR = vi.hoisted(() => ({number: undefined as number | undefined,branch: 'feature' as string | undefined,- status: undefined as string | undefined,}));vi.mock('@/store/device', async (importOriginal) => ({...(await importOriginal<object>()),useFetchGitBranch: () => ({ data: linkedPR.branch ? { branch: linkedPR.branch } : undefined }),- useFetchGitLinkedPR: () => ({- data: {- pullRequestStatus: linkedPR.status,- pullRequest: linkedPR.number- ? { number: linkedPR.number, state: 'open', url: 'https://github.com/test/repo/pull/1' }- : undefined,- },- }),+}));++vi.mock('@/features/TopicPullRequests/useTopicPullRequests', () => ({+ useTopicPullRequests: () => {+ const views = linkedPR.number+ ? [+ {+ confirmed: true,+ identifier: `test/repo#${linkedPR.number}`,+ isDraft: false,+ localDetail: true,+ number: linkedPR.number,+ repoFullName: 'test/repo',+ state: 'open',+ title: `PR ${linkedPR.number}`,+ url: `https://github.com/test/repo/pull/${linkedPR.number}`,+ vouched: true,+ },+ ]+ : [];+ return { primary: views[0], probes: [], views };+ },}));vi.mock('../PullRequest', async () => {@@ -498,7 +512,6 @@ beforeEach(() => {platform.isDesktop = true;linkedPR.number = undefined;linkedPR.branch = 'feature';- linkedPR.status = undefined;chatStore.topicDataMap = {};chatStore.topicDetailMap = {};filesProps.current = undefined;diff --git a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsxindex 1961a5a0fd0..08ec0f9ba57 100644--- a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx+++ b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx@@ -31,74 +31,6 @@ const { default: PullRequestHeader } = await import('../PullRequest/Header');const { default: PullRequestSections } = await import('../PullRequest/Sections');describe('AgentWorkingSidebar — controlled panel width', () => {- it('opens a scoped saved PR before branch lookup and discards it after authoritative empty lookup', () => {- linkedPR.branch = undefined;- reviewState.workingDirectory = '/repo';- chatStore.activeTopicId = 'topic-pr';- chatStore.topicDetailMap = {- 'topic-pr': {- id: 'topic-pr',- metadata: {- workingDirectoryConfig: {- path: '/repo',- git: {- branch: 'feature',- github: {- pullRequest: {- number: 42,- title: 'Saved PR',- state: 'open',- url: 'https://github.com/test/repo/pull/42',- },- },- },- },- },- },- };- globalStore.status.workingSidebarTab = 'pr';- localStorageState.openTabsByContext = { 'topic:topic-pr': ['pr'] };- const { rerender } = render(<AgentWorkingSidebar />);- expect(screen.getByRole('textbox', { name: 'PR draft' })).toBeInTheDocument();- linkedPR.status = 'ok';- rerender(<AgentWorkingSidebar availableWidth={1200} />);- expect(screen.queryByRole('textbox', { name: 'PR draft' })).not.toBeInTheDocument();- });-- it.each([- { path: '/other', boundDeviceId: undefined },- { path: '/repo', boundDeviceId: 'other-device' },- ])('does not bootstrap a snapshot from another scope: %o', ({ path, boundDeviceId }) => {- linkedPR.branch = undefined;- reviewState.workingDirectory = '/repo';- chatStore.activeTopicId = 'topic-pr';- chatStore.topicDetailMap = {- 'topic-pr': {- id: 'topic-pr',- metadata: {- boundDeviceId,- workingDirectoryConfig: {- path,- git: {- github: {- pullRequest: {- number: 42,- state: 'open',- title: 'Other PR',- url: 'https://github.com/test/repo/pull/42',- },- },- },- },- },- },- };- globalStore.status.workingSidebarTab = 'pr';- localStorageState.openTabsByContext = { 'topic:topic-pr': ['pr'] };- render(<AgentWorkingSidebar />);- expect(screen.queryByRole('textbox', { name: 'PR draft' })).not.toBeInTheDocument();- });-it('resets PR state when the PR number or directory changes', () => {reviewState.repoType = 'github';reviewState.workingDirectory = '/repo';@@ -120,7 +52,6 @@ describe('AgentWorkingSidebar — controlled panel width', () => {reviewState.repoType = 'github';reviewState.workingDirectory = '/repo';linkedPR.number = 42;- linkedPR.status = 'ok';render(<AgentWorkingSidebar />);diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex b725a197a51..e5a733abd89 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -303,7 +303,6 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })// WorkingDirectorySection: a persisted-worktree topic has no matching// `workingDirs` entry, and committing the worktree path as sourcePath would// rewrite the topic's repo source (see that component's comment).- const topicDeviceId = useChatStore((s) => topicSelectors.currentTopicMetadata(s)?.boundDeviceId);const deviceDirs = useDeviceStore(deviceSelectors.getDeviceWorkingDirs(targetDeviceId));const sourceWorkingDirectory = useMemo(() => {if (!workingDirectory) return undefined;@@ -368,14 +367,6 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })});const filesAvailable = !isChatMode && filesDirectory !== undefined;const reviewAvailable = (isLocalExecution || isDeviceMode) && !!workingDirectory && !!repoType;- const snapshotConfig =- (topicDeviceId ? topicDeviceId === targetDeviceId : isLocalExecution) &&- getWorkingDirEffectivePath(topicWorkingDirectoryConfig) === workingDirectory- ? topicWorkingDirectoryConfig- : deviceDirs.find((entry) => getWorkingDirEffectivePath(entry) === workingDirectory);- const isGithub =- repoType === 'github' || (!repoType && !!snapshotConfig?.git?.github?.pullRequest);- const gitPath = filesystemEnvironmentAvailable && isGithub ? workingDirectory : undefined;const {dismissPullRequest,linkPullRequest,@@ -388,9 +379,6 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })} = useSidebarPullRequests({available: filesystemEnvironmentAvailable && !!workingDirectory,deviceId: remoteDeviceId,- gitPath,- isGithub,- snapshot: snapshotConfig?.git,topicId,workingDirectory: sourceWorkingDirectory ?? workingDirectory,});diff --git a/src/features/Settings/conversation/features/Sending.tsx b/src/features/Settings/conversation/features/Sending.tsxindex dd6ec5b0d89..1d6e175c1d4 100644--- a/src/features/Settings/conversation/features/Sending.tsx+++ b/src/features/Settings/conversation/features/Sending.tsx@@ -1,6 +1,7 @@'use client';import { KeyEnum } from '@lobechat/const/hotkeys';+import { DEFAULT_FOLLOW_UP_BEHAVIOR } from '@lobechat/types';import { combineKeys, Flexbox, Hotkey, Select, Switch } from '@lobehub/ui';import { Form, type FormFieldProps, type FormGroupItem, useForm } from '@lobehub/ui/form';import isEqual from 'fast-deep-equal';@@ -13,11 +14,7 @@ import { FORM_STYLE } from '@/const/layoutTokens';import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';import { useSaveState } from '@/hooks/useSaveState';import { useUserStore } from '@/store/user';-import {- labPreferSelectors,- settingsSelectors,- userGeneralSettingsSelectors,-} from '@/store/user/selectors';+import { settingsSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';import { type UserGeneralConfig } from '@/types/user/settings';import { isMobileSurface } from '@/utils/mobileSurface';@@ -52,9 +49,6 @@ const Sending = memo(() => {const general = useUserStore((s) => settingsSelectors.currentSettings(s).general, isEqual);const enablePasteAutoConvert = useUserStore(userGeneralSettingsSelectors.enablePasteAutoConvert);const enableVoiceMessage = useUserStore(userGeneralSettingsSelectors.enableVoiceMessage);- const enableBetterCodingExperience = useUserStore(- labPreferSelectors.enableBetterCodingExperience,- );const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);const { sendKey, setSendKey } = useSendKeyPreference();const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();@@ -86,31 +80,28 @@ const Sending = memo(() => {),};- // Only read while the Better Coding Experience lab is on.- const followUpBehaviorItem: FormFieldProps | undefined = enableBetterCodingExperience- ? {- children: (- <Select- style={{ width: 160 }}- value={general.followUpBehavior ?? 'steer'}- options={[- {- label: t('settingChatAppearance.followUpBehavior.options.queue'),- value: 'queue',- },- {- label: t('settingChatAppearance.followUpBehavior.options.steer'),- value: 'steer',- },- ]}- onChange={(value) => update({ followUpBehavior: value })}- />- ),- desc: t('settingChatAppearance.followUpBehavior.desc'),- label: t('settingChatAppearance.followUpBehavior.title'),- minWidth: undefined,- }- : undefined;+ const followUpBehaviorItem: FormFieldProps = {+ children: (+ <Select+ style={{ width: 160 }}+ value={general.followUpBehavior ?? DEFAULT_FOLLOW_UP_BEHAVIOR}+ options={[+ {+ label: t('settingChatAppearance.followUpBehavior.options.queue'),+ value: 'queue',+ },+ {+ label: t('settingChatAppearance.followUpBehavior.options.steer'),+ value: 'steer',+ },+ ]}+ onChange={(value) => update({ followUpBehavior: value })}+ />+ ),+ desc: t('settingChatAppearance.followUpBehavior.desc'),+ label: t('settingChatAppearance.followUpBehavior.title'),+ minWidth: undefined,+ };const group: FormGroupItem = {children: [diff --git a/src/features/Settings/labs/features.ts b/src/features/Settings/labs/features.tsindex 1492ad6996c..d3f093b7346 100644--- a/src/features/Settings/labs/features.ts+++ b/src/features/Settings/labs/features.ts@@ -17,7 +17,6 @@ type LabFeatureI18nKey =| 'agentGraphConfig'| 'agentIdentity'| 'artifactDeployment'- | 'betterCodingExperience'| 'claudeCodeSdk'| 'codexAppServer'| 'desktopSplitView'@@ -112,12 +111,6 @@ const ALL_LAB_FEATURES: LabFeatureItem[] = [searchKeywords: ['tunnel', 'port forwarding', 'dev server', 'localhost'],stage: 'alpha',},- {- flag: 'enableBetterCodingExperience',- i18nKey: 'betterCodingExperience',- searchKeywords: ['coding', 'code', 'developer', 'programming', 'IDE'],- stage: 'alpha',- },{flag: 'enableProjects',i18nKey: 'projects',diff --git a/src/features/TopicPullRequests/useTopicPullRequests.ts b/src/features/TopicPullRequests/useTopicPullRequests.tsindex 6c6ddcc45fb..47c1f0bede4 100644--- a/src/features/TopicPullRequests/useTopicPullRequests.ts+++ b/src/features/TopicPullRequests/useTopicPullRequests.ts@@ -2,8 +2,6 @@ import { useMemo } from 'react';import { gitPullRequestKey } from '@/store/device/gitReview/projection';import { useGitReviewStore } from '@/store/device/gitReview/store';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';import { useWorkStore, workActions, workSelectors } from '@/store/work';import {@@ -22,8 +20,6 @@ export interface UseTopicPullRequestsParams {}export interface TopicPullRequests {- /** Under Better Coding Experience only; false means "show the old surfaces". */- enabled: boolean;primary?: TopicPullRequestView;/*** Numbers to read on the execution device (mount {@link TopicPullRequestProbes}):@@ -35,17 +31,16 @@ export interface TopicPullRequests {}/**- * The pull requests a topic's Work rows link (Better Coding Experience), each- * resolved to a displayable state. Without the lab — or before a topic exists- * (new conversation) — nothing is read and the list is empty.+ * The pull requests a topic's Work rows link, each resolved to a displayable+ * state. Before a topic exists (new conversation) nothing is read and the list+ * is empty.*/export const useTopicPullRequests = ({deviceId,path,topicId,}: UseTopicPullRequestsParams): TopicPullRequests => {- const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);- const activeTopicId = betterCoding && topicId ? topicId : undefined;+ const activeTopicId = topicId || undefined;workActions.useFetchTopicPullRequests(activeTopicId ? { topicId: activeTopicId } : null);const items = useWorkStore(workSelectors.topicPullRequests(activeTopicId));@@ -65,12 +60,11 @@ export const useTopicPullRequests = ({);});return {- enabled: betterCoding,probes: path? list.map((item) => ({ number: item.number, version: new Date(item.linkedAt).getTime() })): [],primary: pickPrimaryPullRequest(views),views,};- }, [betterCoding, detailEntries, detailMap, deviceId, items, path]);+ }, [detailEntries, detailMap, deviceId, items, path]);};diff --git a/src/libs/swr/keys.frozen.test.ts b/src/libs/swr/keys.frozen.test.tsindex 95472372d3a..afade716806 100644--- a/src/libs/swr/keys.frozen.test.ts+++ b/src/libs/swr/keys.frozen.test.ts@@ -29,7 +29,6 @@ const LEGACY_SWR_KEYS = ['deviceKeys.appUpdateState','deviceKeys.browseDirectory','deviceKeys.cliUpdateState',- 'deviceKeys.gitLinkedPR','deviceKeys.gitPullRequestActivity','deviceKeys.gitPullRequestDetail','deviceKeys.gitPullRequestMergeContext',diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 1fbb5e9d4c7..71d779ab7bb 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -328,16 +328,6 @@ export const deviceKeys = {(workspaceId: string | null, deviceId: string, path?: string, cursor?: string) =>['device:browseDirectory', workspaceId, deviceId, path, cursor] as const,),- gitLinkedPR: def(- 'device:gitLinkedPR',- (deviceId: string, path: string, branch: string, pullRequestNumber?: number) => [- 'device:gitLinkedPR',- deviceId,- path,- branch,- ...(pullRequestNumber === undefined ? [] : [pullRequestNumber]),- ],- ),gitPullRequestDetail: def('device:gitPullRequestDetail',(deviceId: string, path: string, number: number) => [diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsxindex cc2b07fbd0e..6ece33fca37 100644--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx@@ -5,8 +5,6 @@ import { useParams } from 'react-router';import { useClearActiveTopicUnread } from '@/features/Conversation/hooks';import { useTopicCommentDeepLink } from '@/features/TopicComment/useTopicCommentDeepLink';-import { useChatStore } from '@/store/chat';-import { topicSelectors } from '@/store/chat/selectors';import { useChatRouteSync } from './useChatRouteSync';@@ -19,14 +17,8 @@ interface ChatHydrationProps {const ChatHydration: FC<ChatHydrationProps> = memo(({ getConversationPath, getTopicPath }) => {const params = useParams<{ aid?: string; topicId?: string }>();const routeTopicId = params.topicId;- const activeAgentId = useChatStore((s) => s.activeAgentId);- const topicMetadata = useChatStore((s) =>- routeTopicId ? topicSelectors.getTopicById(routeTopicId)(s)?.metadata : undefined,- );- const useFetchTopicLinkedPullRequest = useChatStore((s) => s.useFetchTopicLinkedPullRequest);useClearActiveTopicUnread();- useFetchTopicLinkedPullRequest(activeAgentId ? routeTopicId : undefined, topicMetadata);useTopicCommentDeepLink(routeTopicId);useChatRouteSync({ getConversationPath, getTopicPath });diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.tsindex 4abb738135d..7e88b40d4d2 100644--- a/src/services/electron/heterogeneousAgent.ts+++ b/src/services/electron/heterogeneousAgent.ts@@ -57,9 +57,9 @@ class HeterogeneousAgentService {workspaceId?: string;imageList?: Array<{ id: string; url: string }>;operationId: string;- /** Claude Code permission mode (Better Coding Experience lab); absent allows everything. */+ /** Claude Code permission mode; absent allows everything. */permissionMode?: HeteroPermissionMode;- /** Codex Plan switch (Better Coding Experience lab); absent sends no collaboration mode. */+ /** Codex Plan switch; absent sends no collaboration mode. */collaborationMode?: CodexCollaborationMode;prompt: string;/**@@ -103,7 +103,7 @@ class HeterogeneousAgentService {return this.ipc.heterogeneousAgent.stopBackgroundTask({ sessionId, taskId });}- /** Switch a local Claude Code run's permission mode (Better Coding Experience mode chip). */+ /** Switch a local Claude Code run's permission mode (the composer's mode chip). */async setPermissionMode(sessionId: string, mode: HeteroPermissionMode) {return this.ipc.heterogeneousAgent.setPermissionMode({ mode, sessionId });}diff --git a/src/services/work.test.ts b/src/services/work.test.tsindex cd60de482d3..1633ccbe7cb 100644--- a/src/services/work.test.ts+++ b/src/services/work.test.ts@@ -136,7 +136,7 @@ describe('workService.refreshConversationViews', () => {expect(typeof versionMatcher).toBe('function');expect(versionMatcher(workKeys.versions('w1'))).toBe(true);expect(versionMatcher(workKeys.conversation('t1', 'th1'))).toBe(false);- // The topic's linked pull requests (Better Coding Experience) ride the same scan.+ // The topic's linked pull requests ride the same scan.const prMatcher = mutate.mock.calls[2][0] as (key: unknown) => boolean;expect(prMatcher(topicPullRequestsSync('t1'))).toBe(true);expect(prMatcher(topicPullRequestsSync('t2'))).toBe(false);diff --git a/src/services/work.ts b/src/services/work.tsindex 083b8ba244b..5c453742cf6 100644--- a/src/services/work.ts+++ b/src/services/work.ts@@ -132,12 +132,12 @@ class WorkService {}): Promise<{ failed: number; registered: number; rootOperationId: string | null }> =>lambdaClient.work.registerShellWorksForRun.mutate(params);- /** Better Coding Experience: the pull requests a topic's Work rows link, with App state. */+ /** The pull requests a topic's Work rows link, with App state. */listTopicPullRequests = async (topicId: string): Promise<TopicPullRequestItem[]> =>lambdaClient.work.listTopicPullRequests.query({ topicId });/**- * Better Coding Experience: link the pull requests a `git push` tool call+ * Link the pull requests a `git push` tool call* updated. `pullRequests` is the execution device's `gh pr list --head`* answer; the server re-reads the push itself and prefers the GitHub App.*/@@ -156,7 +156,7 @@ class WorkService {}) => lambdaClient.work.linkPushedPullRequests.mutate(params);/**- * Better Coding Experience: keep a PR on the topic itself — found on its own+ * Keep a PR on the topic itself — found on its own* branch (`branch`) or linked by hand (`manual`). Display-only links: they* never feed the SCM links that accept deliveries or wake agents.*/@@ -170,7 +170,7 @@ class WorkService {}): Promise<{ identifier: string; linked: boolean }> =>lambdaClient.work.linkTopicPullRequest.mutate(params);- /** Better Coding Experience: remove a PR from the topic's lists, or bring it back. */+ /** Remove a PR from the topic's lists, or bring it back. */setTopicPullRequestDismissed = async (params: {dismissed: boolean;identifier: string;diff --git a/src/store/chat/heteroPermissionMode.test.ts b/src/store/chat/heteroPermissionMode.test.tsindex dbbf85ac0fd..01623a9af0b 100644--- a/src/store/chat/heteroPermissionMode.test.ts+++ b/src/store/chat/heteroPermissionMode.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import {applyPermissionModeReport,@@ -11,13 +11,6 @@ import {setPendingHeteroPermissionMode,} from './heteroPermissionMode';-const lab = vi.hoisted(() => ({ on: true }));--vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));-vi.mock('@/store/user/selectors', () => ({- labPreferSelectors: { enableBetterCodingExperience: () => lab.on },-}));-const storeWith = (metadata: Record<string, unknown> | undefined) => {const updateTopicMetadata = vi.fn(async () => {});const internal_dispatchTopic = vi.fn();@@ -30,18 +23,10 @@ const storeWith = (metadata: Record<string, unknown> | undefined) => {};describe('heteroPermissionMode (renderer)', () => {- beforeEach(() => {- lab.on = true;- });-- it('starts local Claude Code runs in the topic mode only with the lab on', () => {+ it('starts local Claude Code runs in the topic mode, bypassPermissions by default', () => {expect(resolveRunPermissionMode('claude-code', { heteroPermissionMode: 'plan' })).toBe('plan');expect(resolveRunPermissionMode('claude-code', {})).toBe('bypassPermissions');expect(resolveRunPermissionMode('codex', { heteroPermissionMode: 'plan' })).toBeUndefined();- lab.on = false;- expect(- resolveRunPermissionMode('claude-code', { heteroPermissionMode: 'plan' }),- ).toBeUndefined();});it('hands the new-topic chip mode to the topic it creates', () => {diff --git a/src/store/chat/heteroPermissionMode.ts b/src/store/chat/heteroPermissionMode.tsindex 474e315e230..c2955b541cf 100644--- a/src/store/chat/heteroPermissionMode.ts+++ b/src/store/chat/heteroPermissionMode.ts@@ -11,11 +11,9 @@ import { DEFAULT_HETERO_PERMISSION_MODE, isHeteroPermissionMode } from '@lobechaimport { topicSelectors } from '@/store/chat/selectors';import type { ChatStore } from '@/store/chat/store';-import { getUserStoreState } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';/*- * Claude Code permission modes (Better Coding Experience lab), renderer side.+ * Claude Code permission modes, renderer side.** A topic's mode lives in `metadata.heteroPermissionMode`: the composer chip* writes it, every run starts in it, and Claude Code's own reports (leaving@@ -24,10 +22,9 @@ import { labPreferSelectors } from '@/store/user/selectors';* `takePendingHeteroPermissionMode`).*/-/** Whether runs of `agentType` have permission modes: Claude Code with the lab on. */+/** Whether runs of `agentType` have permission modes: Claude Code only. */export const hasHeteroPermissionModes = (agentType: string | undefined): boolean =>- agentType === 'claude-code' &&- labPreferSelectors.enableBetterCodingExperience(getUserStoreState());+ agentType === 'claude-code';/** The mode a topic's runs start in; the default when it has none. */export const readTopicPermissionMode = (@@ -37,7 +34,7 @@ export const readTopicPermissionMode = (return isHeteroPermissionMode(mode) ? mode : DEFAULT_HETERO_PERMISSION_MODE;};-/** The mode a local run starts in, or undefined to allow every action (lab off, other agents). */+/** The mode a local run starts in, or undefined to allow every action (other agents). */export const resolveRunPermissionMode = (agentType: string | undefined,metadata: ChatTopicMetadata | null | undefined,@@ -58,8 +55,8 @@ export const setPendingHeteroPermissionMode = (/*** Metadata a new Claude Code topic is born with: the mode its chip showed.- * Empty when no chip showed one (the lab off, another agent, a send from- * elsewhere), so the topic starts in the default.+ * Empty when no chip showed one (another agent, a send from elsewhere), so+ * the topic starts in the default.*/export const pendingHeteroPermissionModeMetadata = (agentId: string,diff --git a/src/store/chat/heteroPlanMode.test.ts b/src/store/chat/heteroPlanMode.test.tsindex dfd47037534..cfa1f2beb65 100644--- a/src/store/chat/heteroPlanMode.test.ts+++ b/src/store/chat/heteroPlanMode.test.ts@@ -10,12 +10,11 @@ import {shouldShowCodexPlanDecision,} from './heteroPlanMode';-const lab = vi.hoisted(() => ({ appServer: true, betterCoding: true }));+const lab = vi.hoisted(() => ({ appServer: true }));vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));vi.mock('@/store/user/selectors', () => ({labPreferSelectors: {- enableBetterCodingExperience: () => lab.betterCoding,enableCodexAppServer: () => lab.appServer,},}));@@ -34,7 +33,6 @@ const storeWith = (metadata: Record<string, unknown> | undefined) => {describe('resolveRunCollaborationMode (local runs)', () => {beforeEach(() => {lab.appServer = true;- lab.betterCoding = true;});it('sends nothing for a topic that never turned Plan on, or another agent', () => {@@ -47,23 +45,18 @@ describe('resolveRunCollaborationMode (local runs)', () => {expect(resolveRunCollaborationMode('codex', { heteroPlanMode: false })).toBe('default');});- it('sends nothing when either lab is off', () => {- for (const off of ['appServer', 'betterCoding'] as const) {- lab.appServer = true;- lab.betterCoding = true;- lab[off] = false;- expect(resolveRunCollaborationMode('codex', { heteroPlanMode: true })).toBeUndefined();- }+ it('sends nothing with the app-server lab off', () => {+ lab.appServer = false;+ expect(resolveRunCollaborationMode('codex', { heteroPlanMode: true })).toBeUndefined();});});describe('pendingHeteroPlanModeMetadata (new topics)', () => {beforeEach(() => {lab.appServer = true;- lab.betterCoding = true;});- it('hands over the switch the composer showed, off included, with the labs on', () => {+ it('hands over the switch the composer showed, off included, with the app-server lab on', () => {setPendingHeteroPlanMode('agt', false);expect(pendingHeteroPlanModeMetadata('agt', 'codex')).toEqual({ heteroPlanMode: false });setPendingHeteroPlanMode('agt', true);@@ -132,7 +125,6 @@ describe('shouldShowCodexPlanDecision', () => {beforeEach(() => {lab.appServer = true;- lab.betterCoding = true;});it('shows under the latest plan once the topic is idle with Plan on', () => {@@ -160,7 +152,7 @@ describe('shouldShowCodexPlanDecision', () => {expect(show({ messages: [...messages, plan('p2')] })).toBe(false);});- it('hides with either lab off', () => {+ it('hides with the app-server lab off', () => {lab.appServer = false;expect(show()).toBe(false);});diff --git a/src/store/chat/heteroPlanMode.ts b/src/store/chat/heteroPlanMode.tsindex bd037073bf1..e8fda891fd4 100644--- a/src/store/chat/heteroPlanMode.ts+++ b/src/store/chat/heteroPlanMode.ts@@ -12,7 +12,7 @@ import { getUserStoreState } from '@/store/user';import { labPreferSelectors } from '@/store/user/selectors';/*- * Codex Plan switch (Better Coding Experience lab), renderer side.+ * Codex Plan switch, renderer side.** A topic's switch lives in `metadata.heteroPlanMode`: absent until the user* first turns it on, so a topic that never did sends no collaboration mode at@@ -21,18 +21,13 @@ import { labPreferSelectors } from '@/store/user/selectors';* switch, or Execute plan under a plan).*/-/** Whether the Plan switch applies at all: both labs on (it needs the native app-server). */-export const isCodexPlanModeEnabled = (): boolean => {- const state = getUserStoreState();- return (- labPreferSelectors.enableBetterCodingExperience(state) &&- labPreferSelectors.enableCodexAppServer(state)- );-};+/** Whether the Plan switch applies at all: it needs the native app-server (its lab on). */+export const isCodexPlanModeEnabled = (): boolean =>+ labPreferSelectors.enableCodexAppServer(getUserStoreState());/*** The collaboration mode a local Codex run sends, or undefined to send none- * (another agent, a topic that never turned Plan on, a lab off).+ * (another agent, a topic that never turned Plan on, the app-server lab off).*/export const resolveRunCollaborationMode = (agentType: string | undefined,diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.backgroundTask.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.backgroundTask.test.tsindex 7ed46a08168..e339e43b5bb 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.backgroundTask.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.backgroundTask.test.ts@@ -18,7 +18,7 @@ import {setupIpcCapture,} from './heterogeneousAgentExecutor.testUtils';-const followUp = vi.hoisted(() => ({ mode: 'queue' as 'legacy' | 'queue' | 'steer' }));+const followUp = vi.hoisted(() => ({ mode: 'queue' as 'queue' | 'steer' }));vi.mock('../lifecycle/followUpMode', () => ({ getFollowUpMode: () => followUp.mode }));const mockSendPrompt = vi.fn();@@ -183,21 +183,18 @@ describe('heterogeneousAgentExecutor background tasks', () => {expect(getLocalBackgroundTaskStopper(defaultParams.operationId)).toBeUndefined();});- it.each(['queue', 'legacy'] as const)(- 'offers a stop for a CLI run in %s mode, whose input stays open though nothing is steered',- async (mode) => {- followUp.mode = mode;- await withSdkLab(false, () =>- executeHeterogeneousAgent(() => createMockStore(), defaultParams),- );+ it('offers a stop for a CLI run in Queue mode, whose input stays open though nothing is steered', async () => {+ followUp.mode = 'queue';+ await withSdkLab(false, () =>+ executeHeterogeneousAgent(() => createMockStore(), defaultParams),+ );- expect(stopperDuringRun).toBeDefined();- mockStopBackgroundTask.mockResolvedValue(undefined);- await stopperDuringRun!('bys1w0wxo');- expect(mockStopBackgroundTask).toHaveBeenCalledWith('ipc-sess-1', 'bys1w0wxo');- expect(getLocalBackgroundTaskStopper(defaultParams.operationId)).toBeUndefined();- },- );+ expect(stopperDuringRun).toBeDefined();+ mockStopBackgroundTask.mockResolvedValue(undefined);+ await stopperDuringRun!('bys1w0wxo');+ expect(mockStopBackgroundTask).toHaveBeenCalledWith('ipc-sess-1', 'bys1w0wxo');+ expect(getLocalBackgroundTaskStopper(defaultParams.operationId)).toBeUndefined();+ });it('offers a stop for a CLI run in Steer mode', async () => {followUp.mode = 'steer';diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.followUp.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.followUp.test.tsindex 7e3882a7ab8..f609b2aeb1f 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.followUp.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.followUp.test.ts@@ -13,7 +13,7 @@ import { messageMapKey } from '../../../../utils/messageMapKey';import { TEST_CONTENT, TEST_IDS } from './fixtures';import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';-const mode = vi.hoisted(() => ({ value: 'legacy' as 'legacy' | 'queue' | 'steer' }));+const mode = vi.hoisted(() => ({ value: 'steer' as 'queue' | 'steer' }));vi.mock('../lifecycle/followUpMode', () => ({ getFollowUpMode: () => mode.value }));vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),@@ -86,8 +86,8 @@ const firstStepSeesQueue = async () => {};describe('client run and the Follow-up behavior', () => {- it('hands the turn back for queued messages on the legacy behavior', async () => {- mode.value = 'legacy';+ it('hands the turn back for queued messages in Steer mode', async () => {+ mode.value = 'steer';await expect(firstStepSeesQueue()).resolves.toBe(true);});diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/queuedFollowUp.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/queuedFollowUp.test.tsindex 1054f41d04a..1ab7922bb0f 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/queuedFollowUp.test.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/queuedFollowUp.test.ts@@ -5,7 +5,7 @@ import type { ChatStore } from '@/store/chat/store';import { drainQueuedTurn, findOrphanedQueueKey, scheduleQueuedFollowUp } from '../queuedFollowUp';-const mode = vi.hoisted(() => ({ value: 'legacy' as 'legacy' | 'queue' | 'steer' }));+const mode = vi.hoisted(() => ({ value: 'steer' as 'queue' | 'steer' }));vi.mock('../followUpMode', () => ({ getFollowUpMode: () => mode.value }));const queued = (@@ -65,8 +65,8 @@ describe('scheduleQueuedFollowUp', () => {const context = { agentId: 'agent-1', topicId: 'topic-1' };- it('merges everything queued into one send on the legacy behavior', () => {- mode.value = 'legacy';+ it('merges everything queued into one send in Steer mode', () => {+ mode.value = 'steer';const { get, store } = createStore([queued('q1', 'first'), queued('q2', 'second')]);scheduleQueuedFollowUp(get, context, 'op-1');diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/snapshotWorkingDirGit.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/snapshotWorkingDirGit.test.tsindex 02192769ee6..afb6a6bf97d 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/snapshotWorkingDirGit.test.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/__tests__/snapshotWorkingDirGit.test.ts@@ -17,13 +17,11 @@ vi.mock('@lobechat/const', async (importOriginal) => {const gitMocks = vi.hoisted(() => ({getGitBranch: vi.fn(),- getLinkedPullRequest: vi.fn(),}));vi.mock('@/services/git', () => ({gitService: {getGitBranch: gitMocks.getGitBranch,- getLinkedPullRequest: gitMocks.getLinkedPullRequest,},}));@@ -77,13 +75,6 @@ vi.mock('../../../../topic/selectors', () => ({},}));-const labMocks = vi.hoisted(() => ({ betterCoding: false }));--vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));-vi.mock('@/store/user/selectors', () => ({- labPreferSelectors: { enableBetterCodingExperience: () => labMocks.betterCoding },-}));-const PR = {ciStatus: 'pending' as const,number: 123,@@ -111,19 +102,22 @@ const makeGet = () => {beforeEach(() => {vi.clearAllMocks();- labMocks.betterCoding = false;mockConstEnv.isDesktop = true;env.currentDeviceId = undefined;env.targetDeviceId = undefined;deviceMocks.workingDirs = [];electronGitMocks.detectRepoType.mockResolvedValue(undefined);gitMocks.getGitBranch.mockResolvedValue({ branch: 'fix/remote-review', detached: false });- gitMocks.getLinkedPullRequest.mockResolvedValue({ pullRequest: PR, pullRequestStatus: 'ok' });});describe('snapshotTopicWorkingDirGit', () => {- it('snapshots the live branch + linked PR onto the topic config', async () => {+ it('records the branch and its remote ref, never a PR guessed for the branch', async () => {topicMocks.getTopicById.mockReturnValue(githubTopic);+ gitMocks.getGitBranch.mockResolvedValue({+ branch: 'fix/remote-review',+ detached: false,+ upstream: { branch: 'fix/remote-review', remote: 'origin' },+ });const { get, updateTopicMetadata } = makeGet();await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });@@ -132,8 +126,8 @@ describe('snapshotTopicWorkingDirGit', () => {workingDirectoryConfig: {git: {branch: 'fix/remote-review',- github: { pullRequest: PR, pullRequestStatus: 'ok' },isWorktree: false,+ upstream: { branch: 'fix/remote-review', remote: 'origin' },},path: '/repo',repoType: 'github',@@ -152,11 +146,7 @@ describe('snapshotTopicWorkingDirGit', () => {expect(updateTopicMetadata).toHaveBeenCalledWith('topic-1', {workingDirectoryConfig: {- git: {- branch: 'fix/remote-review',- github: { pullRequest: PR, pullRequestStatus: 'ok' },- isWorktree: false,- },+ git: { branch: 'fix/remote-review', isWorktree: false },path: '/repo',repoType: 'github',},@@ -205,14 +195,13 @@ describe('snapshotTopicWorkingDirGit', () => {expect(updateTopicMetadata).not.toHaveBeenCalled();});- it('leaves the prior snapshot on a detached HEAD (no branch to query)', async () => {+ it('leaves the prior snapshot on a detached HEAD (no branch to record)', async () => {topicMocks.getTopicById.mockReturnValue(githubTopic);gitMocks.getGitBranch.mockResolvedValue({ branch: 'abc1234', detached: true });const { get, updateTopicMetadata } = makeGet();await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });- expect(gitMocks.getLinkedPullRequest).not.toHaveBeenCalled();expect(updateTopicMetadata).not.toHaveBeenCalled();});@@ -220,11 +209,7 @@ describe('snapshotTopicWorkingDirGit', () => {topicMocks.getTopicById.mockReturnValue({metadata: {workingDirectoryConfig: {- git: {- branch: 'fix/remote-review',- github: { pullRequest: PR, pullRequestStatus: 'ok' },- isWorktree: false,- },+ git: { branch: 'fix/remote-review', isWorktree: false },path: '/repo',repoType: 'github',},@@ -247,37 +232,6 @@ describe('snapshotTopicWorkingDirGit', () => {expect(gitMocks.getGitBranch).not.toHaveBeenCalled();expect(updateTopicMetadata).not.toHaveBeenCalled();});-});--describe('snapshotTopicWorkingDirGit — Better Coding Experience', () => {- beforeEach(() => {- labMocks.betterCoding = true;- });-- it('records the branch and its remote ref without asking gh for a PR', async () => {- topicMocks.getTopicById.mockReturnValue(githubTopic);- gitMocks.getGitBranch.mockResolvedValue({- branch: 'fix/remote-review',- detached: false,- upstream: { branch: 'fix/remote-review', remote: 'origin' },- });- const { get, updateTopicMetadata } = makeGet();-- await snapshotTopicWorkingDirGit(get, { agentId: 'agent-1', topicId: 'topic-1' });-- expect(gitMocks.getLinkedPullRequest).not.toHaveBeenCalled();- expect(updateTopicMetadata).toHaveBeenCalledWith('topic-1', {- workingDirectoryConfig: {- git: {- branch: 'fix/remote-review',- isWorktree: false,- upstream: { branch: 'fix/remote-review', remote: 'origin' },- },- path: '/repo',- repoType: 'github',- },- });- });it('drops a recorded PR once the branch moved, keeps it while it stays', async () => {const recorded = {diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.pullRequests.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.pullRequests.test.tsindex a8122557f04..93a3d6b78ff 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.pullRequests.test.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.pullRequests.test.ts@@ -7,7 +7,6 @@ import { messageMapKey } from '../../../../utils/messageMapKey';import { buildRunLifecycle } from './buildRunLifecycle';const mocks = vi.hoisted(() => ({- betterCoding: true,linkOwnBranchPullRequest: vi.fn(async () => {}),refreshTopicPullRequests: vi.fn(async () => {}),}));@@ -18,17 +17,6 @@ vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequestvi.mock('@/services/work', () => ({workService: { refreshTopicPullRequests: mocks.refreshTopicPullRequests },}));-// Partial: the queued follow-up path reads other user selectors (follow-up mode).-vi.mock('@/store/user/selectors', async (importOriginal) => {- const actual = await importOriginal<any>();- return {- ...actual,- labPreferSelectors: {- ...actual.labPreferSelectors,- enableBetterCodingExperience: () => mocks.betterCoding,- },- };-});vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),}));@@ -77,7 +65,6 @@ const complete = (get: () => ChatStore, runtimeStatus: 'done' | 'error' = 'done'describe('buildRunLifecycle.completeRun — topic pull requests', () => {beforeEach(() => {vi.clearAllMocks();- mocks.betterCoding = true;});it('looks up the own-branch PR even when a queued follow-up takes over', async () => {@@ -91,12 +78,10 @@ describe('buildRunLifecycle.completeRun — topic pull requests', () => {});});- it('skips the lookup for a failed run and while the lab is off', async () => {+ it('skips the lookup for a failed run', async () => {await complete(makeStore(false), 'error');- mocks.betterCoding = false;- await complete(makeStore(false));expect(mocks.linkOwnBranchPullRequest).not.toHaveBeenCalled();- expect(mocks.refreshTopicPullRequests).toHaveBeenCalledTimes(2);+ expect(mocks.refreshTopicPullRequests).toHaveBeenCalledTimes(1);});});diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.tsindex 1e05a859b21..32f0d9c829d 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts@@ -19,8 +19,6 @@ import {hasCompletedAssistantText,isAudioOnlyFirstUserMessage,} from '@/store/chat/utils/topicTitle';-import { getUserStoreState } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';import { toTitleText } from '@/utils/markdownToTxt';import { messageMapKey } from '../../../../utils/messageMapKey';@@ -404,17 +402,12 @@ export const buildRunLifecycle = (// Same for the topic's linked PRs: a queued follow-up skips the// completion notification, not these. The run's gh / push commands were// linked by the completion Work scan before the run reported its end; only- // a mounted list (Better Coding Experience PR chip / sidebar) refetches.+ // a mounted list (the PR chip / sidebar) refetches.if (adapter.runScope !== 'sub_agent') {void workService.refreshTopicPullRequests(topicId).catch(() => {});// A PR someone opened on the topic's own branch — looked up before a// queued turn can move the topic off that branch.- if (- disposition === 'success' &&- topicId &&- agentId &&- labPreferSelectors.enableBetterCodingExperience(getUserStoreState())- )+ if (disposition === 'success' && topicId && agentId)void linkOwnBranchPullRequest(get, { agentId, topicId });}diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/followUpMode.ts b/src/store/chat/slices/agentRun/actions/lifecycle/followUpMode.tsindex 83be3c86e5b..f936e1c2c17 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/followUpMode.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/followUpMode.ts@@ -1,4 +1,4 @@-import type { FollowUpMode } from '@lobechat/types';+import type { FollowUpBehavior } from '@lobechat/types';import { getUserStoreState } from '@/store/user';import { userGeneralSettingsSelectors } from '@/store/user/selectors';@@ -7,5 +7,5 @@ import { userGeneralSettingsSelectors } from '@/store/user/selectors';* The user's Follow-up behavior in effect now: what a message sent while a run* is going does. Read at each decision, so a change applies to the next one.*/-export const getFollowUpMode = (): FollowUpMode =>+export const getFollowUpMode = (): FollowUpBehavior =>userGeneralSettingsSelectors.followUpBehavior(getUserStoreState());diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest.ts b/src/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest.tsindex 39c13b2c75b..03b04d49d87 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/linkOwnBranchPullRequest.ts@@ -13,7 +13,7 @@ import { topicSelectors } from '../../../topic/selectors';const sameRepo = (a?: string, b?: string) => !!a && !!b && a.toLowerCase() === b.toLowerCase();/**- * At the end of a run (Better Coding Experience), link the open PR of the+ * At the end of a run, link the open PR of the* branch the topic CREATED — its first-send worktree branch, or one its agent* made — when someone opened it outside the agent's commands (on GitHub, from* another tool). Never for a branch the topic merely switched to: that is thediff --git a/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts b/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.tsindex 842885a3682..f63dacc4984 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/snapshotWorkingDirGit.ts@@ -6,13 +6,10 @@ import { gitService } from '@/services/git';import type { ChatStore } from '@/store/chat/store';import {canReadTopicGitTransport,- mergeWorkingDirGithubState,+ mergeWorkingDirGitBranch,resolveTopicGitTransport,- toWorkingDirGithubState,} from '@/store/chat/utils/topicWorkingDirGit';import { deviceSelectors, getDeviceStoreState } from '@/store/device';-import { getUserStoreState } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';import { topicSelectors } from '../../../topic/selectors';@@ -22,7 +19,7 @@ import { topicSelectors } from '../../../topic/selectors';* (local machine only) a filesystem probe. Deliberately NOT read off the topic's* stored `workingDirectoryConfig.repoType`: legacy topics persist only* `workingDirectory` with no config, so a config-based gate would skip them and- * never refresh their branch/PR snapshot.+ * never refresh their branch snapshot.*/const resolveRepoType = async (params: {isLocalDevice: boolean;@@ -40,10 +37,10 @@ const resolveRepoType = async (params: {};/**- * Capture the working directory's live branch + linked PR onto the topic's- * `workingDirectoryConfig` at SEND time.+ * Capture the working directory's live branch and its remote ref onto the+ * topic's `workingDirectoryConfig` at SEND time.*- * This is the sole writer of the branch/PR snapshot into topic metadata. It used+ * This is the sole send-time writer of the branch snapshot into topic metadata. It used* to live as a reactive effect in the ControlBar's `GitStatus`, but that fired on* every mount — so merely OPENING a topic re-stamped it with whatever branch the* shared working directory happened to be on, clobbering the historical snapshot.@@ -51,8 +48,8 @@ const resolveRepoType = async (params: {* chat branch reflects the last-used active branch; sending a message updates* it") and leaves `GitStatus` a pure live display of the current directory.*- * Fire-and-forget: the `gh pr list` leg is slow (8s timeout), so callers must not- * await it on the send path. It only ever patches topic metadata, idempotently.+ * Fire-and-forget: the device reads may be slow, so callers must not await it on+ * the send path. It only ever patches topic metadata, idempotently.*/export const snapshotTopicWorkingDirGit = async (get: () => ChatStore,@@ -71,8 +68,8 @@ export const snapshotTopicWorkingDirGit = async (// a remote read needs a `deviceId`. Neither → nothing to probe.if (!canReadTopicGitTransport({ deviceId })) return;- // Branch/PR snapshot is only meaningful for a GitHub repo — mirror GitStatus's- // `isGithub` gate (non-github repos never show a PR chip). Resolve it live (the+ // The branch snapshot is only kept for a GitHub repo — mirror GitStatus's+ // `isGithub` gate. Resolve it live (the// config's own `repoType` may be absent on legacy topics); the stored value is// still a valid fast path when present.const repoType =@@ -85,24 +82,14 @@ export const snapshotTopicWorkingDirGit = async (// No branch ref to query (unprobed / detached HEAD) → leave the prior snapshot.if (!branch || detached) return;- // Better Coding Experience links PRs only through the agent's own commands- // (server Work rows), so the send records the branch and its remote ref but- // no longer asks `gh` which PR the branch has.- const betterCoding = labPreferSelectors.enableBetterCodingExperience(getUserStoreState());- const prData = betterCoding- ? undefined- : await gitService.getLinkedPullRequest({ branch, deviceId, path });- const github = toWorkingDirGithubState(prData);- if (!github && !betterCoding) return;-- const nextConfig = mergeWorkingDirGithubState({+ // PRs reach the topic only through the agent's own commands (server Work+ // rows), so the send records the branch and its remote ref, never which PR+ // `gh` guesses for the branch.+ const nextConfig = mergeWorkingDirGitBranch({branch,currentConfig,- github,path,- // The PR lookup's ref outranks the branch read's: it carries the PR's own head- // ref, and it is the only one that lands when the push left no local trace.- upstream: prData?.upstream ?? branchInfo?.upstream,+ upstream: branchInfo?.upstream,});if (isEqual(currentConfig, nextConfig)) return;diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 43b497a223f..e8359829e9e 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -2383,7 +2383,7 @@ export const executeHeterogeneousAgent = async (const sendResult = await heterogeneousAgentService.sendPrompt({agentId: context.agentId,assistantMessageId,- // The Codex Plan switch (Better Coding Experience lab).+ // The Codex Plan switch.collaborationMode: resolveRunCollaborationMode(adapterType, runTopicMetadata),imageList,userId: userProfileSelectors.userId(getUserStoreState()),diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.test.tsindex 8348e5dc860..8249e8ebd89 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.test.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.test.ts@@ -11,7 +11,7 @@ vi.mock('@/services/electron/heterogeneousAgent', () => ({heterogeneousAgentService: { steerSession: vi.fn() },}));vi.mock('@/services/message', () => ({ messageService: { createMessage: vi.fn() } }));-const mode = vi.hoisted(() => ({ value: 'steer' as 'legacy' | 'queue' | 'steer' }));+const mode = vi.hoisted(() => ({ value: 'steer' as 'queue' | 'steer' }));vi.mock('../../lifecycle/followUpMode', () => ({ getFollowUpMode: () => mode.value }));const queued = (@@ -370,9 +370,4 @@ describe('startLocalSteer', () => {expect(cc).toBeDefined();cc?.settle();});-- it('does nothing with the lab off', () => {- mode.value = 'legacy';- expect(start('codex')).toBeUndefined();- });});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.tsindex bd0ff7af8e6..03fd44fc416 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/localSteer.ts@@ -310,7 +310,6 @@ export const startLocalSteer = (},): LocalSteer | undefined => {const mode = getFollowUpMode();- if (mode === 'legacy') return;const { contextKey, get, operationId } = options;if (!supportsLocalSteer(options.agentType, { codexAppServer: options.codexAppServer })) {diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 1c1276e218d..ae6b04f29c0 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -3654,159 +3654,6 @@ describe('topic action', () => {});});- describe('internal_updateTopicLinkedPullRequest', () => {- const agentId = 'agent-1';- const topicId = 'topic-1';- const branch = 'fix/topic-running';- const path = '/repo';- const key = topicMapKey({ agentId });- const stalePR = {- number: 123,- state: 'OPEN',- title: 'fix: stop stale running topics',- url: 'https://github.com/lobehub/lobehub/pull/123',- };- const mergedPR = {- ...stalePR,- mergedAt: '2026-07-07T09:00:00Z',- state: 'MERGED',- };-- const setupTopic = (- pullRequest: typeof stalePR | null = stalePR,- pullRequestStatus: 'error' | 'gh-missing' | 'ok' = 'ok',- ) => {- const topic: ChatTopic = {- createdAt: Date.now(),- favorite: false,- id: topicId,- metadata: {- workingDirectory: path,- workingDirectoryConfig: {- git: {- branch,- github: { pullRequest, pullRequestStatus },- isWorktree: false,- },- path,- repoType: 'github',- },- },- sessionId: agentId,- title: 'Topic',- updatedAt: Date.now(),- };-- useChatStore.setState({- activeAgentId: agentId,- topicDataMap: {- [key]: singleTopicPage(topic),- },- });- };-- it('silently patches the topic with the latest merged PR state', async () => {- const { result } = renderHook(() => useChatStore());- setupTopic();- const updateTopicMetadataMock = vi- .spyOn(topicService, 'updateTopicMetadata')- .mockResolvedValue(undefined as never);-- await act(async () => {- await result.current.internal_updateTopicLinkedPullRequest(- { branch, path, pullRequestNumber: 123, topicId },- { pullRequest: mergedPR, pullRequestStatus: 'ok' },- );- });-- const updatedTopic = useChatStore.getState().topicDataMap[key]!.items[0]!;- expect(updatedTopic.metadata?.workingDirectoryConfig?.git?.github).toEqual({- pullRequest: mergedPR,- pullRequestStatus: 'ok',- });- expect(updateTopicMetadataMock).toHaveBeenCalledWith(topicId, {- workingDirectoryConfig: {- git: {- branch,- github: { pullRequest: mergedPR, pullRequestStatus: 'ok' },- isWorktree: false,- },- path,- repoType: 'github',- },- });- });-- it('updates empty PR metadata when no existing PR number is anchored', async () => {- const { result } = renderHook(() => useChatStore());- setupTopic(null, 'error');- const updateTopicMetadataMock = vi- .spyOn(topicService, 'updateTopicMetadata')- .mockResolvedValue(undefined as never);-- await act(async () => {- await result.current.internal_updateTopicLinkedPullRequest(- { branch, path, topicId },- { pullRequest: null, pullRequestStatus: 'ok' },- );- });-- expect(- useChatStore.getState().topicDataMap[key]!.items[0]!.metadata?.workingDirectoryConfig?.git- ?.github,- ).toEqual({ pullRequest: null, pullRequestStatus: 'ok' });- expect(updateTopicMetadataMock).toHaveBeenCalledTimes(1);- });-- it('keeps the existing PR snapshot when lookup returns a different PR number', async () => {- const { result } = renderHook(() => useChatStore());- setupTopic();- const updateTopicMetadataMock = vi- .spyOn(topicService, 'updateTopicMetadata')- .mockResolvedValue(undefined as never);-- await act(async () => {- await result.current.internal_updateTopicLinkedPullRequest(- { branch, path, pullRequestNumber: 123, topicId },- {- pullRequest: {- ...mergedPR,- number: 456,- url: 'https://github.com/lobehub/lobehub/pull/456',- },- pullRequestStatus: 'ok',- },- );- });-- expect(updateTopicMetadataMock).not.toHaveBeenCalled();- expect(- useChatStore.getState().topicDataMap[key]!.items[0]!.metadata?.workingDirectoryConfig?.git- ?.github,- ).toEqual({ pullRequest: stalePR, pullRequestStatus: 'ok' });- });-- it('keeps the existing PR snapshot when gh is unavailable', async () => {- const { result } = renderHook(() => useChatStore());- setupTopic();- const updateTopicMetadataMock = vi- .spyOn(topicService, 'updateTopicMetadata')- .mockResolvedValue(undefined as never);-- await act(async () => {- await result.current.internal_updateTopicLinkedPullRequest(- { branch, path, topicId },- { ghMissing: true, pullRequest: null, pullRequestStatus: 'gh-missing' },- );- });-- expect(updateTopicMetadataMock).not.toHaveBeenCalled();- expect(- useChatStore.getState().topicDataMap[key]!.items[0]!.metadata?.workingDirectoryConfig?.git- ?.github,- ).toEqual({ pullRequest: stalePR, pullRequestStatus: 'ok' });- });- });describe('optimistic topic preservation across refetches', () => {const agentId = 'agent-1';const key = topicMapKey({ agentId });diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex eced616c1d8..66acad23cfe 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -35,7 +35,6 @@ import { mutate } from '@/libs/swr';import { cronKeys, topicKeys } from '@/libs/swr/keys';import { getCacheScope } from '@/libs/swr/useCacheScope';import { aiChatService } from '@/services/aiChat';-import { type GitLinkedPRSummary } from '@/services/git';import { messageService } from '@/services/message';import type { TopicBatchDeleteScope } from '@/services/topic';import { topicService } from '@/services/topic';@@ -48,14 +47,6 @@ import {isAudioOnlyFirstUserMessage,normalizeTopicTitleMessages,} from '@/store/chat/utils/topicTitle';-import {- canReadTopicGitTransport,- getTopicLinkedPullRequestBase,- isSuccessfulLinkedPullRequestLookup,- mergeWorkingDirGithubState,- resolveTopicGitTransport,- toWorkingDirGithubState,-} from '@/store/chat/utils/topicWorkingDirGit';import { useGlobalStore } from '@/store/global';import { getHomeStoreState } from '@/store/home';import { type StoreSetter } from '@/store/types';@@ -83,10 +74,6 @@ import {import { type ChatTopicDispatch } from './reducer';import { topicSelectors } from './selectors';import { createTopicDetailSlice, RUN_WATCH_INTERVAL } from './topicDetail';-import {- type TopicLinkedPullRequestRefreshParams,- useTopicLinkedPullRequestSync,-} from './topicLinkedPullRequest';const n = setNamespace('t');@@ -274,29 +261,6 @@ export class ChatTopicActionImpl {subscribeCacheScope((scope) => this.#topicList.ensureScope(scope));}- #resolveTopicLinkedPullRequestRefreshParams = (- topicId: string,- metadata?: ChatTopicMetadata,- ): TopicLinkedPullRequestRefreshParams | undefined => {- const sourceMetadata = metadata ?? topicSelectors.getTopicById(topicId)(this.#get())?.metadata;- const base = getTopicLinkedPullRequestBase(sourceMetadata);- if (!base) return undefined;-- const { activeAgentId } = this.#get();- if (!activeAgentId) return undefined;-- const transport = resolveTopicGitTransport(activeAgentId);- if (!canReadTopicGitTransport(transport)) return undefined;-- return {- branch: base.branch,- deviceId: transport.deviceId,- path: base.path,- pullRequestNumber: base.pullRequestNumber,- topicId,- };- };-closeAllTopicsDrawer = (): void => {this.#set({ allTopicsDrawerOpen: false }, false, n('closeAllTopicsDrawer'));};@@ -1260,13 +1224,6 @@ export class ChatTopicActionImpl {return true;};- /** Keep a topic's recorded PR state current (see `useTopicLinkedPullRequestSync`). */- useFetchTopicLinkedPullRequest = (topicId?: string, metadata?: ChatTopicMetadata) =>- useTopicLinkedPullRequestSync(- topicId ? this.#resolveTopicLinkedPullRequestRefreshParams(topicId, metadata) : undefined,- (params, pr) => this.#get().internal_updateTopicLinkedPullRequest(params, pr),- );-autoRenameTopicTitle = async (id: string, topicAgentId?: string): Promise<void> => {const { activeAgentId, summaryTopicTitle } = this.#get();const agentId = topicAgentId ?? activeAgentId;@@ -1758,70 +1715,6 @@ export class ChatTopicActionImpl {await this.#get().refreshTopic(containerKey);};- internal_updateTopicLinkedPullRequest = async (- params: TopicLinkedPullRequestRefreshParams,- prData?: GitLinkedPRSummary,- ): Promise<void> => {- if (!isSuccessfulLinkedPullRequestLookup(prData)) return;-- const topic = topicSelectors.getTopicById(params.topicId)(this.#get());- if (!topic) return;-- const base = getTopicLinkedPullRequestBase(topic.metadata);- if (- !base ||- base.branch !== params.branch ||- base.path !== params.path ||- base.pullRequestNumber !== params.pullRequestNumber- ) {- return;- }-- const github = toWorkingDirGithubState(prData);- if (!github) return;-- if (- base.pullRequestNumber !== undefined &&- github.pullRequest?.number !== base.pullRequestNumber- ) {- return;- }-- const nextConfig = mergeWorkingDirGithubState({- branch: base.branch,- currentConfig: base.currentConfig,- github,- path: base.path,- upstream: prData?.upstream,- });-- if (isEqual(base.currentConfig, nextConfig)) return;-- this.#get().internal_dispatchTopic(- {- id: params.topicId,- type: 'updateTopic',- value: {- metadata: {- ...topic.metadata,- workingDirectoryConfig: nextConfig,- },- },- },- n('refreshTopicLinkedPullRequest'),- );-- try {- await topicService.updateTopicMetadata(params.topicId, {- workingDirectoryConfig: nextConfig,- });- await this.#get().refreshTopic();- } catch (error) {- await this.#get().refreshTopic();- throw error;- }- };-internal_createTopic = async (params: CreateTopicParams): Promise<string> => {// A blank conversation opened from a project group's "+" carries the// directory it belongs to — fold it into the create call so the row is borndiff --git a/src/store/chat/slices/topic/topicLinkedPullRequest.ts b/src/store/chat/slices/topic/topicLinkedPullRequest.tsdeleted file mode 100644index 712ef177ba0..00000000000--- a/src/store/chat/slices/topic/topicLinkedPullRequest.ts+++ /dev/null@@ -1,74 +0,0 @@-import { useEffect, useRef } from 'react';--import type { GitLinkedPRSummary } from '@/services/git';-import { gitLinkedPRKey } from '@/store/device/gitReview/projection';-import { useGitReviewStore } from '@/store/device/gitReview/store';-import { useUserStore } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';--export interface TopicLinkedPullRequestRefreshParams {- branch: string;- deviceId?: string;- path: string;- pullRequestNumber?: number;- topicId: string;-}--/** Forwarded to SWR as given: a failed `gh` lookup is not retried. */-const NO_RETRY = { shouldRetryOnError: false };--/**- * Keep a topic's recorded PR state current. Reads through the device's- * linked-PR replica, so with no recorded PR number it shares the composer's- * row and request for the same branch. Every device answer for that row is- * written back to the topic — also one the composer fetched before this hook- * mounted (inside the dedupe window no new response arrives). A row hydrated- * from storage is not proof and is never written back.- */-export const useTopicLinkedPullRequestSync = (- params: TopicLinkedPullRequestRefreshParams | undefined,- writeBack: (- params: TopicLinkedPullRequestRefreshParams,- pr?: GitLinkedPRSummary,- ) => Promise<void>,-) => {- // Better Coding Experience reads a topic's PRs from its Work rows: the- // branch-guessed snapshot is neither refreshed nor written back.- const betterCoding = useUserStore(labPreferSelectors.enableBetterCodingExperience);- const replicaParams =- params && !betterCoding- ? {- branch: params.branch,- deviceId: params.deviceId,- path: params.path,- pullRequestNumber: params.pullRequestNumber,- }- : null;- const key = replicaParams ? gitLinkedPRKey(replicaParams) : undefined;-- const sync = useGitReviewStore.getState().slices.linkedPR.useSync(replicaParams, {- dedupingInterval: 60 * 1000,- focusThrottleInterval: 60 * 1000,- revalidateOnFocus: true,- ...NO_RETRY,- });-- const confirmed = useGitReviewStore((s) =>- key && s.gitLinkedPRReplica.entries[key]?.source === 'server'- ? s.gitLinkedPRMap[key]- : undefined,- );- const latest = useRef({ params, writeBack });- latest.current = { params, writeBack };-- useEffect(() => {- const { params: current, writeBack: write } = latest.current;- if (!confirmed || !current) return;-- void write(current, confirmed.value).catch((error) => {- console.error('[useFetchTopicLinkedPullRequest] sync failed:', error);- });- }, [confirmed, params?.topicId]);-- return sync;-};diff --git a/src/store/chat/utils/topicWorkingDirGit.ts b/src/store/chat/utils/topicWorkingDirGit.tsindex ab49118f523..ecbc34bd2b3 100644--- a/src/store/chat/utils/topicWorkingDirGit.ts+++ b/src/store/chat/utils/topicWorkingDirGit.ts@@ -1,15 +1,9 @@import { isDesktop, isHeterogeneousAgentModelId } from '@lobechat/const';-import type {- ChatTopicMetadata,- DeviceGitUpstreamRef,- WorkingDirConfig,- WorkingDirGithubState,-} from '@lobechat/types';-import { dropStaleAutoCreated, getWorkingDirEffectivePath } from '@lobechat/types';+import type { DeviceGitUpstreamRef, WorkingDirConfig } from '@lobechat/types';+import { dropStaleAutoCreated } from '@lobechat/types';import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';import { applyTopicDeviceBinding } from '@/helpers/executionTarget';-import type { GitLinkedPRSummary } from '@/services/git';import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';import { getElectronStoreState } from '@/store/electron';@@ -20,13 +14,6 @@ export interface TopicGitTransport {targetDeviceId?: string;}-export interface TopicLinkedPullRequestBase {- branch: string;- currentConfig?: WorkingDirConfig;- path: string;- pullRequestNumber?: number;-}-export const canReadTopicGitTransport = (transport: Pick<TopicGitTransport, 'deviceId'>) =>!!transport.deviceId || isDesktop;@@ -65,60 +52,19 @@ export const resolveTopicGitTransport = (};};-export const getTopicLinkedPullRequestBase = (- metadata?: ChatTopicMetadata,-): TopicLinkedPullRequestBase | undefined => {- const currentConfig = metadata?.workingDirectoryConfig;- const git = currentConfig?.git;- const branch = git?.branch;- const path = getWorkingDirEffectivePath(currentConfig) ?? metadata?.workingDirectory;- const repoType =- currentConfig?.repoType ??- (git?.github ? 'github' : undefined) ??- (isDesktop ? undefined : 'github');-- if (!path || !branch || git?.detached || repoType !== 'github') return undefined;-- return {- branch,- currentConfig,- path,- pullRequestNumber: git?.github?.pullRequest?.number,- };-};--export const isSuccessfulLinkedPullRequestLookup = (- prData?: GitLinkedPRSummary,-): prData is GitLinkedPRSummary =>- !!prData && !prData.ghMissing && (prData.pullRequestStatus ?? 'ok') === 'ok';--export const toWorkingDirGithubState = (- prData?: GitLinkedPRSummary,-): WorkingDirGithubState | undefined => {- if (!prData) return undefined;-- return {- ...(prData.extraCount === undefined ? {} : { extraPullRequestCount: prData.extraCount }),- pullRequest: prData.pullRequest ?? null,- pullRequestStatus: prData.pullRequestStatus ?? (prData.ghMissing ? 'gh-missing' : 'ok'),- };-};--export const mergeWorkingDirGithubState = ({+/**+ * Record the working directory's live branch (and its remote ref) on the+ * topic's config. A PR snapshot recorded by an older client is kept while the+ * branch stays, and dropped once it moves.+ */+export const mergeWorkingDirGitBranch = ({branch,currentConfig,- github,path,upstream,}: {branch: string;currentConfig?: WorkingDirConfig;- /**- * The linked-PR snapshot to record. Omitted under Better Coding Experience,- * which no longer guesses a PR from the branch: the one already recorded is- * kept while the branch stays, and dropped once it moves.- */- github?: WorkingDirGithubState;path: string;upstream?: DeviceGitUpstreamRef;}): WorkingDirConfig => {@@ -129,8 +75,7 @@ export const mergeWorkingDirGithubState = ({branch,isWorktree,};- if (github) git.github = github;- else if (currentConfig?.git?.branch !== branch) delete git.github;+ if (currentConfig?.git?.branch !== branch) delete git.github;delete git.detached;if (isWorktree) git.activeWorktree = path;diff --git a/src/store/device/deviceReplicaFirstPaint.test.ts b/src/store/device/deviceReplicaFirstPaint.test.tsindex 32a4a151cd4..6f0947a6d10 100644--- a/src/store/device/deviceReplicaFirstPaint.test.ts+++ b/src/store/device/deviceReplicaFirstPaint.test.ts@@ -2,8 +2,8 @@* @vitest-environment happy-dom** Device reads that used to live only in SWR's memory cache — the base-ref- * pickers' remote branches, the Ports row's tunnel links and listening ports,- * and a topic's linked-PR refresh — are replicas: after a reload they paint the+ * pickers' remote branches, and the Ports row's tunnel links and listening+ * ports — are replicas: after a reload they paint the* persisted copy before the device answers, and the answer replaces it.*/import { randomUUID } from 'node:crypto';@@ -19,10 +19,8 @@ import { AppIndexedDBStorage, cacheScope } from '@/libs/replica';import { setScopedMutate } from '@/libs/swr/mutate';import { deviceService } from '@/services/device';import { gitService } from '@/services/git';-import { useChatStore } from '@/store/chat';-import { useUserStore } from '@/store/user';-import { useFetchGitLinkedPR, useGitRemoteBranches } from './gitHooks';+import { useGitRemoteBranches } from './gitHooks';import { useFetchDeviceListeningPorts, useFetchDeviceTunnels } from './tunnelHooks';vi.mock('@lobechat/const', async (importOriginal) => ({@@ -32,7 +30,6 @@ vi.mock('@lobechat/const', async (importOriginal) => ({vi.mock('@/services/git', () => ({gitService: {- getLinkedPullRequest: vi.fn(),listGitRemoteBranches: vi.fn(),},}));@@ -193,105 +190,4 @@ describe('device replicas paint from storage first', () => {await waitFor(() => expect(result.current.data?.ports.map((p) => p.port)).toEqual([3000]));expect((result.current as { isConfirmed?: boolean }).isConfirmed).toBe(true);});-- // Review P2: a topic hook that mounts after the composer already fetched the- // shared row (e.g. hovering a background topic) gets no new response inside- // the dedupe window; it must still write the confirmed PR back to the topic.- it('writes a PR the composer already confirmed back to a topic that mounts later', async () => {- vi.mocked(gitService.getLinkedPullRequest).mockResolvedValue({- ghMissing: false,- pullRequest: { number: 9, state: 'open', title: 'feat', url: 'https://x/9' } as any,- pullRequestStatus: 'ok',- });- useChatStore.setState({ activeAgentId: 'agent-1' });- const metadata = {- workingDirectory: CWD,- workingDirectoryConfig: { git: { branch: 'feat/late' }, path: CWD, repoType: 'github' },- } as any;- const update = vi.fn().mockResolvedValue(undefined);- useChatStore.setState({ internal_updateTopicLinkedPullRequest: update } as any);-- const { result, rerender } = renderHook(- ({ withTopic }: { withTopic: boolean }) => {- useChatStore- .getState()- .useFetchTopicLinkedPullRequest(withTopic ? 'topic-late' : undefined, metadata);- return useFetchGitLinkedPR(undefined, CWD, 'feat/late', true);- },- { initialProps: { withTopic: false }, wrapper },- );- await waitFor(() => expect(result.current.data?.pullRequest?.number).toBe(9));- expect(update).not.toHaveBeenCalled();-- rerender({ withTopic: true });-- await waitFor(() => expect(update).toHaveBeenCalled());- expect(update.mock.calls[0][0]).toMatchObject({ branch: 'feat/late', topicId: 'topic-late' });- expect(update.mock.calls[0][1]).toMatchObject({ pullRequest: { number: 9 } });- expect(gitService.getLinkedPullRequest).toHaveBeenCalledTimes(1);- });-- // Regression: the topic refresh and the composer's lookup used the same SWR- // key with different fetchers and value shapes, so whichever ran first owned- // the cache — and each still sent its own `gh pr list`.- it('shares one linked-PR read between a topic refresh and the composer', async () => {- vi.mocked(gitService.getLinkedPullRequest).mockResolvedValue({- ghMissing: false,- pullRequest: { number: 7, state: 'open', title: 'feat', url: 'https://x/7' } as any,- pullRequestStatus: 'ok',- });- useChatStore.setState({ activeAgentId: 'agent-1' });- const metadata = {- workingDirectory: CWD,- workingDirectoryConfig: { git: { branch: 'feat/x' }, path: CWD, repoType: 'github' },- } as any;- const update = vi- .spyOn(useChatStore.getState(), 'internal_updateTopicLinkedPullRequest')- .mockResolvedValue();- useChatStore.setState({ internal_updateTopicLinkedPullRequest: update } as any);-- const { result } = renderHook(- () => {- useChatStore.getState().useFetchTopicLinkedPullRequest('topic-1', metadata);- return useFetchGitLinkedPR(undefined, CWD, 'feat/x', true);- },- { wrapper },- );-- await waitFor(() => expect(result.current.data?.pullRequest?.number).toBe(7));- await waitFor(() => expect(update).toHaveBeenCalled());- expect(update.mock.calls[0][1]).toMatchObject({ pullRequest: { number: 7 } });- expect(gitService.getLinkedPullRequest).toHaveBeenCalledTimes(1);- });-- it('neither refreshes nor writes back the branch-guessed PR under Better Coding Experience', async () => {- const preference = useUserStore.getState().preference;- useUserStore.setState({- preference: { ...preference, lab: { ...preference.lab, enableBetterCodingExperience: true } },- });- const metadata = {- workingDirectory: CWD,- workingDirectoryConfig: { git: { branch: 'feat/x' }, path: CWD, repoType: 'github' },- } as any;- const update = vi.fn().mockResolvedValue(undefined);- useChatStore.setState({- activeAgentId: 'agent-1',- internal_updateTopicLinkedPullRequest: update,- } as any);-- try {- renderHook(- () => useChatStore.getState().useFetchTopicLinkedPullRequest('topic-1', metadata),- {- wrapper,- },- );- await new Promise((resolve) => setTimeout(resolve, 50));-- expect(gitService.getLinkedPullRequest).not.toHaveBeenCalled();- expect(update).not.toHaveBeenCalled();- } finally {- useUserStore.setState({ preference });- }- });});diff --git a/src/store/device/gitHooks.ts b/src/store/device/gitHooks.tsindex 71dda81fb8c..91c276a6fc3 100644--- a/src/store/device/gitHooks.ts+++ b/src/store/device/gitHooks.ts@@ -16,10 +16,9 @@ import { useCallback, useMemo, useRef } from 'react';import { mutate } from '@/libs/swr';import { deviceKeys, localFileKeys } from '@/libs/swr/keys';-import type { GitBranchSummary, GitLinkedPRSummary } from '@/services/git';+import type { GitBranchSummary } from '@/services/git';import {- gitLinkedPRKey,gitPullRequestKey,gitPullRequestMergeContextKey,type GitPullRequestMergeContextParams,@@ -29,7 +28,7 @@ import {type ReviewMode,type ReviewPatchesData,} from './gitReview/projection';-import { type GitReviewStore, useGitReviewStore, warmPullRequestReplicas } from './gitReview/store';+import { type GitReviewStore, useGitReviewStore } from './gitReview/store';import {type GitDiffStats,gitStatusKey,@@ -387,50 +386,6 @@ export const useFetchGitBranch = (deviceId: string | undefined, path?: string) ={ dedupingInterval: 2 * 1000 },);-/**- * PR linked to the current branch. The lookup spawns `gh pr list` (8s timeout),- * so keep a long 60s dedupe + 60s focus throttle — unlike the cheap branch read,- * this must NOT re-run on every remount or directory revisit. Keyed by branch,- * so a checkout naturally re-keys into a fresh lookup; disabled for non-github- * repos and detached HEAD (no branch ref to query). Includes merged/closed PRs- * so the lifecycle badge can refresh after GitHub changes outside the app.- */-export const useFetchGitLinkedPR = (- deviceId: string | undefined,- path: string | undefined,- branch: string | undefined,- isGithub = false,-) => {- const enabled = isGithub && !!branch && isEnabled(deviceId, path);- const params = useMemo(- () => (enabled ? { branch: branch!, deviceId, path: path! } : null),- [enabled, branch, deviceId, path],- );- // The PR tab mounts the moment the linked PR is known; start reading its- // persisted detail / activity then, so the tab body paints from storage on- // its first frame instead of a skeleton while its own hydration reads them.- const warm = useCallback(- (read: GitReviewRead<GitLinkedPRSummary>) => {- const number = read.value?.pullRequest?.number;- if (number !== undefined && path) warmPullRequestReplicas({ deviceId, number, path });- },- [deviceId, path],- );- return useGitReviewRead(- (slices) => slices.linkedPR,- (s) => s.gitLinkedPRMap,- (s) => s.gitLinkedPRReplica.entries,- gitLinkedPRKey,- params,- {- dedupingInterval: 60 * 1000,- focusThrottleInterval: 60 * 1000,- onHydrated: warm,- onSuccess: warm,- },- );-};-/*** Compact uncommitted-diff counts for the composer's `+N −M` chip. There is no* read of its own: the review-patch hook writes the counts here once they load,diff --git a/src/store/device/gitReview/projection.ts b/src/store/device/gitReview/projection.tsindex 8dffb64cf27..34aa594297f 100644--- a/src/store/device/gitReview/projection.ts+++ b/src/store/device/gitReview/projection.ts@@ -10,7 +10,6 @@ import type {import { defineReplica } from '@/libs/replica';import { deviceKeys } from '@/libs/swr/keys';-import type { GitLinkedPRSummary } from '@/services/git';/*** The Working Sidebar Review and Pull Request tab reads. They are replicas so@@ -127,17 +126,6 @@ export interface GitReviewPatchesParams {path: string;}-export interface GitLinkedPRParams {- branch: string;- deviceId?: string;- path: string;- /**- * The PR a topic recorded for this branch, so the lookup follows that PR even- * after another one opens on the branch. Absent for the composer's lookup.- */- pullRequestNumber?: number;-}-export interface GitPullRequestParams {deviceId?: string;number: number;@@ -153,12 +141,6 @@ export interface GitPullRequestMergeContextParams extends GitPullRequestParams {export const gitReviewPatchesKey = ({ baseRef, deviceId, mode, path }: GitReviewPatchesParams) =>joinKey(deviceId ?? LOCAL, path, mode, baseRef ?? '');-/** Without a PR number this is the composer's key, so both readers share one row. */-export const gitLinkedPRKey = ({ branch, deviceId, path, pullRequestNumber }: GitLinkedPRParams) =>- pullRequestNumber === undefined- ? joinKey(deviceId ?? LOCAL, path, branch)- : joinKey(deviceId ?? LOCAL, path, branch, pullRequestNumber);-export const gitPullRequestKey = ({ deviceId, number, path }: GitPullRequestParams) =>joinKey(deviceId ?? LOCAL, path, number);@@ -188,19 +170,6 @@ export const gitReviewPatchesResource = defineReplica<GitReviewPatchesParams, Reversion: 1,});-export const gitLinkedPRResource = defineReplica<- GitLinkedPRParams,- GitReviewRead<GitLinkedPRSummary>->({- key: gitLinkedPRKey,- name: 'deviceGitLinkedPR',- persist: { maxEntries: 50 },- storage: 'indexedDB',- syncKey: ({ branch, deviceId, path, pullRequestNumber }) =>- deviceKeys.gitLinkedPR(deviceId ?? LOCAL, path, branch, pullRequestNumber),- version: 1,-});-export const gitPullRequestDetailResource = defineReplica<GitPullRequestParams,GitReviewRead<DeviceGitPullRequestDetailResult>diff --git a/src/store/device/gitReview/store.test.ts b/src/store/device/gitReview/store.test.tsindex e01c3dfb77e..095ed336953 100644--- a/src/store/device/gitReview/store.test.ts+++ b/src/store/device/gitReview/store.test.ts@@ -3,7 +3,7 @@** The Review / Pull Request tab reads are replicas: after a reload the last* file list (paths + counts, no diff text) and the last PR detail / activity /- * merge context / linked PR paint from the persisted copy on the first frame,+ * merge context paint from the persisted copy on the first frame,* and the device read only confirms them.*/import { randomUUID } from 'node:crypto';@@ -22,7 +22,6 @@ import { gitService } from '@/services/git';import {invalidateGitReviewCaches,- useFetchGitLinkedPR,useFetchGitPullRequestActivity,useFetchGitPullRequestDetail,useFetchGitPullRequestMergeContext,@@ -31,11 +30,8 @@ import {import {getReviewSummaryState,GIT_REVIEW_MAX_PERSISTED_BYTES,- gitLinkedPRKey,- gitLinkedPRResource,gitPullRequestActivityResource,gitPullRequestDetailResource,- gitPullRequestKey,gitPullRequestMergeContextResource,gitReviewPatchesResource,type ReviewPatchesData,@@ -51,7 +47,6 @@ vi.mock('@/services/git', () => ({gitService: {getGitBranchDiff: vi.fn(),getGitWorkingTreePatches: vi.fn(),- getLinkedPullRequest: vi.fn(),getPullRequestActivity: vi.fn(),getPullRequestDetail: vi.fn(),getPullRequestMergeContext: vi.fn(),@@ -123,7 +118,6 @@ const REVIEW = {path: '/repo',};const PR = { deviceId: 'device-1', number: 42, path: '/repo' };-const LINKED = { branch: 'feat/x', deviceId: 'device-1', path: '/repo' };const MERGE = {...PR,baseRefName: 'canary',@@ -378,14 +372,8 @@ describe('Review / PR tab replicas', () => {describe('Pull Request tab', () => {// Regression: the PR reads lived only in SWR's memory cache, so after a// reload the PR tab body was a skeleton until `gh pr view` answered again.- it('paints the persisted linked PR, detail, activity and merge context before gh answers', async () => {+ it('paints the persisted detail, activity and merge context before gh answers', async () => {await Promise.all([- seed(gitLinkedPRResource, LINKED, {- value: {- pullRequest: { number: 42, state: 'open', title: 'Cached PR title', url: 'u' },- pullRequestStatus: 'ok',- },- }),seed(gitPullRequestDetailResource, PR, { value: detailResult }),seed(gitPullRequestActivityResource, PR, {value: { comments: [{ author: 'a', body: 'cached comment' }], commits: [], reviews: [] },@@ -399,14 +387,12 @@ describe('Review / PR tab replicas', () => {},}),]);- vi.mocked(gitService.getLinkedPullRequest).mockImplementation(pending);vi.mocked(gitService.getPullRequestDetail).mockImplementation(pending);vi.mocked(gitService.getPullRequestActivity).mockImplementation(pending);vi.mocked(gitService.getPullRequestMergeContext).mockImplementation(pending);const { result } = renderHook(() => {- const linked = useFetchGitLinkedPR('device-1', '/repo', 'feat/x', true);const detail = useFetchGitPullRequestDetail('device-1', '/repo', 42);const activity = useFetchGitPullRequestActivity('device-1', '/repo', 42);const context = useFetchGitPullRequestMergeContext(@@ -414,7 +400,7 @@ describe('Review / PR tab replicas', () => {'/repo',detail.data?.detail ?? undefined,);- return { activity, context, detail, linked };+ return { activity, context, detail };},{ wrapper },);@@ -424,7 +410,6 @@ describe('Review / PR tab replicas', () => {);expect(result.current.detail.isLoading).toBe(false);expect(result.current.detail.isValidating).toBe(true);- expect(result.current.linked.data?.pullRequest?.number).toBe(42);await waitFor(() =>expect(result.current.activity.data?.comments[0]?.body).toBe('cached comment'),);@@ -432,40 +417,6 @@ describe('Review / PR tab replicas', () => {expect(gitService.getPullRequestDetail).toHaveBeenCalledWith({ ...PR, coreOnly: true });});- // Regression: the PR tab mounts once the linked PR is known, and its own- // hydration then read the detail from storage — a skeleton frame in between.- it('reads the PR detail and activity from storage once the linked PR hydrates', async () => {- await Promise.all([- seed(gitLinkedPRResource, LINKED, {- value: {- pullRequest: { number: 42, state: 'open', title: 'Cached PR title', url: 'u' },- pullRequestStatus: 'ok',- },- }),- seed(gitPullRequestDetailResource, PR, { value: detailResult }),- seed(gitPullRequestActivityResource, PR, {- value: { comments: [{ author: 'a', body: 'cached comment' }], commits: [], reviews: [] },- }),- ]);- vi.mocked(gitService.getLinkedPullRequest).mockImplementation(pending);-- // Only the linked-PR read is mounted: the PR tab is not rendered yet.- renderHook(() => useFetchGitLinkedPR('device-1', '/repo', 'feat/x', true), { wrapper });-- const key = gitPullRequestKey(PR);- await waitFor(() =>- expect(- useGitReviewStore.getState().gitPullRequestDetailMap[key]?.value?.detail?.title,- ).toBe('Cached PR title'),- );- await waitFor(() =>- expect(- useGitReviewStore.getState().gitPullRequestActivityMap[key]?.value?.comments[0]?.body,- ).toBe('cached comment'),- );- expect(gitService.getPullRequestDetail).not.toHaveBeenCalled();- });-it('replaces the persisted detail with the gh read and persists it', async () => {await seed(gitPullRequestDetailResource, PR, { value: detailResult });const fresh: DeviceGitPullRequestDetailResult = {@@ -484,63 +435,6 @@ describe('Review / PR tab replicas', () => {);});- it('lets an empty linked-PR answer replace a stale persisted PR', async () => {- await seed(gitLinkedPRResource, LINKED, {- value: { pullRequest: { number: 42 }, pullRequestStatus: 'ok' },- });- const none = { pullRequest: null, pullRequestStatus: 'ok' } as const;- vi.mocked(gitService.getLinkedPullRequest).mockResolvedValue(none as any);-- const { result } = renderHook(- () => useFetchGitLinkedPR('device-1', '/repo', 'feat/x', true),- { wrapper },- );-- await waitFor(() => expect(result.current.data?.pullRequest).toBeNull());- await waitFor(async () =>- expect(await readRow(gitLinkedPRResource, LINKED)).toEqual({ value: none }),- );- });-- // Regression: an offline remote device resolves the lookup to `undefined`;- // that was committed as "no PR", so the PR tab vanished and its persisted- // copy was overwritten.- it('keeps the persisted linked PR when the device read fails', async () => {- const cached = { value: { pullRequest: { number: 42 }, pullRequestStatus: 'ok' } };- await seed(gitLinkedPRResource, LINKED, cached);- vi.mocked(gitService.getLinkedPullRequest).mockResolvedValue(undefined);-- const { result } = renderHook(- () => useFetchGitLinkedPR('device-1', '/repo', 'feat/x', true),- { wrapper },- );-- await waitFor(() => expect(result.current.error).toBeTruthy());- expect(result.current.data?.pullRequest?.number).toBe(42);- expect(await readRow(gitLinkedPRResource, LINKED)).toEqual(cached);- });-- // Regression: a transient `gh` failure answers `{ pullRequest: null,- // status: 'error' }`; that was committed as "no PR" over the cached one.- it('keeps the persisted linked PR when the lookup reports an error', async () => {- const cached = { value: { pullRequest: { number: 42 }, pullRequestStatus: 'ok' } };- await seed(gitLinkedPRResource, LINKED, cached);- vi.mocked(gitService.getLinkedPullRequest).mockResolvedValue({- pullRequest: null,- pullRequestStatus: 'error',- } as any);-- const { result } = renderHook(- () => useFetchGitLinkedPR('device-1', '/repo', 'feat/x', true),- { wrapper },- );-- await waitFor(() => expect(result.current.error).toBeTruthy());- expect(result.current.data?.pullRequest?.number).toBe(42);- expect(result.current.isConfirmed).toBe(false);- expect(await readRow(gitLinkedPRResource, LINKED)).toEqual(cached);- });-// A persisted row paints, but only the device's answer makes it actionable.it('reports a hydrated detail as unconfirmed until gh answers', async () => {await seed(gitPullRequestDetailResource, PR, { value: detailResult });@@ -604,71 +498,5 @@ describe('Review / PR tab replicas', () => {expect(result.current.data?.requiredChecks).toEqual(['ci']);expect(await readRow(gitPullRequestMergeContextResource, MERGE)).toEqual(cached);});-- it('does not read a PR for a non-GitHub repo', async () => {- const { result } = renderHook(- () => useFetchGitLinkedPR('device-1', '/repo', 'feat/x', false),- { wrapper },- );- await new Promise((resolve) => setTimeout(resolve, 20));-- expect(gitService.getLinkedPullRequest).not.toHaveBeenCalled();- expect(result.current.isLoading).toBe(false);- });-- // Regression: SWR settles a request still in flight when its key goes null- // through the latest callbacks, which closed over null params, so a slow- // `gh` lookup that failed after the read was disabled threw- // "Cannot destructure property 'branch' of null" from `gitLinkedPRKey`.- it('settles a lookup that fails after the read is disabled', async () => {- let reject!: (error: unknown) => void;- vi.mocked(gitService.getLinkedPullRequest).mockImplementation(- () => new Promise((_resolve, rejectLookup) => (reject = rejectLookup)),- );- const linkedPR = useGitReviewStore.getState().slices.linkedPR;- // Earlier never-resolving reads stay pending on the shared slice.- const pendingBefore = linkedPR.debugPendingSyncRequests();- const unhandled = vi.fn();- process.on('unhandledRejection', unhandled);-- try {- const { rerender } = renderHook(- ({ isGithub }) => useFetchGitLinkedPR('device-1', '/repo', 'feat/x', isGithub),- { initialProps: { isGithub: true }, wrapper },- );- await waitFor(() => expect(gitService.getLinkedPullRequest).toHaveBeenCalled());-- rerender({ isGithub: false });- await act(async () => reject(new Error('gh pr list timed out')));- await new Promise((resolve) => setTimeout(resolve, 20));-- expect(unhandled).not.toHaveBeenCalled();- expect(linkedPR.debugPendingSyncRequests()).toBe(pendingBefore);- } finally {- process.off('unhandledRejection', unhandled);- }- });- });-- describe('linked PR key', () => {- it('shares the composer row when a topic has no recorded PR, and splits it when it has one', () => {- const composer = { branch: 'feat/x', deviceId: 'device-1', path: '/repo' };-- expect(gitLinkedPRKey({ ...composer, pullRequestNumber: undefined })).toBe(- gitLinkedPRKey(composer),- );- // A topic that recorded PR #7 asks `gh` about that PR, not "the PR of- // this branch": its answer must not land on the composer's row.- expect(gitLinkedPRKey({ ...composer, pullRequestNumber: 7 })).not.toBe(- gitLinkedPRKey(composer),- );- expect(gitLinkedPRResource.syncKey!({ ...composer, pullRequestNumber: 7 })).toEqual([- 'device:gitLinkedPR',- 'device-1',- '/repo',- 'feat/x',- 7,- ]);- });});});diff --git a/src/store/device/gitReview/store.ts b/src/store/device/gitReview/store.tsindex 073d3931dc1..160f01a7a6d 100644--- a/src/store/device/gitReview/store.ts+++ b/src/store/device/gitReview/store.ts@@ -12,17 +12,14 @@ import {recordLens,type ReplicaState,} from '@/libs/replica';-import { type GitLinkedPRSummary, gitService } from '@/services/git';+import { gitService } from '@/services/git';import { createDevtools } from '@/store/middleware/createDevtools';import { expose } from '@/store/middleware/expose';import {boundedPersist,- type GitLinkedPRParams,- gitLinkedPRResource,gitPullRequestActivityResource,gitPullRequestDetailResource,- gitPullRequestKey,type GitPullRequestMergeContextParams,gitPullRequestMergeContextResource,type GitPullRequestParams,@@ -33,15 +30,11 @@ import {toReviewPatchesSummary,} from './projection';-type LinkedPRRead = GitReviewRead<GitLinkedPRSummary>;type DetailRead = GitReviewRead<DeviceGitPullRequestDetailResult>;type ActivityRead = GitReviewRead<DeviceGitPullRequestActivity>;type MergeContextRead = GitReviewRead<DeviceGitPullRequestMergeContext | null>;export interface GitReviewStoreState {- /** `gitLinkedPRKey(params)` → PR linked to a branch. */- gitLinkedPRMap: Record<string, LinkedPRRead>;- gitLinkedPRReplica: ReplicaState<LinkedPRRead>;/** `gitPullRequestKey(params)` → comments / reviews / commits. */gitPullRequestActivityMap: Record<string, ActivityRead>;gitPullRequestActivityReplica: ReplicaState<ActivityRead>;@@ -57,8 +50,6 @@ export interface GitReviewStoreState {}export const initialGitReviewState: GitReviewStoreState = {- gitLinkedPRMap: {},- gitLinkedPRReplica: createReplicaState(),gitPullRequestActivityMap: {},gitPullRequestActivityReplica: createReplicaState(),gitPullRequestDetailMap: {},@@ -110,25 +101,6 @@ const createSlices = (set: (partial: Partial<GitReviewStore>, replace?: false, action?: any) => void,get: () => GitReviewStore,) => ({- linkedPR: createReplicaSlice(gitLinkedPRResource, {- actionPrefix: 'gitReview/linkedPR',- // "No PR" is an answer (`pullRequest: null`, status `ok`); `undefined` (a- // failed remote read) and status `error` (a transient `gh` failure) are not.- // `gh-missing` stays an answer: the composer shows it.- fetcher: async (params: GitLinkedPRParams) => {- const value = requireAnswer(- await gitService.getLinkedPullRequest(params),- 'linked pull request',- );- if (value.pullRequestStatus === 'error')- throw new Error('Unable to load linked pull request');- return { value };- },- get,- set,- stateKey: 'gitLinkedPRReplica',- view: recordLens<GitReviewStore, LinkedPRRead>('gitLinkedPRMap'),- }),pullRequestActivity: createReplicaSlice(gitPullRequestActivityResource, {actionPrefix: 'gitReview/pullRequestActivity',fetcher: async (params: GitPullRequestParams) => ({@@ -202,15 +174,3 @@ export const useGitReviewStore = createWithEqualityFn<GitReviewStore>()();expose('gitReview', useGitReviewStore);--/**- * Read a PR's persisted detail and activity into memory ahead of the PR tab's- * own hydration. Rows already in memory are left alone.- */-export const warmPullRequestReplicas = (params: GitPullRequestParams) => {- const { gitPullRequestActivityMap, gitPullRequestDetailMap, slices } =- useGitReviewStore.getState();- const key = gitPullRequestKey(params);- if (!gitPullRequestDetailMap[key]) void slices.pullRequestDetail.hydrate(params);- if (!gitPullRequestActivityMap[key]) void slices.pullRequestActivity.hydrate(params);-};diff --git a/src/store/tool/slices/builtin/executors/__tests__/antigravityGitEffects.test.ts b/src/store/tool/slices/builtin/executors/__tests__/antigravityGitEffects.test.tsindex 3f3b008d356..a9e8dccb492 100644--- a/src/store/tool/slices/builtin/executors/__tests__/antigravityGitEffects.test.ts+++ b/src/store/tool/slices/builtin/executors/__tests__/antigravityGitEffects.test.ts@@ -50,7 +50,12 @@ describe('Antigravity Git completion effects', () => {expect(mocks.updateTopicMetadata).toHaveBeenCalledWith('run-topic', {workingDirectoryConfig: {- git: { activeWorktree: '/agy-worktree', branch: 'fix/agy', isWorktree: true },+ git: {+ activeWorktree: '/agy-worktree',+ branch: 'fix/agy',+ isWorktree: true,+ ownBranch: 'fix/agy',+ },path: '/repo',},});diff --git a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.betterCoding.test.ts b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.pushAndOwnBranch.test.tssimilarity index 86%rename from src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.betterCoding.test.tsrename to src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.pushAndOwnBranch.test.tsindex dc7309ad0eb..0e844c38aea 100644--- a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.betterCoding.test.ts+++ b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.pushAndOwnBranch.test.ts@@ -6,7 +6,6 @@ const chatMocks = vi.hoisted(() => ({topics: {} as Record<string, { metadata?: Record<string, any> }>,updateTopicMetadata: vi.fn(),}));-const labMocks = vi.hoisted(() => ({ betterCoding: true }));const linkMocks = vi.hoisted(() => ({ linkPushedPullRequests: vi.fn(async () => []) }));const gsMocks = vi.hoisted(() => ({ revalidateGitStatus: vi.fn() }));@@ -21,10 +20,6 @@ vi.mock('@/services/git', () => ({ gitService: { listGitWorktrees: vi.fn() } }))vi.mock('@/store/electron', () => ({getElectronStoreState: () => ({ gatewayDeviceInfo: { deviceId: 'device-1' } }),}));-vi.mock('@/store/user', () => ({ getUserStoreState: () => ({}) }));-vi.mock('@/store/user/selectors', () => ({- labPreferSelectors: { enableBetterCodingExperience: () => labMocks.betterCoding },-}));vi.mock('../pushedPullRequests', () => linkMocks);const topic = (git: Record<string, unknown> = { branch: 'feat/x' }) => ({@@ -39,10 +34,9 @@ const PUSH = {].join('\n'),};-describe('recordGitCommandEffects — Better Coding Experience', () => {+describe('recordGitCommandEffects — pushes and own branches', () => {beforeEach(() => {vi.clearAllMocks();- labMocks.betterCoding = true;chatMocks.topics = { t1: topic() };});@@ -103,29 +97,12 @@ describe('recordGitCommandEffects — Better Coding Experience', () => {);});- it('does not link without the call id, or with the lab off', async () => {+ it('does not link without the call id', async () => {await recordGitCommandEffects({ ...PUSH, topicId: 't1' });- labMocks.betterCoding = false;- await recordGitCommandEffects({ ...PUSH, toolCallId: 'call-push', topicId: 't1' });expect(linkMocks.linkPushedPullRequests).not.toHaveBeenCalled();});- it('keeps binding gh pr create while the lab is off', async () => {- labMocks.betterCoding = false;-- await recordGitCommandEffects({- command: 'gh pr create --title "Fix"',- resultContent: 'https://github.com/lobehub/lobehub/pull/456',- topicId: 't1',- });-- expect(- chatMocks.updateTopicMetadata.mock.calls[0][1].workingDirectoryConfig.git.github.pullRequest- .number,- ).toBe(456);- });-it('links a push whose result repeats the ref table under Stdout and Stderr', async () => {const table = ['To github.com:lobehub/lobehub.git', ' 031bf96..f6b1c2a feat/x -> feat/x'];await recordGitCommandEffects({diff --git a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.tsindex 7434c9bb748..9484823ee43 100644--- a/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts+++ b/src/store/tool/slices/builtin/executors/__tests__/worktreeDetection.test.ts@@ -420,46 +420,6 @@ describe('recordGitCommandEffects', () => {});});- it('binds a created GitHub PR from gh pr create output', async () => {- chatMocks.topics = {- t1: {- metadata: {- workingDirectoryConfig: {- git: { branch: 'fix/topic' },- path: '/repo',- repoType: 'github',- },- },- },- };-- await recordGitCommandEffects({- command: 'gh pr create --title "Fix topic" --draft',- resultContent: 'https://github.com/lobehub/lobehub/pull/456',- topicId: 't1',- });-- expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {- workingDirectoryConfig: {- git: {- branch: 'fix/topic',- github: {- pullRequest: {- isDraft: true,- number: 456,- state: 'OPEN',- title: 'Fix topic',- url: 'https://github.com/lobehub/lobehub/pull/456',- },- pullRequestStatus: 'ok',- },- },- path: '/repo',- repoType: 'github',- },- });- });-it('records a worktree add shipped through the Codex zsh wrapper', async () => {chatMocks.topics = { t1: PR_TOPIC };@@ -474,6 +434,7 @@ describe('recordGitCommandEffects', () => {activeWorktree: '/Users/me/wt',branch: 'feat/agent-testing-s3rver',isWorktree: true,+ ownBranch: 'feat/agent-testing-s3rver',},path: '/repo',repoType: 'github',@@ -498,34 +459,6 @@ describe('recordGitCommandEffects', () => {});});- it('binds a created PR from a wrapped gh pr create', async () => {- chatMocks.topics = { t1: PR_TOPIC };-- await recordGitCommandEffects({- command: `/bin/zsh -lc "gh pr create --title 'Fix topic'"`,- resultContent: 'https://github.com/lobehub/lobehub/pull/456',- topicId: 't1',- });-- expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {- workingDirectoryConfig: {- git: {- github: {- pullRequest: {- number: 456,- state: 'OPEN',- title: 'Fix topic',- url: 'https://github.com/lobehub/lobehub/pull/456',- },- pullRequestStatus: 'ok',- },- },- path: '/repo',- repoType: 'github',- },- });- });-it('does not query the device when the worktree path parses statically', async () => {chatMocks.topics = { t1: PR_TOPIC };@@ -597,7 +530,12 @@ describe('recordGitCommandEffects', () => {expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {workingDirectoryConfig: {- git: { activeWorktree: '/repo-feat-y', branch: 'feat/y', isWorktree: true },+ git: {+ activeWorktree: '/repo-feat-y',+ branch: 'feat/y',+ isWorktree: true,+ ownBranch: 'feat/y',+ },path: '/repo',repoType: 'github',},@@ -632,35 +570,6 @@ describe('recordGitCommandEffects', () => {expect(chatMocks.updateTopicMetadata).not.toHaveBeenCalled();});-- it('uses gh pr create --head as the topic branch when present', async () => {- chatMocks.topics = { t1: PR_TOPIC };-- await recordGitCommandEffects({- command: 'gh pr create --head arvinxx:fix/head-branch --title "Head branch"',- resultContent: 'Created pull request: https://github.com/lobehub/lobehub/pull/789',- topicId: 't1',- });-- expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {- workingDirectoryConfig: {- git: {- branch: 'fix/head-branch',- github: {- pullRequest: {- number: 789,- state: 'OPEN',- title: 'Head branch',- url: 'https://github.com/lobehub/lobehub/pull/789',- },- pullRequestStatus: 'ok',- },- },- path: '/repo',- repoType: 'github',- },- });- });});/**@@ -747,7 +656,12 @@ describe('recordWorktreeEnter', () => {expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {workingDirectoryConfig: {- git: { activeWorktree: '/repo/wt', branch: 'worktree-a', isWorktree: true },+ git: {+ activeWorktree: '/repo/wt',+ branch: 'worktree-a',+ isWorktree: true,+ ownBranch: 'worktree-a',+ },path: '/repo',repoType: 'github',},@@ -1061,8 +975,8 @@ describe('recordGitCommandEffects — git push', () => {});});- // `gh pr create` then `git push` in one run must not erase the PR it just recorded.- it('keeps a freshly created PR on the first push to that ref', async () => {+ // A first push must not erase a PR snapshot an older client recorded.+ it('keeps a recorded PR on the first push to that ref', async () => {const pullRequest = {number: 17_101,state: 'OPEN',diff --git a/src/store/tool/slices/builtin/executors/localSystem.ts b/src/store/tool/slices/builtin/executors/localSystem.tsindex 89854e66f5a..b22006709a4 100644--- a/src/store/tool/slices/builtin/executors/localSystem.ts+++ b/src/store/tool/slices/builtin/executors/localSystem.ts@@ -40,10 +40,10 @@ const commandExitedCleanly = (state: unknown): boolean =>* The package's own executor handles invocation; this adds the renderer-side* `onAfterCall` hook the dispatcher (`gatewayEventHandler.dispatchOnAfterCall`)* resolves by identifier, so a native agent's `runCommand` calls get the same- * git/gh side-effect tracking (`git worktree add` / `git switch` / `git push` /- * `gh pr create` → topic metadata) heterogeneous CLI shell calls already have.- * Without this hook the topic's branch/PR binding silently misses every worktree- * or PR created inside a native-agent run.+ * git side-effect tracking (`git worktree add` / `git switch` / `git push` →+ * topic metadata, a push's PR → Work rows) heterogeneous CLI shell calls+ * already have. Without this hook the topic's branch binding silently misses+ * every worktree or push made inside a native-agent run.*/class LocalSystemExecutorWithGitEffects {readonly identifier = localSystemExecutor.identifier;diff --git a/src/store/tool/slices/builtin/executors/ownBranch.ts b/src/store/tool/slices/builtin/executors/ownBranch.tsindex 57b0ee7444e..0a355ac1a7e 100644--- a/src/store/tool/slices/builtin/executors/ownBranch.ts+++ b/src/store/tool/slices/builtin/executors/ownBranch.ts@@ -27,7 +27,7 @@ export const parseCreatedBranch = (content?: string): string | undefined => {/*** Record `branch` as the conversation's own when the command created it and- * the topic is now on it (`git.ownBranch`, Better Coding Experience). The run+ * the topic is now on it (`git.ownBranch`). The run* end only asks GitHub for the PR of that branch.*/export const applyOwnBranchToConfig = (diff --git a/src/store/tool/slices/builtin/executors/pushedPullRequests.ts b/src/store/tool/slices/builtin/executors/pushedPullRequests.tsindex 4d83a0975ef..fd1675b318d 100644--- a/src/store/tool/slices/builtin/executors/pushedPullRequests.ts+++ b/src/store/tool/slices/builtin/executors/pushedPullRequests.ts@@ -7,7 +7,7 @@ export const PUSH_LINK_RETRY_DELAYS = [1500, 4000, 10_000];const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));/**- * After an agent's `git push` (Better Coding Experience), link the pull+ * After an agent's `git push`, link the pull* request the pushed branch already has to the topic.** The execution device answers which PR heads the branch (`gh pr list --head`diff --git a/src/store/tool/slices/builtin/executors/worktreeConfigEffects.ts b/src/store/tool/slices/builtin/executors/worktreeConfigEffects.tsindex 4727e94cdd8..6c6997257cb 100644--- a/src/store/tool/slices/builtin/executors/worktreeConfigEffects.ts+++ b/src/store/tool/slices/builtin/executors/worktreeConfigEffects.ts@@ -1,8 +1,4 @@-import type {- DeviceGitLinkedPullRequest,- DeviceGitUpstreamRef,- WorkingDirConfig,-} from '@lobechat/types';+import type { DeviceGitUpstreamRef, WorkingDirConfig } from '@lobechat/types';import { dropStaleAutoCreated } from '@lobechat/types';/**@@ -16,11 +12,6 @@ export interface WorktreeAddInfo {path: string;}-export interface PullRequestCreateInfo {- branch?: string;- pullRequest: DeviceGitLinkedPullRequest;-}-export const applyBranchToConfig = (currentConfig: WorkingDirConfig | undefined,source: string,@@ -69,31 +60,6 @@ export const applyDetachedToConfig = (};};-export const applyPullRequestToConfig = (- currentConfig: WorkingDirConfig | undefined,- source: string,- info: PullRequestCreateInfo,-): WorkingDirConfig => {- const branch = info.branch ?? currentConfig?.git?.branch;- const git: NonNullable<WorkingDirConfig['git']> = {- ...currentConfig?.git,- ...(branch ? { branch } : {}),- github: {- pullRequest: info.pullRequest,- pullRequestStatus: 'ok',- },- };-- delete git.detached;-- return {- ...currentConfig,- git,- path: source,- repoType: 'github',- };-};-/*** Record where the branch now publishes to. This is what makes the PR lookup work at* all for a worktree: its local branch name (`worktree-feat+x`) never exists on the@@ -110,9 +76,8 @@ export const applyPushToConfig = (upstream,};- // Re-pointing the branch at a DIFFERENT remote ref orphans the PR bound to the old- // one. Only a change invalidates it — a first push must not drop a PR that a- // preceding `gh pr create` in the same run just recorded.+ // Re-pointing the branch at a DIFFERENT remote ref orphans a PR an older client+ // recorded for the old one. Only a change invalidates it.if (previous && previous !== upstream.branch) delete git.github;return {diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.remove.test.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.remove.test.tsindex d83ff586612..3a1bbe96f9a 100644--- a/src/store/tool/slices/builtin/executors/worktreeDetection.remove.test.ts+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.remove.test.ts@@ -263,7 +263,7 @@ describe('recordGitCommandEffects — git worktree remove', () => {expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {workingDirectoryConfig: {- git: { activeWorktree: '/tmp/b', branch: 'b', isWorktree: true },+ git: { activeWorktree: '/tmp/b', branch: 'b', isWorktree: true, ownBranch: 'b' },path: '/repo',},});@@ -295,7 +295,7 @@ describe('recordGitCommandEffects — git worktree remove', () => {expect(chatMocks.updateTopicMetadata).toHaveBeenCalledWith('t1', {workingDirectoryConfig: {- git: { activeWorktree: '/tmp/wt', branch: 'fresh', isWorktree: true },+ git: { activeWorktree: '/tmp/wt', branch: 'fresh', isWorktree: true, ownBranch: 'fresh' },path: '/repo',},});diff --git a/src/store/tool/slices/builtin/executors/worktreeDetection.ts b/src/store/tool/slices/builtin/executors/worktreeDetection.tsindex e790ed6a5b5..76c82004a65 100644--- a/src/store/tool/slices/builtin/executors/worktreeDetection.ts+++ b/src/store/tool/slices/builtin/executors/worktreeDetection.ts@@ -8,19 +8,15 @@ import { topicSelectors } from '@/store/chat/selectors';import { getChatStoreState } from '@/store/chat/store';import { getGitStatusStoreState } from '@/store/device/gitStatus/store';import { getElectronStoreState } from '@/store/electron';-import { getUserStoreState } from '@/store/user';-import { labPreferSelectors } from '@/store/user/selectors';import { applyOwnBranchToConfig, parseCreatedBranch } from './ownBranch';import { linkPushedPullRequests } from './pushedPullRequests';import {applyBranchToConfig,applyDetachedToConfig,- applyPullRequestToConfig,applyPushToConfig,applyWorktreeAddToConfig,applyWorktreeExitToConfig,- type PullRequestCreateInfo,type WorktreeAddInfo,} from './worktreeConfigEffects';@@ -30,7 +26,7 @@ import {** Runs from the `claude-code` / `codex` executor's `onAfterCall` hook* (renderer-side, fired on `tool_end`). The CLI session cwd stays anchored to- * the source repo; selected worktree / branch / linked PR are topic metadata.+ * the source repo; selected worktree / branch are topic metadata.** Command parsing is a trigger + hint, not the source of truth: a Codex-style* login-shell wrapper (`/bin/zsh -lc "…"`) is peeled off first, `$VAR`@@ -60,32 +56,6 @@ const BRANCH_SWITCH_VALUE_FLAGS = new Set([const DETACH_FLAGS = new Set(['-d', '--detach']);const GIT_BRANCH_SWITCH_SUBCOMMANDS = new Set(['checkout', 'switch']);const GIT_SWITCH_VALUE_FLAGS = new Set(['--conflict', '--pathspec-from-file']);-const GH_VALUE_FLAGS = new Set([- '-B',- '-H',- '-R',- '-t',- '--base',- '--body',- '--body-file',- '--head',- '--label',- '--milestone',- '--project',- '--recover',- '--repo',- '--reviewer',- '--template',- '--title',-]);-const GH_GLOBAL_VALUE_FLAGS = new Set([- '-R',- '--config-dir',- '--git-protocol',- '--hostname',- '--repo',-]);-const GITHUB_PR_URL_PATTERN = /https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)/i;const BRANCH_OUTPUT_PATTERNS = [/Switched to (?:a new )?branch ['"]([^'"\n]+)['"]/i,/Already on ['"]([^'"\n]+)['"]/i,@@ -179,11 +149,6 @@ const isGitExecutable = (token: string): boolean => {return executable === 'git' || executable === 'git.exe';};-const isGhExecutable = (token: string): boolean => {- const executable = getExecutableName(token);- return executable === 'gh' || executable === 'gh.exe';-};-const normalizeBranch = (branch?: string): string | undefined => {const value = branch?.trim();// A `$`/backtick here is an unexpanded shell construct, not a branch name.@@ -249,13 +214,6 @@ const parseBranchFromGitOutput = (content?: string): string | undefined => {}};-const parsePrUrlFromOutput = (content?: string): { number: number; url: string } | undefined => {- const match = content?.match(GITHUB_PR_URL_PATTERN);- if (!match) return undefined;-- return { number: Number(match[1]), url: match[0] };-};-const getOptionValue = (tokens: string[],index: number,@@ -357,76 +315,6 @@ const parseGitBranchSwitch = (return findInCommand(command, parseGitBranchSwitchTokens);};-const parseGhPrCreateTokens = (- tokens: string[],- resultContent?: string,- env?: ShellEnv,-): PullRequestCreateInfo | undefined => {- const prUrl = parsePrUrlFromOutput(resultContent);- if (!prUrl) return undefined;-- let i = consumeCommandPreamble(tokens);- if (!isGhExecutable(tokens[i] ?? '')) return undefined;- i += 1;-- while (i < tokens.length && tokens[i].startsWith('-')) {- if (GH_GLOBAL_VALUE_FLAGS.has(stripQuotes(tokens[i]))) i += 2;- else i += 1;- }-- if (stripQuotes(tokens[i] ?? '') !== 'pr') return undefined;- i += 1;- if (stripQuotes(tokens[i] ?? '') !== 'create') return undefined;- i += 1;-- let branch: string | undefined;- let isDraft = false;- let title: string | undefined;- for (; i < tokens.length; i += 1) {- const token = stripQuotes(tokens[i]);- if (token === '--draft') {- isDraft = true;- continue;- }-- const titleValue = getOptionValue(tokens, i, ['-t', '--title'], env);- if (titleValue.value) {- title = titleValue.value;- if (titleValue.skipNext) i += 1;- continue;- }-- const headValue = getOptionValue(tokens, i, ['-H', '--head'], env);- if (headValue.value) {- branch = normalizeBranch(headValue.value) ?? branch;- if (headValue.skipNext) i += 1;- continue;- }-- if (GH_VALUE_FLAGS.has(token)) {- i += 1;- continue;- }- }-- return {- branch,- pullRequest: {- ...(isDraft ? { isDraft: true } : {}),- number: prUrl.number,- state: 'OPEN',- title: title || `PR #${prUrl.number}`,- url: prUrl.url,- },- };-};--const parseGhPrCreate = (- command: string | string[],- resultContent?: string,-): PullRequestCreateInfo | undefined =>- findInCommand(command, (tokens, env) => parseGhPrCreateTokens(tokens, resultContent, env));-/*** One ref a `git push` moved, as the push itself reported it.* `local` is the ref that was pushed (a branch name, or `HEAD`); `remote` the@@ -938,8 +826,9 @@ export const recordWorktreeAdd = async (params: {* - `git worktree add` selects the created worktree and explicit branch.* - `git worktree remove` of that worktree returns the topic to its source repo.* - `git switch` / confirmed `git checkout` updates the branch snapshot.- * - `git push` records the remote ref the branch publishes to.- * - `gh pr create` binds the created PR URL to the topic.+ * - `git push` records the remote ref the branch publishes to, and links the+ * pull request the pushed branch already has (as a server Work row).+ * - A branch the command created is recorded as the conversation's own.*/export const recordGitCommandEffects = async (params: {command: string | string[];@@ -950,8 +839,6 @@ export const recordGitCommandEffects = async (params: {}): Promise<void> => {const { command, resultContent, toolCallId, topicId } = params;const state = getChatStoreState();- // Better Coding Experience: PRs reach the topic only as server Work rows.- const betterCoding = labPreferSelectors.enableBetterCodingExperience(getUserStoreState());const topic = topicSelectors.getTopicById(topicId)(state);const currentConfig = topic?.metadata?.workingDirectoryConfig;@@ -1000,25 +887,18 @@ export const recordGitCommandEffects = async (params: {// in the creation flag that named it. A chain that recovers from a failure// (`git switch -c x || git switch x`) succeeds whether or not the creation// did, so only git's own output can say so there.- if (betterCoding) {- const commandSaysCreated = !hasFailureRecovery(command);- const created =- parseCreatedBranch(resultContent) ??- (commandSaysCreated && branchSwitch && 'created' in branchSwitch- ? branchSwitch.branch- : undefined) ??- (() => {- if (!commandSaysCreated) return undefined;- const worktreeAdd = parseWorktreeAddInfo(command, source);- return worktreeAdd?.createdBranch ? worktreeAdd.branch : undefined;- })();- nextConfig = applyOwnBranchToConfig(nextConfig, created);- }-- const prCreate = betterCoding ? undefined : parseGhPrCreate(command, resultContent);- if (prCreate) {- nextConfig = applyPullRequestToConfig(nextConfig, source, prCreate);- }+ const commandSaysCreated = !hasFailureRecovery(command);+ const created =+ parseCreatedBranch(resultContent) ??+ (commandSaysCreated && branchSwitch && 'created' in branchSwitch+ ? branchSwitch.branch+ : undefined) ??+ (() => {+ if (!commandSaysCreated) return undefined;+ const worktreeAdd = parseWorktreeAddInfo(command, source);+ return worktreeAdd?.createdBranch ? worktreeAdd.branch : undefined;+ })();+ nextConfig = applyOwnBranchToConfig(nextConfig, created);if (!isEqual(currentConfig, nextConfig)) {await state.updateTopicMetadata(topicId, { workingDirectoryConfig: nextConfig });@@ -1026,7 +906,7 @@ export const recordGitCommandEffects = async (params: {// A checkout performed inside the heterogeneous CLI bypasses ChatInput's// BranchSwitcher, which normally refreshes this cache itself. Revalidate the- // shared branch key so the control bar (and its branch-keyed PR lookup) follows+ // shared branch key so the control bar follows// the repository's actual HEAD immediately after the tool call completes. A push// is refreshed too: it establishes the branch's remote ref, which this key carries.if (branchSwitch || pushUpstream) {@@ -1038,7 +918,7 @@ export const recordGitCommandEffects = async (params: {await getGitStatusStoreState().revalidateGitStatus(revalidateDeviceId, source, ['branch']);const branch = nextConfig?.git?.branch;- if (betterCoding && pushUpstream && toolCallId && branch) {+ if (pushUpstream && toolCallId && branch) {// Not awaited: the device lookup and the server's re-read may retry.void linkPushedPullRequests({branch,@@ -1100,8 +980,7 @@ export const recordWorktreeEnter = async (params: {if (!worktreeInfo || !source || worktreeInfo.path === source) return;let nextConfig = applyWorktreeAddToConfig(currentConfig, source, worktreeInfo);- if (labPreferSelectors.enableBetterCodingExperience(getUserStoreState()))- nextConfig = applyOwnBranchToConfig(nextConfig, parseCreatedBranch(content))!;+ nextConfig = applyOwnBranchToConfig(nextConfig, parseCreatedBranch(content))!;if (isEqual(currentConfig, nextConfig)) return;await state.updateTopicMetadata(topicId, { workingDirectoryConfig: nextConfig });diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.tsindex da1b76b97c6..a6b875f09ba 100644--- a/src/store/user/slices/preference/selectors/labPrefer.ts+++ b/src/store/user/slices/preference/selectors/labPrefer.ts@@ -10,8 +10,6 @@ export const labPreferSelectors = {enableAgentIdentity: (s: UserState): boolean => s.preference.lab?.enableAgentIdentity ?? false,enableArtifactDeployment: (s: UserState): boolean =>s.preference.lab?.enableArtifactDeployment ?? false,- enableBetterCodingExperience: (s: UserState): boolean =>- s.preference.lab?.enableBetterCodingExperience ?? false,enableClaudeCodeSdk: (s: UserState): boolean => s.preference.lab?.enableClaudeCodeSdk ?? false,enableCodexAppServer: (s: UserState): boolean => s.preference.lab?.enableCodexAppServer ?? false,enableDeviceTunnel: (s: UserState): boolean => s.preference.lab?.enableDeviceTunnel ?? false,diff --git a/src/store/user/slices/settings/selectors/general.test.ts b/src/store/user/slices/settings/selectors/general.test.tsindex 70dde8d6f3b..16932cc5cbb 100644--- a/src/store/user/slices/settings/selectors/general.test.ts+++ b/src/store/user/slices/settings/selectors/general.test.ts@@ -97,25 +97,14 @@ describe('settingsSelectors', () => {});describe('followUpBehavior', () => {- it('should stay on the legacy behavior while the lab is off, whatever is stored', () => {- const s: UserState = merge(initialState, {- settings: { general: { followUpBehavior: 'queue' } },- });-- expect(userGeneralSettingsSelectors.followUpBehavior(s as UserStore)).toBe('legacy');- });-- it('should default to steer with the lab on', () => {- const s: UserState = merge(initialState, {- preference: { lab: { enableBetterCodingExperience: true } },- });-- expect(userGeneralSettingsSelectors.followUpBehavior(s as UserStore)).toBe('steer');+ it('should default to steer', () => {+ expect(userGeneralSettingsSelectors.followUpBehavior(initialState as UserStore)).toBe(+ 'steer',+ );});- it('should read the stored setting with the lab on', () => {+ it('should read the stored setting', () => {const s: UserState = merge(initialState, {- preference: { lab: { enableBetterCodingExperience: true } },settings: { general: { followUpBehavior: 'queue' } },});diff --git a/src/store/user/slices/settings/selectors/general.ts b/src/store/user/slices/settings/selectors/general.tsindex 1f7283cb354..3d6705c301f 100644--- a/src/store/user/slices/settings/selectors/general.ts+++ b/src/store/user/slices/settings/selectors/general.ts@@ -1,4 +1,8 @@-import { type FollowUpMode, type InterfaceDensity, resolveFollowUpMode } from '@lobechat/types';+import {+ DEFAULT_FOLLOW_UP_BEHAVIOR,+ type FollowUpBehavior,+ type InterfaceDensity,+} from '@lobechat/types';import { DEFAULT_LANG } from '@/const/locale';import { type Locales, normalizeLocale } from '@/locales/resources';@@ -55,15 +59,9 @@ const interfaceDensity = (s: UserStore): InterfaceDensity =>const workflowStreamingExpandLevel = (s: UserStore) =>generalConfig(s).expandWorkflowWhileStreaming ? 'full' : 'collapsed';-/**- * What a message sent during a run does. `legacy` (lab off) keeps the- * behavior from before the setting existed; the setting defaults to steer.- */-const followUpBehavior = (s: UserStore): FollowUpMode =>- resolveFollowUpMode(- s.preference.lab?.enableBetterCodingExperience,- generalConfig(s).followUpBehavior,- );+/** What a message sent during a run does; defaults to steer. */+const followUpBehavior = (s: UserStore): FollowUpBehavior =>+ generalConfig(s).followUpBehavior ?? DEFAULT_FOLLOW_UP_BEHAVIOR;export const userGeneralSettingsSelectors = {animationMode,diff --git a/src/store/work/action.ts b/src/store/work/action.tsindex ff044fb87a9..41ee2507c4b 100644--- a/src/store/work/action.ts+++ b/src/store/work/action.ts@@ -85,7 +85,7 @@ export class WorkActionImpl {options?: ReplicaSyncOptions<WorkListItem[], WorkListItem[]>,): ReplicaSyncResult => this.#private.conversationWorks.useSync(params, options);- /** Pull requests linked to a topic (Better Coding Experience); `null` disables the read. */+ /** Pull requests linked to a topic; `null` disables the read. */useFetchTopicPullRequests = (params: TopicPullRequestsParams | null,options?: ReplicaSyncOptions<TopicPullRequestItem[], TopicPullRequestItem[]>,diff --git a/src/store/work/projection.ts b/src/store/work/projection.tsindex 4e92a456d5c..df28cdb0375 100644--- a/src/store/work/projection.ts+++ b/src/store/work/projection.ts@@ -111,7 +111,7 @@ export interface TopicPullRequestsParams {}/**- * The pull requests a topic's Work rows link (Better Coding Experience): the+ * The pull requests a topic's Work rows link: the* control bar's PR chip and the working sidebar's repository card. A reload* paints the last list — with the last known states — before the network* answers. Revalidated by `workService.refreshTopicPullRequests` (run end,