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(device): persist working-dir edits on public workspace devices (#20940)

Lobehub Coder9efcb36912be
diff --git a/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts b/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts
index a263bfad452..98c4c5f15e6 100644
--- a/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/deviceWorkspaceGuard.test.ts
@@ -3,7 +3,11 @@ import { describe, expect, it, vi } from 'vitest';
import type { DeviceModel } from '@/database/models/device';
-import { assertWorkspaceDeviceVisible, assertWorkspaceRootApproved } from '../deviceWorkspaceGuard';
+import {
+ assertWorkspaceDeviceEditable,
+ assertWorkspaceDeviceVisible,
+ assertWorkspaceRootApproved,
+} from '../deviceWorkspaceGuard';
const mockModel = (
row: {
@@ -111,3 +115,16 @@ describe('assertWorkspaceDeviceVisible', () => {
).rejects.toMatchObject({ code: 'NOT_FOUND' });
});
});
+
+describe('assertWorkspaceDeviceEditable', () => {
+ it.each([
+ ['owner', 'owner'],
+ ['member', 'enroller'],
+ ] as const)('lets the %s edit the registration', (role, userId) => {
+ expect(() => assertWorkspaceDeviceEditable(role, userId, 'enroller')).not.toThrow();
+ });
+
+ it('rejects any other member', () => {
+ expect(() => assertWorkspaceDeviceEditable('member', 'member', 'enroller')).toThrow(TRPCError);
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/deviceWorkspaceWorkingDirs.test.ts b/apps/server/src/routers/lambda/__tests__/deviceWorkspaceWorkingDirs.test.ts
new file mode 100644
index 00000000000..dbaa09a0a31
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/deviceWorkspaceWorkingDirs.test.ts
@@ -0,0 +1,107 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { router } from '@/libs/trpc/lambda';
+
+import { workspaceDeviceWorkingDirProcedures } from '../deviceWorkspaceWorkingDirs';
+
+const mocks = vi.hoisted(() => ({
+ findWorkspaceDeviceById: vi.fn(),
+ stored: [] as { path: string; workspace?: unknown }[],
+}));
+
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ return {
+ requireWorkspaceRole: () => mod.trpc.middleware(async (opts: any) => opts.next()),
+ wsProcedure: mod.trpc.procedure,
+ };
+});
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: async (opts: any) => opts.next({ ctx: { ...opts.ctx, serverDB: {} } }),
+}));
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: class {
+ findWorkspaceDeviceById = mocks.findWorkspaceDeviceById;
+ mutateWorkspaceDeviceWorkingDirs = async (_id: string, mutate: (d: any[]) => any[]) => {
+ mocks.stored = mutate(mocks.stored);
+ return mocks.stored;
+ };
+ },
+}));
+
+type Role = 'member' | 'owner' | 'viewer';
+
+const caller = (userId: string, workspaceRole: Role) =>
+ router(workspaceDeviceWorkingDirProcedures).createCaller({
+ userId,
+ workspaceId: 'workspace',
+ workspaceRole,
+ } as never);
+
+const withDevice = (visibility: 'private' | 'public') =>
+ mocks.findWorkspaceDeviceById.mockResolvedValue({
+ deviceId: 'device',
+ userId: 'enroller',
+ visibility,
+ });
+
+describe('workspace device working-dir entries', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.stored = [{ path: '/a', workspace: { cached: true } }, { path: '/b' }];
+ });
+
+ it('lets a member add a dir to the front of a public device list, keeping cached scans', async () => {
+ withDevice('public');
+
+ await caller('member', 'member').addWorkspaceDeviceWorkingDir({
+ deviceId: 'device',
+ entry: { path: '/a' },
+ });
+ await caller('member', 'member').addWorkspaceDeviceWorkingDir({
+ deviceId: 'device',
+ entry: { path: '/c' },
+ });
+
+ expect(mocks.stored).toEqual([
+ { path: '/c' },
+ { path: '/a', workspace: { cached: true } },
+ { path: '/b' },
+ ]);
+ });
+
+ it('lets a member remove one dir from a public device list', async () => {
+ withDevice('public');
+
+ await caller('member', 'member').removeWorkspaceDeviceWorkingDir({
+ deviceId: 'device',
+ path: '/a',
+ });
+
+ expect(mocks.stored).toEqual([{ path: '/b' }]);
+ });
+
+ it.each([
+ ['a member on a private device they did not enroll', 'private', 'member'],
+ ['a viewer on a public device', 'public', 'viewer'],
+ ] as const)('rejects %s', async (_case, visibility, role) => {
+ withDevice(visibility);
+
+ await expect(
+ caller(role, role).removeWorkspaceDeviceWorkingDir({ deviceId: 'device', path: '/a' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(mocks.stored).toHaveLength(2);
+ });
+
+ it('returns NOT_FOUND for a device outside the workspace', async () => {
+ mocks.findWorkspaceDeviceById.mockResolvedValue(undefined);
+
+ await expect(
+ caller('owner', 'owner').addWorkspaceDeviceWorkingDir({
+ deviceId: 'device',
+ entry: { path: '/c' },
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+});
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 84e63e0a562..7aac7976a2e 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -40,10 +40,14 @@ import { deviceTunnels, TUNNEL_MAX_TTL_SECONDS } from '@/server/services/deviceG
import { loadDeviceBoundAgents } from './deviceBoundAgents';
import { preserveWorkspaceCache } from './deviceWorkingDirs';
import {
+ assertWorkspaceDeviceEditable,
assertWorkspaceDeviceVisible,
assertWorkspaceRootApproved,
+ canEditWorkspaceDevice,
+ canOperateWorkspaceDevice,
registerDeviceSkillRoots,
} from './deviceWorkspaceGuard';
+import { workspaceDeviceWorkingDirProcedures } from './deviceWorkspaceWorkingDirs';
// Derive the zod enum from the canonical config so new platforms are
// automatically covered without touching this file.
@@ -145,25 +149,6 @@ const buildTunnelOpenUrl = async (
return `${url}?${TUNNEL_TOKEN_PARAM}=${encodeURIComponent(token)}`;
};
-const canEditWorkspaceDevice = (
- role: WorkspaceRole | undefined,
- actorUserId: string,
- enrollerUserId: string,
-): boolean => role === 'owner' || enrollerUserId === actorUserId;
-
-/**
- * Using a workspace device (as opposed to editing its registration) is open to
- * every member once it is public; read-only viewers never operate a machine.
- * See {@link assertDeviceOperable}.
- */
-const canOperateWorkspaceDevice = (
- role: WorkspaceRole | undefined,
- actorUserId: string,
- row: { userId: string; visibility: 'private' | 'public' },
-): boolean =>
- (row.visibility === 'public' && !!role && role !== 'viewer') ||
- canEditWorkspaceDevice(role, actorUserId, row.userId);
-
/**
* Fixed workspace agents promise every member the same execution device. Keep
* that promise intact until an editor changes the agent back to member choice
@@ -299,6 +284,7 @@ const resolveRunUserIds = async (
const RUNNING_SUMMARY_LIMIT = 500;
export const deviceRouter = router({
+ ...workspaceDeviceWorkingDirProcedures,
/**
* Probe whether a specific agent platform (openclaw / hermes) is available
* on the given device. Dispatches a `checkPlatformCapability` tool call to
@@ -2098,10 +2084,8 @@ export const deviceRouter = router({
}),
/**
- * Rename / set working dirs of a WORKSPACE device. Scoped by `workspace_id`
- * and gated by {@link canEditWorkspaceDevice}: owners may edit any device in
- * the pool; members may edit only devices they enrolled themselves. Mirrors
- * {@link deviceRouter.updateDevice} but for the workspace pool.
+ * Rename / replace the working dirs of a WORKSPACE device (enroller or owner only).
+ * Members edit one recent dir via `workspaceDeviceWorkingDirProcedures`.
*/
updateWorkspaceDevice: wsWritableProcedure
.use(serverDatabase)
@@ -2121,12 +2105,7 @@ export const deviceRouter = router({
throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });
}
const role = (ctx as { workspaceRole?: WorkspaceRole }).workspaceRole;
- if (!canEditWorkspaceDevice(role, ctx.userId, row.userId)) {
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: 'Only the enrolling member or a workspace owner can modify this device.',
- });
- }
+ assertWorkspaceDeviceEditable(role, ctx.userId, row.userId);
const nextWorkingDirs = workingDirs
? preserveWorkspaceCache(workingDirs, row.workingDirs ?? [])
: undefined;
diff --git a/apps/server/src/routers/lambda/deviceWorkingDirs.ts b/apps/server/src/routers/lambda/deviceWorkingDirs.ts
index 58ac633fd82..2bf5edf85e2 100644
--- a/apps/server/src/routers/lambda/deviceWorkingDirs.ts
+++ b/apps/server/src/routers/lambda/deviceWorkingDirs.ts
@@ -29,3 +29,21 @@ export const preserveWorkspaceCache = (
: entry;
});
};
+
+/** Max recent working directories kept per device (matches the update input cap). */
+export const WORKING_DIRS_MAX = 20;
+
+/**
+ * Move `entry` to the front of `current` (most-recent-first), replacing any entry
+ * with the same path while keeping its server-owned workspace cache, and cap the
+ * list. Mirrors the client's optimistic `nextWorkingDirs`.
+ */
+export const upsertWorkingDir = (
+ entry: WorkingDirEntry,
+ current: readonly WorkingDirEntry[],
+): WorkingDirEntry[] => {
+ const path = entry.path.trim();
+ if (!path) return [...current];
+ const [next] = preserveWorkspaceCache([{ ...entry, path }], current);
+ return [next, ...current.filter((dir) => dir.path !== path)].slice(0, WORKING_DIRS_MAX);
+};
diff --git a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
index 29359fb6334..e748676b84d 100644
--- a/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
+++ b/apps/server/src/routers/lambda/deviceWorkspaceGuard.ts
@@ -1,8 +1,40 @@
import { TRPCError } from '@trpc/server';
+import type { WorkspaceRole } from '@/business/server/trpc-middlewares/workspaceAuth';
import type { DeviceModel } from '@/database/models/device';
import { isPathWithinRoot } from '@/server/services/deviceGateway';
+export const canEditWorkspaceDevice = (
+ role: WorkspaceRole | undefined,
+ actorUserId: string,
+ enrollerUserId: string,
+): boolean => role === 'owner' || enrollerUserId === actorUserId;
+
+/**
+ * Using a workspace device (as opposed to editing its registration) is open to
+ * every member once it is public; read-only viewers never operate a machine.
+ */
+export const canOperateWorkspaceDevice = (
+ role: WorkspaceRole | undefined,
+ actorUserId: string,
+ row: { userId: string; visibility: 'private' | 'public' },
+): boolean =>
+ (row.visibility === 'public' && !!role && role !== 'viewer') ||
+ canEditWorkspaceDevice(role, actorUserId, row.userId);
+
+/** Throw unless the caller may edit this workspace device's registration. */
+export const assertWorkspaceDeviceEditable = (
+ role: WorkspaceRole | undefined,
+ actorUserId: string,
+ enrollerUserId: string,
+): void => {
+ if (canEditWorkspaceDevice(role, actorUserId, enrollerUserId)) return;
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the enrolling member or a workspace owner can modify this device.',
+ });
+};
+
/**
* In-memory cache of device-scoped skill preview roots, populated by
* `listProjectSkills` and consumed by `assertWorkspaceRootApproved` to
diff --git a/apps/server/src/routers/lambda/deviceWorkspaceWorkingDirs.ts b/apps/server/src/routers/lambda/deviceWorkspaceWorkingDirs.ts
new file mode 100644
index 00000000000..8c82e404bc2
--- /dev/null
+++ b/apps/server/src/routers/lambda/deviceWorkspaceWorkingDirs.ts
@@ -0,0 +1,61 @@
+import { workingDirConfigSchema } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import {
+ requireWorkspaceRole,
+ type WorkspaceRole,
+ wsProcedure,
+} from '@/business/server/trpc-middlewares/workspaceAuth';
+import { DeviceModel } from '@/database/models/device';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+
+import { upsertWorkingDir } from './deviceWorkingDirs';
+import { canOperateWorkspaceDevice } from './deviceWorkspaceGuard';
+
+/**
+ * Add or remove ONE recent working directory on a workspace device. Picking,
+ * adding and removing a folder is part of using a device, so any member who may
+ * operate it (every non-viewer on a public device) may do this. Each call edits
+ * the stored list under a row lock instead of replacing it with the caller's
+ * snapshot, so concurrent members cannot drop each other's entries.
+ */
+const workingDirProcedure = wsProcedure
+ .use(requireWorkspaceRole('member'))
+ .use(serverDatabase)
+ .use(async (opts) => {
+ const { ctx } = opts;
+ const { deviceId } = z.object({ deviceId: z.string() }).parse(await opts.getRawInput());
+ const model = new DeviceModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
+ const row = await model.findWorkspaceDeviceById(deviceId);
+ if (!row) throw new TRPCError({ code: 'NOT_FOUND', message: 'Workspace device not found.' });
+
+ const role = (ctx as { workspaceRole?: WorkspaceRole }).workspaceRole;
+ if (!canOperateWorkspaceDevice(role, ctx.userId, row)) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'You cannot change the working directories of this device.',
+ });
+ }
+ return opts.next({ ctx: { workspaceDeviceModel: model } });
+ });
+
+export const workspaceDeviceWorkingDirProcedures = {
+ addWorkspaceDeviceWorkingDir: workingDirProcedure
+ .input(z.object({ deviceId: z.string(), entry: workingDirConfigSchema }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.workspaceDeviceModel.mutateWorkspaceDeviceWorkingDirs(input.deviceId, (dirs) =>
+ upsertWorkingDir(input.entry, dirs),
+ );
+ return { success: true };
+ }),
+
+ removeWorkspaceDeviceWorkingDir: workingDirProcedure
+ .input(z.object({ deviceId: z.string(), path: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.workspaceDeviceModel.mutateWorkspaceDeviceWorkingDirs(input.deviceId, (dirs) =>
+ dirs.filter((dir) => dir.path !== input.path),
+ );
+ return { success: true };
+ }),
+};
diff --git a/packages/database/src/models/__tests__/device.test.ts b/packages/database/src/models/__tests__/device.test.ts
index c3cd8c147d4..7b89b3ee996 100644
--- a/packages/database/src/models/__tests__/device.test.ts
+++ b/packages/database/src/models/__tests__/device.test.ts
@@ -681,4 +681,69 @@ describe('DeviceModel', () => {
expect(row).toBeUndefined();
});
});
+
+ describe('mutateWorkspaceDeviceWorkingDirs', () => {
+ const dirsWsId = 'device-model-ws-working-dirs';
+
+ const enroll = async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({ id: dirsWsId, name: 'WS', primaryOwnerId: userId, slug: dirsWsId });
+ const enroller = new DeviceModel(serverDB, otherUserId, dirsWsId);
+ await enroller.registerWorkspaceDevice({
+ deviceId: 'ws-dirs-dev',
+ identitySource: 'machine-id',
+ workspaceId: dirsWsId,
+ });
+ await enroller.updateWorkspaceDevice('ws-dirs-dev', { workingDirs: [{ path: '/a' }] });
+ };
+
+ const storedDirs = async () =>
+ (
+ await serverDB.query.devices.findFirst({
+ where: and(eq(devices.workspaceId, dirsWsId), eq(devices.deviceId, 'ws-dirs-dev')),
+ })
+ )?.workingDirs;
+
+ afterEach(async () => {
+ await serverDB.delete(devices).where(eq(devices.workspaceId, dirsWsId));
+ await serverDB.delete(workspaces).where(eq(workspaces.id, dirsWsId));
+ });
+
+ it("edits another member's workspace device row in place", async () => {
+ await enroll();
+ const member = new DeviceModel(serverDB, userId, dirsWsId);
+
+ const next = await member.mutateWorkspaceDeviceWorkingDirs('ws-dirs-dev', (dirs) => [
+ { path: '/b' },
+ ...dirs,
+ ]);
+
+ expect(next).toEqual([{ path: '/b' }, { path: '/a' }]);
+ expect(await storedDirs()).toEqual([{ path: '/b' }, { path: '/a' }]);
+ });
+
+ it('keeps both entries when two members add concurrently', async () => {
+ await enroll();
+ const add = (path: string) =>
+ new DeviceModel(serverDB, userId, dirsWsId).mutateWorkspaceDeviceWorkingDirs(
+ 'ws-dirs-dev',
+ (dirs) => [{ path }, ...dirs],
+ );
+
+ await Promise.all([add('/x'), add('/y')]);
+
+ expect((await storedDirs())?.map((d) => d.path).sort()).toEqual(['/a', '/x', '/y']);
+ });
+
+ it('returns undefined for a device outside the current workspace', async () => {
+ await enroll();
+ const outsider = new DeviceModel(serverDB, userId, 'device-model-other-ws');
+
+ expect(
+ await outsider.mutateWorkspaceDeviceWorkingDirs('ws-dirs-dev', () => []),
+ ).toBeUndefined();
+ expect(await storedDirs()).toEqual([{ path: '/a' }]);
+ });
+ });
});
diff --git a/packages/database/src/models/device.ts b/packages/database/src/models/device.ts
index 6dc43545be6..2d7ed85ecfb 100644
--- a/packages/database/src/models/device.ts
+++ b/packages/database/src/models/device.ts
@@ -358,6 +358,33 @@ export class DeviceModel {
.where(and(eq(devices.workspaceId, this.workspaceId), eq(devices.deviceId, deviceId)));
};
+ /**
+ * Read-modify-write a WORKSPACE device's `workingDirs` under a row lock, so
+ * concurrent members adding or removing one directory each cannot overwrite
+ * the other's change with a stale client snapshot. Returns the stored list,
+ * or `undefined` when the device is not in the current workspace.
+ */
+ mutateWorkspaceDeviceWorkingDirs = async (
+ deviceId: string,
+ mutate: (current: WorkingDirEntry[]) => WorkingDirEntry[],
+ ): Promise<WorkingDirEntry[] | undefined> => {
+ if (!this.workspaceId) return undefined;
+ const where = and(eq(devices.workspaceId, this.workspaceId), eq(devices.deviceId, deviceId));
+
+ return this.db.transaction(async (tx) => {
+ const [row] = await tx
+ .select({ workingDirs: devices.workingDirs })
+ .from(devices)
+ .where(where)
+ .for('update');
+ if (!row) return undefined;
+
+ const next = mutate(row.workingDirs ?? []);
+ await tx.update(devices).set({ updatedAt: new Date(), workingDirs: next }).where(where);
+ return next;
+ });
+ };
+
/**
* Remove a WORKSPACE device, scoped by `workspace_id`. Permission
* (workspace owner, or the enroller acting on their own device) is enforced
diff --git a/src/services/device.ts b/src/services/device.ts
index ce9d9c195be..c37f6bd8b87 100644
--- a/src/services/device.ts
+++ b/src/services/device.ts
@@ -25,6 +25,25 @@ class DeviceService {
return lambdaClient.device.updateDevice.mutate(input);
}
+ /** Update user-editable fields of a workspace-enrolled device (workspace-scoped write). */
+ updateWorkspaceDevice(input: Parameters<DeviceClient['updateWorkspaceDevice']['mutate']>[0]) {
+ return lambdaClient.device.updateWorkspaceDevice.mutate(input);
+ }
+
+ /** Add (or move to the front) one recent working dir on a workspace device. */
+ addWorkspaceDeviceWorkingDir(
+ input: Parameters<DeviceClient['addWorkspaceDeviceWorkingDir']['mutate']>[0],
+ ) {
+ return lambdaClient.device.addWorkspaceDeviceWorkingDir.mutate(input);
+ }
+
+ /** Remove one recent working dir from a workspace device. */
+ removeWorkspaceDeviceWorkingDir(
+ input: Parameters<DeviceClient['removeWorkspaceDeviceWorkingDir']['mutate']>[0],
+ ) {
+ return lambdaClient.device.removeWorkspaceDeviceWorkingDir.mutate(input);
+ }
+
/**
* Check whether a path exists on a device and is a directory (via the device's
* `statPath` RPC). Returns `null` when the device is unreachable β€” callers
diff --git a/src/store/device/action.test.ts b/src/store/device/action.test.ts
index 11e3f9e2687..5b37f0c58b4 100644
--- a/src/store/device/action.test.ts
+++ b/src/store/device/action.test.ts
@@ -37,6 +37,11 @@ describe('DeviceAction', () => {
vi.clearAllMocks();
vi.mocked(mutate).mockResolvedValue(undefined);
vi.spyOn(deviceService, 'updateDevice').mockResolvedValue({ success: true });
+ vi.spyOn(deviceService, 'updateWorkspaceDevice').mockResolvedValue({ success: true });
+ vi.spyOn(deviceService, 'addWorkspaceDeviceWorkingDir').mockResolvedValue({ success: true });
+ vi.spyOn(deviceService, 'removeWorkspaceDeviceWorkingDir').mockResolvedValue({
+ success: true,
+ });
useDeviceStore.setState({ devices: [], isDevicesInit: true });
});
@@ -111,4 +116,75 @@ describe('DeviceAction', () => {
expect(mutate).toHaveBeenCalledWith(deviceKeys.listDevices());
});
});
+
+ // Workspace devices are stored under `workspace_id`; the personal mutation is
+ // userId-scoped and would silently drop the write, so removed dirs came back.
+ describe('workspace devices', () => {
+ const workspaceDevice = () =>
+ buildDevice({
+ deviceId: 'ws-dev',
+ scope: 'workspace',
+ workingDirs: [{ path: '/a' }, { path: '/b' }],
+ });
+
+ // Members share the list, so only the touched entry is sent β€” never this
+ // client's whole (possibly stale) snapshot.
+ it('removes one recent dir through the workspace entry mutation', async () => {
+ useDeviceStore.setState({ devices: [workspaceDevice()] });
+
+ await useDeviceStore.getState().removeDeviceWorkingDir('ws-dev', '/a');
+
+ expect(deviceService.removeWorkspaceDeviceWorkingDir).toHaveBeenCalledWith({
+ deviceId: 'ws-dev',
+ path: '/a',
+ });
+ expect(deviceService.updateWorkspaceDevice).not.toHaveBeenCalled();
+ expect(deviceService.updateDevice).not.toHaveBeenCalled();
+ expect(deviceSelectors.getDeviceWorkingDirs('ws-dev')(useDeviceStore.getState())).toEqual([
+ { path: '/b' },
+ ]);
+ });
+
+ it('adds one picked dir through the workspace entry mutation', async () => {
+ useDeviceStore.setState({ devices: [workspaceDevice()] });
+
+ await useDeviceStore
+ .getState()
+ .updateDeviceCwd('ws-dev', { path: ' /c ' }, { setDefault: false });
+
+ expect(deviceService.addWorkspaceDeviceWorkingDir).toHaveBeenCalledWith({
+ deviceId: 'ws-dev',
+ entry: { path: '/c' },
+ });
+ expect(deviceService.updateWorkspaceDevice).not.toHaveBeenCalled();
+ expect(deviceService.updateDevice).not.toHaveBeenCalled();
+ });
+
+ it('sets the device default separately from the entry add', async () => {
+ useDeviceStore.setState({ devices: [workspaceDevice()] });
+
+ await useDeviceStore.getState().updateDeviceCwd('ws-dev', { path: '/c' });
+
+ expect(deviceService.addWorkspaceDeviceWorkingDir).toHaveBeenCalledWith({
+ deviceId: 'ws-dev',
+ entry: { path: '/c' },
+ });
+ expect(deviceService.updateWorkspaceDevice).toHaveBeenCalledWith({
+ defaultCwd: '/c',
+ deviceId: 'ws-dev',
+ });
+ });
+
+ it('keeps personal devices on the personal mutation', async () => {
+ useDeviceStore.setState({ devices: [buildDevice({ workingDirs: [{ path: '/a' }] })] });
+
+ await useDeviceStore.getState().removeDeviceWorkingDir('dev-1', '/a');
+
+ expect(deviceService.updateDevice).toHaveBeenCalledWith({
+ deviceId: 'dev-1',
+ workingDirs: [],
+ });
+ expect(deviceService.updateWorkspaceDevice).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/src/store/device/action.ts b/src/store/device/action.ts
index 35fdd3120a7..bf838669954 100644
--- a/src/store/device/action.ts
+++ b/src/store/device/action.ts
@@ -19,6 +19,18 @@ type Setter = StoreSetter<DeviceStore>;
const revalidateDeviceLists = () =>
Promise.all([mutate(deviceKeys.listDevices()), refreshDeviceList()]);
+type UpdateDeviceInput = Parameters<typeof deviceService.updateDevice>[0];
+
+/**
+ * Persist user-editable fields, routed by the device's own scope. Workspace
+ * devices live under `workspace_id`, so the userId-scoped personal mutation
+ * would match no row and the write would be silently dropped.
+ */
+const persistDevice = (device: DeviceListItem | undefined, input: UpdateDeviceInput) =>
+ device?.scope === 'workspace'
+ ? deviceService.updateWorkspaceDevice(input)
+ : deviceService.updateDevice(input);
+
export const deviceSlice = (set: Setter, get: () => DeviceStore, _api?: unknown) =>
new DeviceActionImpl(set, get, _api);
@@ -65,11 +77,22 @@ export class DeviceActionImpl {
);
try {
- await deviceService.updateDevice({
- deviceId,
- ...(setDefault ? { defaultCwd: trimmed } : {}),
- workingDirs: updatedDirs,
- });
+ if (device?.scope === 'workspace') {
+ // Members share this list: add the one entry server-side instead of
+ // replacing the list with this client's possibly stale snapshot.
+ await deviceService.addWorkspaceDeviceWorkingDir({
+ deviceId,
+ entry: { ...entry, path: trimmed },
+ });
+ if (setDefault)
+ await deviceService.updateWorkspaceDevice({ defaultCwd: trimmed, deviceId });
+ } else {
+ await deviceService.updateDevice({
+ deviceId,
+ ...(setDefault ? { defaultCwd: trimmed } : {}),
+ workingDirs: updatedDirs,
+ });
+ }
} finally {
// Re-fetch the truth (self-corrects a failed optimistic write).
await revalidateDeviceLists();
@@ -94,7 +117,7 @@ export class DeviceActionImpl {
);
try {
- await deviceService.updateDevice({ defaultCwd: null, deviceId });
+ await persistDevice(device, { defaultCwd: null, deviceId });
} catch (error) {
// Preserve the prior default if the optimistic write cannot be persisted.
this.#set(
@@ -143,7 +166,7 @@ export class DeviceActionImpl {
);
try {
- await deviceService.updateDevice({ deviceId, workingDirs: merged });
+ await persistDevice(device, { deviceId, workingDirs: merged });
} finally {
await revalidateDeviceLists();
}
@@ -166,7 +189,9 @@ export class DeviceActionImpl {
);
try {
- await deviceService.updateDevice({ deviceId, workingDirs: updated });
+ await (device.scope === 'workspace'
+ ? deviceService.removeWorkspaceDeviceWorkingDir({ deviceId, path })
+ : deviceService.updateDevice({ deviceId, workingDirs: updated }));
} finally {
await revalidateDeviceLists();
}