Skip to content

🀯 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.

πŸ› fix(chat-input): keep a topic's cwd tied to the machine it ran on (#21075)

Arvin Xuf36f88da11cc
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index e65541580be..1a90e1880b3 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -104,9 +104,8 @@ interface PlatformTaskEntry {
pid: number;
topicId: string;
/**
- * Workspace that owns the dispatched topic β€” used at exit time so the
- * cleanup notify still scopes to the workspace agentNotify resolves the
- * topic in (the server seeds this via the `runHeteroTask` args).
+ * Workspace owning the dispatched topic (seeded by `runHeteroTask`), so the
+ * exit-time cleanup notify scopes to the workspace agentNotify resolves it in.
*/
workspaceId?: string;
}
@@ -269,13 +268,22 @@ export default class GatewayConnectionCtr extends ControllerModule {
return { enabled: this.service.getKeepAwake() };
}
+ /** Stable device id for persisted topic pins β€” local only, no backfill request. */
+ @IpcMethod()
+ async getStableDeviceId(): Promise<string | undefined> {
+ return this.service.resolveCurrentDeviceId();
+ }
+
@IpcMethod()
async getDeviceInfo(): Promise<{
deviceId: string;
hostname: string;
platform: string;
}> {
- const info = this.service.getDeviceInfo();
+ // Signed in, report the stable id the gateway registers β€” not the pre-connect
+ // fallback β€” so the renderer's "this device" matches the pins it writes.
+ const stableId = await this.service.resolveCurrentDeviceId().catch(() => undefined);
+ const info = { ...this.service.getDeviceInfo(), ...(stableId && { deviceId: stableId }) };
try {
const [serverUrl, token] = await Promise.all([
this.remoteServerConfigCtr.getRemoteServerUrl(),
@@ -298,10 +306,8 @@ export default class GatewayConnectionCtr extends ControllerModule {
}
/**
- * Let the web app wake this desktop and restore its gateway connection from
- * an offline device row. The device id guard matters when the user has more
- * than one registered computer: opening the deep link on a different machine
- * must not silently connect that machine instead.
+ * Wake this desktop from an offline device row. The device id guard keeps a
+ * deep link opened on another registered computer from connecting it instead.
*/
@deviceProtocolHandler('reconnect')
async reconnectFromProtocol({ deviceId }: { deviceId?: string }): Promise<boolean> {
@@ -442,10 +448,8 @@ export default class GatewayConnectionCtr extends ControllerModule {
}
/**
- * Platform-specific handlers the shared `@lobechat/device-control` dispatcher
- * delegates to. Git + workspace-scan methods run inside device-control over
- * `@lobechat/local-file-shell`; only file preview / index (and preview
- * approval) are desktop-specific and routed back to the controllers here.
+ * Desktop handlers for the shared `@lobechat/device-control` dispatcher: only
+ * file preview / index (and preview approval) route back to controllers here.
*/
private get deviceControlDeps(): DeviceControlDeps {
return {
@@ -484,9 +488,8 @@ export default class GatewayConnectionCtr extends ControllerModule {
}
/**
- * Dispatch a generic server-internal device RPC (not an agent tool call) by
- * method name. The dispatch logic lives in `@lobechat/device-control` so the
- * desktop main process and the CLI daemon share one device RPC surface.
+ * Dispatch a server-internal device RPC by method name, via the dispatcher
+ * the desktop and the CLI daemon share (`@lobechat/device-control`).
*/
private async executeDeviceRpc(method: string, params: unknown): Promise<unknown> {
const { executeDeviceRpc: runDeviceRpc } = await import('@lobechat/device-control');
@@ -628,11 +631,8 @@ export default class GatewayConnectionCtr extends ControllerModule {
}
/**
- * Execute an MCP tool call tunneled from the cloud server, for MCP servers
- * only this machine can reach: stdio (the server can't spawn the user's
- * local binary) and localhost / LAN HTTP endpoints (the server's fetch
- * can't reach them). The connection params ride along; we run the call
- * through the local MCP client.
+ * Run a tunneled MCP call through the local MCP client, for servers only this
+ * machine can reach: stdio binaries and localhost / LAN HTTP endpoints.
*/
private async executeMcpCall(mcpCall: {
apiName: string;
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index 041c9116208..f26ea5ae3c5 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -2314,18 +2314,18 @@ describe('GatewayConnectionCtr', () => {
await expect(ctr.getDeviceInfo()).resolves.toMatchObject({ hostname: 'mock-hostname' });
});
- it('should return device information', async () => {
- mockStoreGet.mockImplementation((key: string) => {
- if (key === 'gatewayEnabled') return true;
- if (key === 'gatewayDeviceId') return 'my-device';
- return undefined;
- });
+ // Regression: pre-connect it reported the fallback UUID while pins stored the stable id.
+ it('reports the stable device id once signed in, even before connecting', async () => {
+ mockStoreGet.mockImplementation((key: string) =>
+ key === 'gatewayDeviceId' ? 'my-device' : undefined,
+ );
+ const sub = Buffer.from(JSON.stringify({ sub: 'user-1' })).toString('base64url');
+ vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValueOnce(`h.${sub}.s`);
ctr = new GatewayConnectionCtr(mockApp);
ctr.afterFirstFrame();
-
- const info = await ctr.getDeviceInfo();
- expect(info).toEqual({
- deviceId: 'my-device',
+ const stable = deriveDeviceId('user-1', { fallbackId: 'my-device' }).deviceId;
+ await expect(ctr.getDeviceInfo()).resolves.toEqual({
+ deviceId: stable,
hostname: 'mock-hostname',
platform: process.platform,
});
diff --git a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts
index 5d3bc052f9e..1e4c11b264e 100644
--- a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts
+++ b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts
@@ -518,3 +518,58 @@ describe('GatewayConnectionService auth recovery', () => {
});
});
});
+
+const deriveDeviceIdMock = vi.hoisted(() =>
+ vi.fn((userId: string) => ({ deviceId: `stable-${userId}`, identitySource: 'machine' })),
+);
+
+vi.mock('@lobechat/device-identity', () => ({ deriveDeviceId: deriveDeviceIdMock }));
+
+describe('GatewayConnectionService resolveCurrentDeviceId', () => {
+ const jwt = (sub: string) =>
+ ['h', Buffer.from(JSON.stringify({ sub })).toString('base64url'), 's'].join('.');
+
+ const createService = () => {
+ const app = {
+ browserManager: { broadcastToAllWindows: vi.fn() },
+ storeManager: { get: vi.fn(() => 'fallback-uuid'), set: vi.fn() },
+ } as unknown as App;
+ const service = new GatewayConnectionService(app);
+ service.loadOrCreateDeviceId();
+ return service;
+ };
+
+ // Regression: before the gateway connected, topic pins stored the install's
+ // fallback UUID, which stops naming this machine once the identity is derived.
+ it('derives the signed-in user stable id instead of the pre-connect fallback', async () => {
+ const service = createService();
+ service.setTokenProvider(async () => jwt('user-1'));
+
+ expect(service.getDeviceInfo().deviceId).toBe('fallback-uuid');
+ await expect(service.resolveCurrentDeviceId()).resolves.toBe('stable-user-1');
+ });
+
+ it('returns nothing while signed out', async () => {
+ const service = createService();
+ service.setTokenProvider(async () => null);
+
+ await expect(service.resolveCurrentDeviceId()).resolves.toBeUndefined();
+ });
+
+ // Regression: every send re-derived the identity, a synchronous machine-id
+ // read in Electron's main process, despite the documented session cache.
+ it('derives the identity once per user and again when the user changes', async () => {
+ const service = createService();
+ let user = 'user-1';
+ service.setTokenProvider(async () => jwt(user));
+ deriveDeviceIdMock.mockClear();
+
+ await service.resolveCurrentDeviceId();
+ await service.resolveCurrentDeviceId();
+ expect(deriveDeviceIdMock).toHaveBeenCalledTimes(1);
+
+ user = 'user-2';
+ await expect(service.resolveCurrentDeviceId()).resolves.toBe('stable-user-2');
+ expect(deriveDeviceIdMock).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index 8d59dec1a5a..6fbdef43cd6 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -19,7 +19,7 @@ import type {
ToolCallRequestMessage,
ToolCallResponseMessage,
} from '@lobechat/device-gateway-client';
-import type { IdentitySource } from '@lobechat/device-identity';
+import type { DeviceIdentity, IdentitySource } from '@lobechat/device-identity';
import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';
import { createRuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';
import { app, powerSaveBlocker } from 'electron';
@@ -160,6 +160,7 @@ export default class GatewayConnectionService extends ServiceModule {
private statusBroadcastTimer: ReturnType<typeof setTimeout> | null = null;
private identitySource: IdentitySource | null = null;
+ private identityCache: { identity: DeviceIdentity; userId: string } | null = null;
/**
* Bundled CLI capability probe. Each probe starts an Electron-as-node CLI plus a Codex
@@ -204,16 +205,12 @@ export default class GatewayConnectionService extends ServiceModule {
// ─── Configuration ───
- /**
- * Set token provider function (to decouple from RemoteServerConfigCtr)
- */
+ /** Set token provider function (to decouple from RemoteServerConfigCtr) */
setTokenProvider(provider: () => Promise<string | null>) {
this.tokenProvider = provider;
}
- /**
- * Set token refresher function (for auth_expired handling)
- */
+ /** Set token refresher function (for auth_expired handling) */
setTokenRefresher(refresher: () => Promise<{ error?: string; success: boolean }>) {
this.tokenRefresher = refresher;
}
@@ -293,11 +290,7 @@ export default class GatewayConnectionService extends ServiceModule {
// ─── Device ID ───
- /**
- * Ensure a stored fallback id exists. Pre-login this doubles as the device id
- * shown by `getDeviceInfo`; once a userId is available `resolveDeviceIdentity`
- * replaces it with a stable machine-derived id.
- */
+ /** Ensure a stored fallback id (pre-login device id until `resolveDeviceIdentity`). */
loadOrCreateDeviceId() {
const stored = this.app.storeManager.get('gatewayDeviceId') as string | undefined;
if (stored) {
@@ -310,16 +303,17 @@ export default class GatewayConnectionService extends ServiceModule {
}
/**
- * Derive the stable, user-scoped device id. Survives LobeHub reinstalls
- * because it hashes the OS machine id; falls back to the stored random UUID
- * when the machine id is unavailable. Caches the result for this session.
+ * Stable, user-scoped device id: hashes the OS machine id (stored UUID when
+ * unavailable). Cached per user β€” machine-id reads are synchronous here.
*/
- async resolveDeviceIdentity(
- userId: string,
- ): Promise<{ deviceId: string; identitySource: IdentitySource }> {
- const { deriveDeviceId } = await import('@lobechat/device-identity');
- const fallbackId = this.app.storeManager.get('gatewayDeviceId') as string | undefined;
- const identity = deriveDeviceId(userId, { fallbackId });
+ async resolveDeviceIdentity(userId: string): Promise<DeviceIdentity> {
+ let identity = this.identityCache?.userId === userId ? this.identityCache.identity : undefined;
+ if (!identity) {
+ const { deriveDeviceId } = await import('@lobechat/device-identity');
+ const fallbackId = this.app.storeManager.get('gatewayDeviceId') as string | undefined;
+ identity = deriveDeviceId(userId, { fallbackId });
+ this.identityCache = { identity, userId };
+ }
this.deviceId = identity.deviceId;
this.identitySource = identity.identitySource;
return identity;
@@ -329,6 +323,13 @@ export default class GatewayConnectionService extends ServiceModule {
return this.deviceId || 'unknown';
}
+ /** Signed-in user's stable device id, derived locally; none while signed out. */
+ async resolveCurrentDeviceId(): Promise<string | undefined> {
+ const token = await this.tokenProvider?.();
+ const userId = token ? this.extractUserIdFromToken(token) : undefined;
+ return userId ? (await this.resolveDeviceIdentity(userId)).deviceId : undefined;
+ }
+
/**
* Connection routing key β€” the gateway's stale-socket dedupe key, decoupled
* from the stable `deviceId`. Reuses the persisted random UUID (historically
@@ -374,13 +375,7 @@ export default class GatewayConnectionService extends ServiceModule {
*/
async matchesDeviceId(deviceId: string): Promise<boolean> {
if (this.getDeviceId() === deviceId) return true;
-
- const token = await this.tokenProvider?.();
- const userId = token ? this.extractUserIdFromToken(token) : undefined;
- if (userId) {
- const identity = await this.resolveDeviceIdentity(userId);
- if (identity.deviceId === deviceId) return true;
- }
+ if ((await this.resolveCurrentDeviceId()) === deviceId) return true;
for (const workspaceId of this.getPersistedWorkspaceEnrollments()) {
const identity = await this.resolveWorkspaceDeviceIdentity(workspaceId);
diff --git a/apps/workbench/app/stubs/electronStore.ts b/apps/workbench/app/stubs/electronStore.ts
index 3fb6d064d3b..035e49af674 100644
--- a/apps/workbench/app/stubs/electronStore.ts
+++ b/apps/workbench/app/stubs/electronStore.ts
@@ -6,6 +6,8 @@ interface GatewayDeviceInfo {
// directory; SSR has no gateway device, so every reader takes its web branch.
const emptyState = {
gatewayDeviceInfo: undefined as GatewayDeviceInfo | undefined,
+ // No desktop identity in SSR, so no topic pin is ever written from here.
+ resolveGatewayDeviceId: async (): Promise<string | undefined> => undefined,
};
// Renderable stand-in, not a throwing proxy: shared components may call the
diff --git a/apps/workbench/app/stubs/surface.test.ts b/apps/workbench/app/stubs/surface.test.ts
index 7d860b6459e..3a395be9407 100644
--- a/apps/workbench/app/stubs/surface.test.ts
+++ b/apps/workbench/app/stubs/surface.test.ts
@@ -74,6 +74,19 @@ describe('workbench stub surface', () => {
expect(stubUsageGaps(surface, usage!)).toEqual([]);
});
+ // Regression: the send path awaits this member on the electron store, so the
+ // SSR build rejected the module graph until the stub carried it.
+ it('covers the device-id resolver the chat send path calls', () => {
+ const surface = parseStubSurface(readFileSync(path.join(stubDir, 'electronStore.ts'), 'utf8'));
+ const usage = collectStubUsage(
+ `import { getElectronStoreState } from '@/store/electron';
+ void getElectronStoreState().resolveGatewayDeviceId();`,
+ '@/store/electron',
+ );
+
+ expect(stubUsageGaps(surface, usage!)).toEqual([]);
+ });
+
it('does not treat a catch-all selector proxy as covering new methods', () => {
const surface = parseStubSurface(`
export const fileChatSelectors = new Proxy({}, { get: () => () => undefined });
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index 2b7f54719a5..c641183abb6 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -279,6 +279,7 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
canDisplayExecutionTarget,
canSelectExecutionTarget,
isPreferenceLoading: isWorkspacePreferenceLoading,
+ topicDeviceUnknown,
workspaceScoped,
} = useEffectiveAgencyConfig(agentId, { topicId });
const canShowExecutionTarget = canUseResource && canDisplayExecutionTarget;
@@ -481,21 +482,13 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
: undefined;
// The picker splits by whether the caller is inside a workspace agent:
- //
// - **Personal agent** β€” flat list of the caller's personal-scope devices
- // only; there is no workspace context so no group split makes sense.
- // Never show `scope: 'workspace'` rows here (they belong to a workspace
- // the personal-mode agent has nothing to do with).
- //
- // - **Workspace agent** β€” split into `Private` and `Workspace` groups by
- // workspace-scope visibility, and drop `scope: 'personal'` entirely.
- // Personal devices are the caller's account-tier machines: they belong
- // to a different identity than the workspace agent runs under
- // (per-user `sha256(machineUUID + userId)` vs
- // `sha256(machineUUID + workspace:<id>)`), so binding one to a workspace
- // agent conflates identities. The `local` chip already covers "run on my
- // machine" as a per-user override without needing to expose
- // the raw personal deviceId.
+ // only; never `scope: 'workspace'` rows (no workspace context here).
+ // - **Workspace agent** β€” `Private` / `Workspace` groups by workspace-scope
+ // visibility, dropping `scope: 'personal'`: personal devices run under a
+ // different identity (`sha256(machineUUID + userId)` vs
+ // `sha256(machineUUID + workspace:<id>)`), and the `local` chip already
+ // covers "run on my machine" as a per-user override.
//
// Naming β€” Personal is reserved for the account-tier concept; workspace
// groupings say Private/Workspace (私人/ε·₯作区) instead.
@@ -553,6 +546,13 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
t('heteroAgent.executionTarget.unknownDevice'))
: t('heteroAgent.executionTarget.workspaceGroup');
}
+ // A cwd with no recorded machine: naming the agent default here would pair
+ // it with a path that may live on another computer.
+ const isMachineChip = chipExecutionTarget === 'local' || chipExecutionTarget === 'device';
+ if (topicDeviceUnknown && canShowExecutionTargetSelector && isMachineChip) {
+ chipIcon = <ExecutionTargetIcon target={'device'} />;
+ chipLabel = t('heteroAgent.executionTarget.unknownDevice');
+ }
// Tag the row that runs this topic, so it reads as the conversation's own
// machine rather than the agent default. A `fixed` target may point
diff --git a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
index 2e33faf422f..7ba22a30f82 100644
--- a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
@@ -18,6 +18,7 @@ const testState = vi.hoisted(() => ({
updateTopicMetadata: vi.fn(),
},
currentDeviceId: 'this-machine' as string | undefined,
+ resolveGatewayDeviceId: vi.fn(async (): Promise<string | undefined> => undefined),
effective: {
agencyConfig: undefined as Record<string, unknown> | undefined,
isPreferenceLoading: false,
@@ -51,6 +52,7 @@ vi.mock('@/store/device', () => ({
}));
vi.mock('@/store/electron', () => ({
+ getElectronStoreState: () => ({ resolveGatewayDeviceId: testState.resolveGatewayDeviceId }),
useElectronStore: (selector: (s: { gatewayDeviceInfo?: { deviceId?: string } }) => unknown) =>
selector({ gatewayDeviceInfo: { deviceId: testState.currentDeviceId } }),
}));
@@ -241,6 +243,32 @@ describe('useCommitWorkingDirectory β€” topic device provenance', () => {
]);
expect(patch.boundDeviceId).toBeUndefined();
});
+
+ // Regression: an unresolved target wrote the new path with no machine, which
+ // erased the topic's pin and left the picker on the agent default.
+ it('keeps the topic pin when the target machine cannot be resolved', async () => {
+ testState.effective.agencyConfig = { executionTarget: 'device' };
+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
+ await result.current.commit({ path: '/Users/me/repo-c' });
+
+ expect(testState.chat.updateTopicMetadata).toHaveBeenCalledWith(
+ 'topic-id',
+ expect.objectContaining({ boundDeviceId: 'device-a', workingDirectory: '/Users/me/repo-c' }),
+ );
+ });
+
+ it('pins an unbound topic to this desktop when the target cannot be resolved', async () => {
+ testState.effective.agencyConfig = { executionTarget: 'device' };
+ testState.chat.topic = { metadata: {} } as ChatTopic;
+ testState.resolveGatewayDeviceId.mockResolvedValueOnce('this-desktop');
+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
+ await result.current.commit({ path: '/Users/me/repo-c' });
+
+ expect(testState.chat.updateTopicMetadata).toHaveBeenCalledWith(
+ 'topic-id',
+ expect.objectContaining({ boundDeviceId: 'this-desktop' }),
+ );
+ });
});
describe('useCommitWorkingDirectory β€” commitAgentDefault', () => {
diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
index 7e170f1c8a7..e2d206f47a2 100644
--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
@@ -12,7 +12,7 @@ import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import { useDeviceStore } from '@/store/device';
-import { useElectronStore } from '@/store/electron';
+import { getElectronStoreState, useElectronStore } from '@/store/electron';
export interface CommitWorkingDirectoryOptions extends CommitAgentDefaultOptions {
/**
@@ -181,8 +181,14 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
// The pin is a bare path that only holds on the machine it was picked
// for, and the server skips a topic pin whose `boundDeviceId` names a
// different device. Re-stamp it with every write so a conversation
- // moved to another device keeps the directory just chosen there.
- boundDeviceId: entry ? writeDeviceId : undefined,
+ // moved to another device keeps the directory just chosen there. An
+ // unresolved target keeps the topic's own pin (or this desktop's id)
+ // rather than leaving the new path with no machine at all.
+ boundDeviceId: entry
+ ? (writeDeviceId ??
+ activeTopic?.metadata?.boundDeviceId ??
+ (await getElectronStoreState().resolveGatewayDeviceId()))
+ : undefined,
...(shouldUpdateHeteroSession ? { heteroSessionId: scopedHeteroSessionId } : {}),
workingDirectory: sessionCwd,
workingDirectoryConfig: entry ? toAgentWorkingDirConfig(entry) : undefined,
diff --git a/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.test.ts b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.test.ts
index e33dcacc0c5..e77af228259 100644
--- a/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.test.ts
+++ b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.test.ts
@@ -6,8 +6,9 @@ import { useTopicAwareTargetSelect } from './useTopicAwareTargetSelect';
const state = vi.hoisted(() => ({
activeTopicId: undefined as string | undefined,
confirmModal: vi.fn(),
+ resolveGatewayDeviceId: vi.fn(),
selectExecutionTarget: vi.fn(),
- topics: {} as Record<string, { boundDeviceId?: string }>,
+ topics: {} as Record<string, { boundDeviceId?: string; workingDirectory?: string }>,
updateTopicMetadata: vi.fn(),
}));
@@ -28,6 +29,10 @@ vi.mock('@/services/electron/localFileService', () => ({
localFileService: { ensureSandboxWorkspace: vi.fn() },
}));
+vi.mock('@/store/electron', () => ({
+ getElectronStoreState: () => ({ resolveGatewayDeviceId: state.resolveGatewayDeviceId }),
+}));
+
vi.mock('./useCommitWorkingDirectory', () => ({
useCommitWorkingDirectory: () => ({ commit: vi.fn() }),
}));
@@ -53,10 +58,11 @@ const devices = [
{ deviceId: 'device-b', friendlyName: 'Device B' },
];
-const renderSelect = (topicId: string | null) =>
+const renderSelect = (topicId: string | null, currentDeviceId?: string) =>
renderHook(() =>
useTopicAwareTargetSelect({
agentId: 'agent-1',
+ currentDeviceId,
devices,
selectExecutionTarget: state.selectExecutionTarget,
topicId,
@@ -71,6 +77,7 @@ beforeEach(() => {
'pane-topic': { boundDeviceId: 'device-a' },
};
state.confirmModal.mockReset();
+ state.resolveGatewayDeviceId.mockReset().mockResolvedValue('stable-this-desktop');
state.selectExecutionTarget.mockReset().mockResolvedValue(true);
state.updateTopicMetadata.mockReset().mockResolvedValue(undefined);
});
@@ -120,4 +127,55 @@ describe('useTopicAwareTargetSelect', () => {
localSandbox: undefined,
});
});
+
+ // Regression: a cwd with no recorded machine kept following the agent
+ // default, so the chip named whichever device was picked last.
+ it('pins a topic with an unrecorded machine to the device the user picks', async () => {
+ state.topics = { 'legacy-topic': { workingDirectory: '/Users/other/repo' } };
+ const { result } = renderSelect('legacy-topic');
+
+ await act(() => result.current.selectTarget('device', 'device-a'));
+
+ expect(state.confirmModal).not.toHaveBeenCalled();
+ expect(state.selectExecutionTarget).toHaveBeenCalledWith('device', 'device-a', {
+ localSandbox: undefined,
+ });
+ expect(state.updateTopicMetadata).toHaveBeenCalledWith('legacy-topic', {
+ boundDeviceId: 'device-a',
+ });
+ });
+
+ it('does not pin a topic with an unrecorded machine to the cloud sandbox', async () => {
+ state.topics = { 'legacy-topic': { workingDirectory: '/Users/other/repo' } };
+ const { result } = renderSelect('legacy-topic');
+
+ await act(() => result.current.selectTarget('sandbox'));
+
+ expect(state.updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ // Regression: a failed target save still rebound the topic, so the topic and
+ // the agent settings disagreed about where the next run goes.
+ it('leaves an unrecorded topic unpinned when the target save fails', async () => {
+ state.topics = { 'legacy-topic': { workingDirectory: '/Users/other/repo' } };
+ state.selectExecutionTarget.mockResolvedValue(false);
+ const { result } = renderSelect('legacy-topic');
+
+ await act(() => result.current.selectTarget('device', 'device-a'));
+
+ expect(state.updateTopicMetadata).not.toHaveBeenCalled();
+ });
+
+ // Regression: before the gateway connects, `currentDeviceId` is the install's
+ // fallback UUID; pinning it routes later turns to a device that no longer exists.
+ it('pins a local pick to the stable device id rather than the cached one', async () => {
+ state.topics = { 'legacy-topic': { workingDirectory: '/Users/other/repo' } };
+ const { result } = renderSelect('legacy-topic', 'fallback-uuid');
+
+ await act(() => result.current.selectTarget('local'));
+
+ expect(state.updateTopicMetadata).toHaveBeenCalledWith('legacy-topic', {
+ boundDeviceId: 'stable-this-desktop',
+ });
+ });
});
diff --git a/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.ts b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.ts
index 0e2c8f9ae43..abf69cc6073 100644
--- a/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.ts
+++ b/src/features/ChatInput/ControlBar/useTopicAwareTargetSelect.ts
@@ -4,11 +4,12 @@ import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import type { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
-import { getTopicBoundDeviceId } from '@/helpers/executionTarget';
+import { getTopicBoundDeviceId, isTopicDeviceUnknown } from '@/helpers/executionTarget';
import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
import { localFileService } from '@/services/electron/localFileService';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
+import { getElectronStoreState } from '@/store/electron';
import { moveTopicToTarget } from './moveTopicToTarget';
import { useCommitWorkingDirectory } from './useCommitWorkingDirectory';
@@ -87,13 +88,20 @@ export const useTopicAwareTargetSelect = ({
const topicDeviceId = useChatStore((s) =>
getTopicBoundDeviceId(topicId ? topicSelectors.getTopicById(topicId)(s) : undefined, agentId),
);
+ const topicDeviceUnknown = useChatStore((s) =>
+ isTopicDeviceUnknown(
+ topicId ? topicSelectors.getTopicById(topicId)(s) : undefined,
+ agentId,
+ undefined,
+ ),
+ );
const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);
const selectTarget = useCallback(
async (target: DeviceExecutionTarget, deviceId?: string, localSandbox?: boolean) => {
const apply = async () => {
if (localSandbox) await ensureSandboxWorkingDirectory();
- await selectExecutionTarget(target, deviceId, { localSandbox });
+ return selectExecutionTarget(target, deviceId, { localSandbox });
};
const nextMachineId =
@@ -102,7 +110,19 @@ export const useTopicAwareTargetSelect = ({
// is β€” leave the topic pin alone rather than unbinding it.
const machineKnown = target !== 'local' || !!currentDeviceId;
if (!topicId || !topicDeviceId || !machineKnown || nextMachineId === topicDeviceId) {
- await apply();
+ const saved = await apply();
+ // A topic whose cwd never recorded its machine: this pick is the user
+ // naming it, so pin it β€” nothing on another machine is left behind.
+ // Only once the target saved, or topic and agent would disagree; and
+ // `local` pins the stable id, since `currentDeviceId` may still be the
+ // pre-connect fallback.
+ if (saved && topicId && topicDeviceUnknown && machineKnown) {
+ const pinId =
+ target === 'local'
+ ? await getElectronStoreState().resolveGatewayDeviceId()
+ : nextMachineId;
+ if (pinId) await updateTopicMetadata(topicId, { boundDeviceId: pinId });
+ }
return;
}
@@ -149,6 +169,7 @@ export const useTopicAwareTargetSelect = ({
selectExecutionTarget,
t,
topicDeviceId,
+ topicDeviceUnknown,
topicId,
updateTopicMetadata,
],
diff --git a/src/helpers/executionTarget.test.ts b/src/helpers/executionTarget.test.ts
index 7243a210a73..e050d19b640 100644
--- a/src/helpers/executionTarget.test.ts
+++ b/src/helpers/executionTarget.test.ts
@@ -8,7 +8,6 @@ import {
type ExecutionPlan,
executionPlanToManifestExecutionEnv,
executionTargetToRuntimeMode,
- getTopicBoundDeviceId,
isDeviceLockedPlan,
isHeterogeneousSandboxExecutionAvailable,
isLocalSandboxEnabled,
@@ -1335,28 +1334,6 @@ describe('canExecutionTargetReadLocalPaths', () => {
});
});
-describe('getTopicBoundDeviceId', () => {
- it('returns the machine an agent topic is pinned to', () => {
- expect(
- getTopicBoundDeviceId({ agentId: 'agt', metadata: { boundDeviceId: 'dev-a' } }, 'agt'),
- ).toBe('dev-a');
- });
-
- it('ignores another agent topic and a group topic owned by someone else', () => {
- expect(
- getTopicBoundDeviceId({ agentId: 'other', metadata: { boundDeviceId: 'dev-a' } }, 'agt'),
- ).toBeUndefined();
- expect(
- getTopicBoundDeviceId({ groupId: 'grp', metadata: { boundDeviceId: 'dev-a' } }, 'agt'),
- ).toBeUndefined();
- });
-
- it('returns nothing for an unbound topic', () => {
- expect(getTopicBoundDeviceId({ agentId: 'agt', metadata: {} }, 'agt')).toBeUndefined();
- expect(getTopicBoundDeviceId(undefined, 'agt')).toBeUndefined();
- });
-});
-
describe('applyTopicDeviceBinding', () => {
it('keeps a topic on its remote device after the agent default moved elsewhere', () => {
const result = applyTopicDeviceBinding(
diff --git a/src/helpers/executionTarget.topicDevice.test.ts b/src/helpers/executionTarget.topicDevice.test.ts
new file mode 100644
index 00000000000..581a8e53c04
--- /dev/null
+++ b/src/helpers/executionTarget.topicDevice.test.ts
@@ -0,0 +1,75 @@
+import type { LobeAgentAgencyConfig } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { getTopicBoundDeviceId, isTopicDeviceUnknown } from './executionTarget';
+
+describe('getTopicBoundDeviceId', () => {
+ it('returns the machine an agent topic is pinned to', () => {
+ expect(
+ getTopicBoundDeviceId({ agentId: 'agt', metadata: { boundDeviceId: 'dev-a' } }, 'agt'),
+ ).toBe('dev-a');
+ });
+
+ it('ignores another agent topic and a group topic owned by someone else', () => {
+ expect(
+ getTopicBoundDeviceId({ agentId: 'other', metadata: { boundDeviceId: 'dev-a' } }, 'agt'),
+ ).toBeUndefined();
+ expect(
+ getTopicBoundDeviceId({ groupId: 'grp', metadata: { boundDeviceId: 'dev-a' } }, 'agt'),
+ ).toBeUndefined();
+ });
+
+ it('returns nothing for an unbound topic', () => {
+ expect(getTopicBoundDeviceId({ agentId: 'agt', metadata: {} }, 'agt')).toBeUndefined();
+ expect(getTopicBoundDeviceId(undefined, 'agt')).toBeUndefined();
+ });
+});
+
+describe('isTopicDeviceUnknown', () => {
+ const deviceTarget: LobeAgentAgencyConfig = { boundDeviceId: 'dev-b', executionTarget: 'device' };
+
+ // Regression: a topic whose cwd lives on another computer showed the agent
+ // default machine as if the conversation belonged to it.
+ it('flags a topic that holds a cwd but never recorded its machine', () => {
+ const topic = { agentId: 'agt', metadata: { workingDirectory: '/Users/other/repo' } };
+ expect(isTopicDeviceUnknown(topic, 'agt', deviceTarget)).toBe(true);
+ expect(
+ isTopicDeviceUnknown(
+ { agentId: 'agt', metadata: { workingDirectoryConfig: { path: '/Users/other/repo' } } },
+ 'agt',
+ deviceTarget,
+ ),
+ ).toBe(true);
+ });
+
+ it('trusts a recorded machine and a topic without a cwd', () => {
+ expect(
+ isTopicDeviceUnknown(
+ { agentId: 'agt', metadata: { boundDeviceId: 'dev-a', workingDirectory: '/repo' } },
+ 'agt',
+ deviceTarget,
+ ),
+ ).toBe(false);
+ expect(isTopicDeviceUnknown({ agentId: 'agt', metadata: {} }, 'agt', deviceTarget)).toBe(false);
+ expect(isTopicDeviceUnknown(undefined, 'agt', deviceTarget)).toBe(false);
+ });
+
+ it('leaves project-directory topics, other owners and fixed targets alone', () => {
+ const metadata = { workingDirectory: '/repo' };
+ expect(
+ isTopicDeviceUnknown(
+ { agentId: 'agt', metadata, projectWorkingDirectoryId: 'dir' },
+ 'agt',
+ deviceTarget,
+ ),
+ ).toBe(false);
+ expect(isTopicDeviceUnknown({ agentId: 'other', metadata }, 'agt', deviceTarget)).toBe(false);
+ expect(isTopicDeviceUnknown({ groupId: 'grp', metadata }, 'agt', deviceTarget)).toBe(false);
+ expect(
+ isTopicDeviceUnknown({ agentId: 'agt', metadata }, 'agt', {
+ ...deviceTarget,
+ executionTargetSelectionPolicy: 'fixed',
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/src/helpers/executionTarget.ts b/src/helpers/executionTarget.ts
index 26ae9596dbe..f84bdf76fc5 100644
--- a/src/helpers/executionTarget.ts
+++ b/src/helpers/executionTarget.ts
@@ -270,7 +270,12 @@ export const canExecutionTargetReadLocalPaths = (
interface TopicDeviceBindingSource {
agentId?: string | null;
groupId?: string | null;
- metadata?: { boundDeviceId?: string } | null;
+ metadata?: {
+ boundDeviceId?: string;
+ workingDirectory?: string;
+ workingDirectoryConfig?: { path?: string };
+ } | null;
+ projectWorkingDirectoryId?: string | null;
}
/**
@@ -289,6 +294,25 @@ export const getTopicBoundDeviceId = (
return deviceId;
};
+/**
+ * A conversation that holds a cwd but never recorded the machine it belongs
+ * to β€” a row written before device pinning existed. The cwd is a bare path, so
+ * the agent default must not be presented as its machine: the picker says the
+ * machine is unknown until the user names one. Project-directory topics take
+ * their machine from the directory, and a `fixed` target ignores the topic.
+ */
+export const isTopicDeviceUnknown = (
+ topic: TopicDeviceBindingSource | null | undefined,
+ agentId: string | undefined,
+ agencyConfig: LobeAgentAgencyConfig | undefined,
+): boolean => {
+ if (!topic || !agentId || topic.projectWorkingDirectoryId) return false;
+ if (topic.metadata?.boundDeviceId) return false;
+ if (topic.agentId ? topic.agentId !== agentId : !!topic.groupId) return false;
+ if (agencyConfig?.executionTargetSelectionPolicy === 'fixed') return false;
+ return !!(topic.metadata?.workingDirectory || topic.metadata?.workingDirectoryConfig?.path);
+};
+
export interface TopicDeviceBindingResult {
agencyConfig: LobeAgentAgencyConfig | undefined;
workspaceScoped: boolean;
diff --git a/src/hooks/useEffectiveAgencyConfig.test.ts b/src/hooks/useEffectiveAgencyConfig.test.ts
index 9f13b6e866c..09b790c7137 100644
--- a/src/hooks/useEffectiveAgencyConfig.test.ts
+++ b/src/hooks/useEffectiveAgencyConfig.test.ts
@@ -20,7 +20,7 @@ const topicState = vi.hoisted(() => ({
topic: undefined as
| {
agentId?: string;
- metadata?: { boundDeviceId?: string };
+ metadata?: { boundDeviceId?: string; workingDirectory?: string };
projectWorkingDirectoryId?: string;
}
| undefined,
@@ -153,6 +153,7 @@ describe('useEffectiveAgencyConfig', () => {
canDisplayExecutionTarget: true,
canSelectExecutionTarget: true,
isPreferenceLoading: false,
+ topicDeviceUnknown: false,
workspaceScoped: false,
});
});
@@ -191,6 +192,7 @@ describe('useEffectiveAgencyConfig', () => {
canDisplayExecutionTarget: true,
canSelectExecutionTarget: true,
isPreferenceLoading: false,
+ topicDeviceUnknown: false,
workspaceScoped: false,
});
});
@@ -280,6 +282,23 @@ describe('useEffectiveAgencyConfig', () => {
expect(sharedConfig.boundDeviceId).toBe('creator-device');
});
+ // Regression: a cwd with no recorded machine fell back to the agent default
+ // device, and the picker presented that device as the topic's own.
+ it('reports a conversation cwd whose machine was never recorded', () => {
+ setupStores();
+ topicState.topic = { agentId: 'agent-1', metadata: { workingDirectory: '/Users/other/repo' } };
+ const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));
+ expect(result.current.topicDeviceUnknown).toBe(true);
+ expect(result.current.agencyConfig).toEqual(sharedConfig);
+ topicState.topic = {
+ agentId: 'agent-1',
+ metadata: { boundDeviceId: 'dev-a', workingDirectory: '/Users/other/repo' },
+ };
+ expect(renderHook(() => useEffectiveAgencyConfig('agent-1')).result.current).toMatchObject({
+ topicDeviceUnknown: false,
+ });
+ });
+
it('returns undefined config when agentId is missing', () => {
setupStores({ override: { boundDeviceId: 'my-device' }, workspaceId: 'ws-1' });
diff --git a/src/hooks/useEffectiveAgencyConfig.ts b/src/hooks/useEffectiveAgencyConfig.ts
index 569246a71ec..6782210229d 100644
--- a/src/hooks/useEffectiveAgencyConfig.ts
+++ b/src/hooks/useEffectiveAgencyConfig.ts
@@ -5,6 +5,7 @@ import { useAgentManagementAccess } from '@/features/ResourcePermission/useAgent
import {
applyTopicDeviceBinding,
getTopicBoundDeviceId,
+ isTopicDeviceUnknown,
resolveWorkspaceScoped,
} from '@/helpers/executionTarget';
import { useAgentStore } from '@/store/agent';
@@ -32,6 +33,11 @@ export interface UseEffectiveAgencyConfigResult {
* should wait instead of acting on a value that may flip.
*/
isPreferenceLoading: boolean;
+ /**
+ * The conversation holds a cwd but no recorded machine, so `agencyConfig`
+ * fell back to the agent default β€” which may not be where that cwd lives.
+ */
+ topicDeviceUnknown: boolean;
/**
* The effective config still comes from the workspace-shared fallback because
* this member has not explicitly selected an execution target. Callers must
@@ -118,6 +124,13 @@ export const useEffectiveAgencyConfig = (
!!bindingTopicId &&
!!topicSelectors.getTopicById(bindingTopicId)(s)?.projectWorkingDirectoryId,
);
+ const topicDeviceUnknown = useChatStore((s) =>
+ isTopicDeviceUnknown(
+ bindingTopicId ? topicSelectors.getTopicById(bindingTopicId)(s) : undefined,
+ agentId,
+ agentAgencyConfig,
+ ),
+ );
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding(
{
@@ -141,6 +154,7 @@ export const useEffectiveAgencyConfig = (
!isPreferenceLoading &&
agencyConfig?.executionTargetSelectionPolicy !== 'fixed',
isPreferenceLoading,
+ topicDeviceUnknown,
workspaceScoped,
};
};
diff --git a/src/services/electron/gatewayConnection.ts b/src/services/electron/gatewayConnection.ts
index 6e787a46a26..90e4e4ef47d 100644
--- a/src/services/electron/gatewayConnection.ts
+++ b/src/services/electron/gatewayConnection.ts
@@ -24,6 +24,10 @@ class GatewayConnectionService {
getDeviceInfo = async () => {
return ensureElectronIpc().gatewayConnection.getDeviceInfo();
};
+
+ getStableDeviceId = async () => {
+ return ensureElectronIpc().gatewayConnection.getStableDeviceId();
+ };
}
export const gatewayConnectionService = new GatewayConnectionService();
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index ec9c63e7905..fbfc49941ad 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -2786,11 +2786,11 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
});
- // The session now lives on this machine, so the topic is pinned here β€”
- // otherwise a legacy unbound topic follows whatever the agent default
- // becomes and its next turn cannot resume.
+ // The session lives here, so the topic is pinned even before the store has this desktop's id.
it('pins the topic to this machine when it persists the session id', async () => {
- useElectronStore.setState({ gatewayDeviceInfo: { deviceId: 'this-desktop' } as any });
+ const resolveDeviceId = vi
+ .spyOn(useElectronStore.getState(), 'resolveGatewayDeviceId')
+ .mockResolvedValue('this-desktop');
const store = createMockStore({
topicDataMap: { 'agent-1__main': { items: [{ id: 'topic-1', metadata: {} }] } },
});
@@ -2810,7 +2810,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
heteroSessionId: 'cc-session-here',
}),
);
- useElectronStore.setState({ gatewayDeviceInfo: undefined });
+ resolveDeviceId.mockRestore();
});
it.each(['claude-code', 'codex'] as const)(
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index f147a9f2cdf..0c48f11c01d 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -1235,7 +1235,7 @@ export class ConversationLifecycleActionImpl {
: undefined,
topicId: willCreateNewTopic ? undefined : operationContext.topicId,
});
- const currentDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
+ const currentDeviceId = await getElectronStoreState().resolveGatewayDeviceId();
// Resolve the cwd for every run that lands on a MACHINE β€” a hetero CLI
// (in-process `hetero` runtime) and a NATIVE agent alike, as long as the
// effective target routes to a device. The server can only honour a cwd the
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index d6e583af56a..4250bf8f404 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -880,11 +880,9 @@ export const executeHeterogeneousAgent = async (
const getPersistedWorkingDirectoryConfig = (
topicMetadata: ChatTopicMetadata | undefined,
): WorkingDirConfig | undefined =>
- // Prefer the topic's CURRENT config: while the CLI runs, GitStatus may have
- // persisted richer branch/PR/CI (`git.github`) onto it. Falling back to the
- // run-start captured config would drop that enrichment on the completion
- // write until a status component re-probes. Captured config is only the
- // fallback for a topic that carries none yet.
+ // Prefer the topic's CURRENT config: GitStatus may have persisted richer
+ // branch/PR/CI (`git.github`) onto it while the CLI ran, which the run-start
+ // captured config would drop. That one is only for a topic with none yet.
topicMetadata?.workingDirectoryConfig ??
workingDirectoryConfig ??
(workingDirectory === undefined ? undefined : { path: workingDirectory });
@@ -895,11 +893,16 @@ export const executeHeterogeneousAgent = async (
mainState.toolState.payloads.length > 0 ||
toolMsgIdByCallId.size > 0 ||
mainState.subagents.runs.size > 0;
+ // The CLI session and its cwd live on THIS machine: every cwd write pins it.
+ const getRunMachinePin = async () => {
+ const deviceId = await getElectronStoreState().resolveGatewayDeviceId();
+ return deviceId ? { boundDeviceId: deviceId } : {};
+ };
const clearStaleResumeMetadata = async () => {
if (!context.topicId || !updateTopicMetadata) return;
-
const topicMetadata = getTopicMetadataById(get(), context.topicId);
await updateTopicMetadata(context.topicId, {
+ ...(await getRunMachinePin()),
heteroSessionBindingKey: undefined,
heteroSessionBindingKeyByWorkingDirectory: removeHeteroSessionBindingKeyForWorkingDirectory(
topicMetadata,
@@ -930,11 +933,8 @@ export const executeHeterogeneousAgent = async (
.catch(() => {})
.then(async () => {
const topicMetadata = getTopicMetadataById(get(), topicId);
- // The session and its cwd now live on THIS machine, so the topic is
- // pinned here β€” its next turn and the device picker follow it.
- const runDeviceId = getElectronStoreState().gatewayDeviceInfo?.deviceId;
await updateTopicMetadata(topicId, {
- ...(runDeviceId ? { boundDeviceId: runDeviceId } : {}),
+ ...(await getRunMachinePin()),
heteroSessionBindingKey: activeSessionBindingKey,
heteroSessionBindingKeyByWorkingDirectory: setHeteroSessionBindingKeyForWorkingDirectory(
topicMetadata,
diff --git a/src/store/electron/actions/__tests__/gateway.test.ts b/src/store/electron/actions/__tests__/gateway.test.ts
new file mode 100644
index 00000000000..ec3b97341ab
--- /dev/null
+++ b/src/store/electron/actions/__tests__/gateway.test.ts
@@ -0,0 +1,52 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useElectronStore } from '@/store/electron';
+
+const service = vi.hoisted(() => ({ getDeviceInfo: vi.fn(), getStableDeviceId: vi.fn() }));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ isDesktop: true,
+}));
+
+vi.mock('@/services/electron/gatewayConnection', () => ({ gatewayConnectionService: service }));
+
+beforeEach(() => {
+ service.getDeviceInfo.mockReset();
+ service.getStableDeviceId.mockReset();
+ useElectronStore.setState({ gatewayDeviceInfo: undefined });
+});
+
+describe('resolveGatewayDeviceId', () => {
+ // Regression: a cwd write that ran before any picker mounted read an empty
+ // store and saved the path with no machine.
+ it('asks the desktop for its stable id when the store has not loaded one', async () => {
+ service.getStableDeviceId.mockResolvedValue('stable-1');
+
+ await expect(useElectronStore.getState().resolveGatewayDeviceId()).resolves.toBe('stable-1');
+ });
+
+ // Regression: before the gateway connects the store holds the install's
+ // fallback UUID, which no longer names this machine once the identity is derived.
+ it('ignores a cached fallback id and never takes the network-backed device info path', async () => {
+ useElectronStore.setState({
+ gatewayDeviceInfo: { deviceId: 'fallback-uuid', hostname: 'mac', platform: 'darwin' },
+ });
+ service.getStableDeviceId.mockResolvedValue('stable-1');
+
+ await expect(useElectronStore.getState().resolveGatewayDeviceId()).resolves.toBe('stable-1');
+ expect(service.getDeviceInfo).not.toHaveBeenCalled();
+ // The renderer's "this device" must agree with the pin just written, or the
+ // next turn reads this desktop as a remote machine.
+ expect(useElectronStore.getState().gatewayDeviceInfo?.deviceId).toBe('stable-1');
+ });
+
+ it('returns nothing while signed out or when the desktop cannot answer', async () => {
+ service.getStableDeviceId.mockResolvedValueOnce(undefined);
+ await expect(useElectronStore.getState().resolveGatewayDeviceId()).resolves.toBeUndefined();
+
+ service.getStableDeviceId.mockRejectedValueOnce(new Error('ipc down'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ await expect(useElectronStore.getState().resolveGatewayDeviceId()).resolves.toBeUndefined();
+ });
+});
diff --git a/src/store/electron/actions/gateway.ts b/src/store/electron/actions/gateway.ts
index 654cd508917..ab2878d610d 100644
--- a/src/store/electron/actions/gateway.ts
+++ b/src/store/electron/actions/gateway.ts
@@ -20,11 +20,12 @@ export interface GatewayDeviceInfo {
}
export class ElectronGatewayActionImpl {
+ readonly #get: () => ElectronStore;
readonly #set: Setter;
- constructor(set: Setter, _get: () => ElectronStore, _api?: unknown) {
- void _get;
+ constructor(set: Setter, get: () => ElectronStore, _api?: unknown) {
void _api;
+ this.#get = get;
this.#set = set;
}
@@ -54,6 +55,32 @@ export class ElectronGatewayActionImpl {
this.#set({ gatewayConnectionStatus: status }, false, 'setGatewayConnectionStatus');
};
+ /**
+ * This desktop's stable device id, for writes that pin a topic's cwd to it.
+ *
+ * Asked over IPC every time rather than read from `gatewayDeviceInfo`: before
+ * the gateway connects, that holds the install's fallback UUID, which stops
+ * naming this machine once the user-scoped identity is derived. The IPC
+ * derives that identity locally β€” no network on the send path β€” and returns
+ * nothing while signed out, so no pin is written rather than a stale one.
+ * A differing cached id is corrected too, so "this device" comparisons agree
+ * with the pins written here.
+ */
+ resolveGatewayDeviceId = async (): Promise<string | undefined> => {
+ if (!isDesktop) return;
+ try {
+ const deviceId = (await gatewayConnectionService.getStableDeviceId()) ?? undefined;
+ const cached = this.#get().gatewayDeviceInfo;
+ if (deviceId && cached && cached.deviceId !== deviceId) {
+ this.#set({ gatewayDeviceInfo: { ...cached, deviceId } }, false, 'setGatewayDeviceInfo');
+ }
+ return deviceId;
+ } catch (error) {
+ console.error('Gateway device id lookup failed:', error);
+ return;
+ }
+ };
+
useFetchGatewayDeviceInfo = (): SWRResponse<GatewayDeviceInfo> => {
return useSWR<GatewayDeviceInfo>(
// Desktop-only IPC: on web there is no electronAPI, so never fetch off-desktop.