Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6323 fix(views): stop blaming the daemon when the backend is the stale half (#7126)
Bohan Jiang5f4ba41d130d
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 676ed8da3f..cf73a52b34 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -841,6 +841,33 @@ describe("dashboard + runtime usage schema drift", () => {});});+// A server that never heard of worktree mode also never sends this flag, and+// it does not reject the mode either — it drops execution_mode and answers 201,+// leaving the task to run in the user's working copy (#7113). So the absent+// case has to parse as false, not as "unknown, probably fine".+describe("AppConfigSchema local_worktree_supported drift", () => {+ it("defaults to false when the server predates the signal", () => {+ const parsed = AppConfigSchema.parse({ cdn_domain: "cdn.example.com" });+ expect(parsed.local_worktree_supported).toBe(false);+ });++ it("coerces a malformed value to false rather than trusting it", () => {+ const parsed = AppConfigSchema.parse({+ cdn_domain: "cdn.example.com",+ local_worktree_supported: "yes",+ });+ expect(parsed.local_worktree_supported).toBe(false);+ });++ it("carries a genuine true through", () => {+ const parsed = AppConfigSchema.parse({+ cdn_domain: "cdn.example.com",+ local_worktree_supported: true,+ });+ expect(parsed.local_worktree_supported).toBe(true);+ });+});+describe("AppConfigSchema cdn_signed drift", () => {it("defaults cdn_signed to false when the server omits it (pre-MUL-3254 servers)", () => {const parsed = AppConfigSchema.parse({ cdn_domain: "cdn.example.com" });diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 43f980f0be..7994ada9e1 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -662,6 +662,14 @@ export interface AppConfigResponse {* Settings → Integrations "Git providers" section. */vcs_integration_available?: boolean;feature_flags?: Record<string, boolean>;+ /** Whether this server understands local_directory `execution_mode` and+ * gates worktree mode at save time. Absent on every server that predates this+ * capability signal, which includes the ones that silently DROPPED an unknown+ * `execution_mode` and answered 201 — the resource then ran in place while+ * the user was promised isolation (#7113). Servers between that fix and this+ * signal do validate but cannot say so, and are treated as unable: the client+ * has no way to tell them apart, and only one of the two answers is safe. */+ local_worktree_supported?: boolean;server_version?: string;}@@ -856,6 +864,7 @@ export const AppConfigSchema = z.object({workspace_creation_disabled: BooleanWithDefaultSchema(false).optional(),vcs_integration_available: BooleanWithDefaultSchema(false).optional(),feature_flags: FeatureFlagsSchema,+ local_worktree_supported: BooleanWithDefaultSchema(false),server_version: OptionalStringSchema,}).loose();@@ -868,6 +877,9 @@ export const EMPTY_APP_CONFIG: AppConfigResponse = {daemon_app_url: "",workspace_creation_disabled: false,vcs_integration_available: false,+ // Fail closed: an unreadable config must not look like a server that+ // validates execution_mode.+ local_worktree_supported: false,feature_flags: {},};diff --git a/packages/core/config/index.ts b/packages/core/config/index.tsindex 883eb8e802..3b6f8b0081 100644--- a/packages/core/config/index.ts+++ b/packages/core/config/index.ts@@ -25,6 +25,13 @@ interface ConfigState {// self-hosted operators can confirm what's deployed. Empty for dev builds// or servers older than this feature.serverVersion: string;+ // Whether the connected server validates local_directory execution_mode.+ // Defaults to false, and stays false for any server that does not declare it:+ // the dangerous ones accept worktree mode, drop the field, and run the task+ // in the user's working copy anyway (#7113). Servers that validate but+ // predate this signal are caught by the same net — indistinguishable from+ // here, and only one of the two answers is safe to guess.+ localWorktreeSupported: boolean;setCdnConfig: (config: { cdnDomain: string; cdnSigned?: boolean }) => void;setAuthConfig: (config: {allowSignup: boolean;@@ -38,6 +45,7 @@ interface ConfigState {}) => void;setFeatureFlags: (flags?: Record<string, boolean>) => void;setServerVersion: (version?: string) => void;+ setLocalWorktreeSupported: (supported?: boolean) => void;}export const configStore = createStore<ConfigState>((set) => ({@@ -51,6 +59,7 @@ export const configStore = createStore<ConfigState>((set) => ({vcsIntegrationAvailable: false,featureFlags: {},serverVersion: "",+ localWorktreeSupported: false,setCdnConfig: ({ cdnDomain, cdnSigned = false }) => set({ cdnDomain, cdnSigned }),setAuthConfig: ({allowSignup,@@ -62,6 +71,8 @@ export const configStore = createStore<ConfigState>((set) => ({set({ daemonServerUrl, daemonAppUrl }),setFeatureFlags: (flags = {}) => set({ featureFlags: { ...flags } }),setServerVersion: (version = "") => set({ serverVersion: version }),+ setLocalWorktreeSupported: (supported = false) =>+ set({ localWorktreeSupported: supported === true }),}));export function useConfigStore(): ConfigState;diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsxindex 1e15e93317..f70efe3eca 100644--- a/packages/core/platform/auth-initializer.tsx+++ b/packages/core/platform/auth-initializer.tsx@@ -81,6 +81,11 @@ export function AuthInitializer({});configStore.getState().setFeatureFlags(cfg.feature_flags);configStore.getState().setServerVersion(cfg.server_version);+ // Absent on every server that predates the worktree save gate, which+ // is exactly when the client must not offer the mode (#7113).+ configStore+ .getState()+ .setLocalWorktreeSupported(cfg.local_worktree_supported === true);if (cfg.posthog_key) {initAnalytics({key: cfg.posthog_key,diff --git a/packages/core/runtimes/cli-version.test.ts b/packages/core/runtimes/cli-version.test.tsindex 855212e62a..4e77538ac4 100644--- a/packages/core/runtimes/cli-version.test.ts+++ b/packages/core/runtimes/cli-version.test.ts@@ -6,8 +6,7 @@ import {handoffSupported,MIN_CHAT_PROJECT_CONTEXT_CLI_VERSION,MIN_HANDOFF_CLI_VERSION,- runtimeSupportsLocalWorktree,- daemonSupportsLocalWorktree,+ runtimeAdvertisesLocalWorktree,} from "./cli-version";describe("checkQuickCreateCliVersion", () => {@@ -94,48 +93,58 @@ describe("chatProjectContextSupported", () => {});});-describe("runtimeSupportsLocalWorktree", () => {+describe("runtimeAdvertisesLocalWorktree", () => {+ const capable = { capabilities: ["skill-bundles-v1", "local-worktree-v1"] };+ const incapable = { cli_version: "9.9.9", capabilities: null };+ const row = (metadata: unknown, last_seen_at: string | null = "2026-08-13T00:00:00Z") => ({+ daemon_id: "d1",+ last_seen_at,+ metadata,+ });+it("reads the advertised capability", () => {- expect(- runtimeSupportsLocalWorktree({ capabilities: ["skill-bundles-v1", "local-worktree-v1"] }),- ).toBe(true);- expect(runtimeSupportsLocalWorktree({ capabilities: ["skill-bundles-v1"] })).toBe(false);+ expect(runtimeAdvertisesLocalWorktree([row(capable)], "d1")).toBe(true);+ expect(runtimeAdvertisesLocalWorktree([row({ capabilities: ["skill-bundles-v1"] })], "d1")).toBe(+ false,+ );});// The whole reason this replaced a version check: a dev-built daemon reports a// git-describe string that the version floor exempts, so a binary with no// worktree implementation passed and two tasks ran in the user's own- // directory (MUL-5707). The capability must ignore versions entirely.- it("ignores the version string in both directions", () => {- expect(runtimeSupportsLocalWorktree({ cli_version: "v0.4.21-24-gcd3c0bb89" })).toBe(false);- expect(runtimeSupportsLocalWorktree({ cli_version: "9.9.9" })).toBe(false);+ // directory (MUL-5707).+ it("ignores the daemon version string in both directions", () => {+ expect(runtimeAdvertisesLocalWorktree([row({ cli_version: "9.9.9" })], "d1")).toBe(false);expect(- runtimeSupportsLocalWorktree({ cli_version: "0.0.1", capabilities: ["local-worktree-v1"] }),+ runtimeAdvertisesLocalWorktree(+ [row({ cli_version: "0.0.1", capabilities: ["local-worktree-v1"] })],+ "d1",+ ),).toBe(true);});- it("fails closed on anything it cannot read", () => {- for (const metadata of [undefined, null, {}, "nope", 42, { capabilities: "local-worktree-v1" }]) {- expect(runtimeSupportsLocalWorktree(metadata)).toBe(false);+ // Everything unreadable is simply "has not advertised". This function no+ // longer tries to say WHY — an old daemon, a row written before the server+ // recorded capabilities, and a server too old to record them are+ // indistinguishable from here, and pretending otherwise is what blocked a+ // user on the newest release with an instruction that could not help (#7113).+ it("says nothing about the reason when no row advertises", () => {+ for (const metadata of [{}, { cli_version: "v0.4.28" }, undefined, null, "nope", 42]) {+ expect(runtimeAdvertisesLocalWorktree([row(metadata)], "d1")).toBe(false);}+ expect(runtimeAdvertisesLocalWorktree([row(incapable)], "d1")).toBe(false);+ expect(runtimeAdvertisesLocalWorktree([row({ capabilities: "local-worktree-v1" })], "d1")).toBe(+ false,+ );});-});--describe("daemonSupportsLocalWorktree", () => {- const capable = { capabilities: ["local-worktree-v1"] };- const incapable = { cli_version: "9.9.9" };// Deregistering only marks a runtime offline; its metadata survives and the- // list endpoint still returns it. An any-row match would therefore keep- // vouching for a machine that has since downgraded, so the UI would offer a- // mode the server refuses at claim time.+ // list endpoint still returns it. An any-row match would keep preselecting+ // parallel for a machine that has since downgraded.it("ignores a stale capable row once a newer row lacks the capability", () => {expect(- daemonSupportsLocalWorktree(- [- { daemon_id: "d1", last_seen_at: "2026-08-01T00:00:00Z", metadata: capable },- { daemon_id: "d1", last_seen_at: "2026-08-13T00:00:00Z", metadata: incapable },- ],+ runtimeAdvertisesLocalWorktree(+ [row(capable, "2026-08-01T00:00:00Z"), row(incapable, "2026-08-13T00:00:00Z")],"d1",),).toBe(false);@@ -143,41 +152,32 @@ describe("daemonSupportsLocalWorktree", () => {it("recognises an upgrade: newest row advertises it", () => {expect(- daemonSupportsLocalWorktree(- [- { daemon_id: "d1", last_seen_at: "2026-08-01T00:00:00Z", metadata: incapable },- { daemon_id: "d1", last_seen_at: "2026-08-13T00:00:00Z", metadata: capable },- ],+ runtimeAdvertisesLocalWorktree(+ [row(incapable, "2026-08-01T00:00:00Z"), row(capable, "2026-08-13T00:00:00Z")],"d1",),).toBe(true);});it("does not depend on array order", () => {- const rows = [- { daemon_id: "d1", last_seen_at: "2026-08-13T00:00:00Z", metadata: incapable },- { daemon_id: "d1", last_seen_at: "2026-08-01T00:00:00Z", metadata: capable },- ];- expect(daemonSupportsLocalWorktree(rows, "d1")).toBe(false);- expect(daemonSupportsLocalWorktree([...rows].reverse(), "d1")).toBe(false);+ const rows = [row(incapable, "2026-08-13T00:00:00Z"), row(capable, "2026-08-01T00:00:00Z")];+ expect(runtimeAdvertisesLocalWorktree(rows, "d1")).toBe(false);+ expect(runtimeAdvertisesLocalWorktree([...rows].reverse(), "d1")).toBe(false);});it("a row that never reported loses to one that did", () => {expect(- daemonSupportsLocalWorktree(- [- { daemon_id: "d1", last_seen_at: null, metadata: capable },- { daemon_id: "d1", last_seen_at: "2026-08-13T00:00:00Z", metadata: incapable },- ],+ runtimeAdvertisesLocalWorktree(+ [row(capable, null), row(incapable, "2026-08-13T00:00:00Z")],"d1",),).toBe(false);});- it("ignores other daemons, and fails closed with no rows or no id", () => {+ it("ignores other daemons, and answers no with no rows or no id", () => {const other = [{ daemon_id: "d2", last_seen_at: "2026-08-13T00:00:00Z", metadata: capable }];- expect(daemonSupportsLocalWorktree(other, "d1")).toBe(false);- expect(daemonSupportsLocalWorktree([], "d1")).toBe(false);- expect(daemonSupportsLocalWorktree(other, null)).toBe(false);+ expect(runtimeAdvertisesLocalWorktree(other, "d1")).toBe(false);+ expect(runtimeAdvertisesLocalWorktree([], "d1")).toBe(false);+ expect(runtimeAdvertisesLocalWorktree(other, null)).toBe(false);});});diff --git a/packages/core/runtimes/cli-version.ts b/packages/core/runtimes/cli-version.tsindex 6e6b9d90c8..bdc46830ce 100644--- a/packages/core/runtimes/cli-version.ts+++ b/packages/core/runtimes/cli-version.ts@@ -145,30 +145,6 @@ function meetsMinCliVersion(detected: string | undefined | null, minimum: stringreturn !lessThan(parsed, parseSemver(minimum)!);}-/**- * Minimum daemon CLI version that implements worktree mode for- * `local_directory` resources (`execution_mode: "worktree"`).- *- * Server twin: `MinLocalWorktreeCLIVersion` in `server/pkg/agent/version.go`.- * Keep the two in lockstep — the server refuses to SAVE a worktree resource- * below this floor, and this constant only exists so the UI can say so before- * the user submits rather than surfacing a bare 422.- *- * HARD gate, unlike `handoffSupported`: a daemon below the floor does not know- * the field exists, so it would run the task in place — editing the working- * copy the user asked to isolate. Degrading to "just try it" is not an option.- */-export const MIN_LOCAL_WORKTREE_CLI_VERSION = "0.4.24";--/**- * Whether a daemon-reported CLI version can run worktree mode. Missing /- * unparsable / below-minimum are `false`; dev-built daemons (git-describe- * shape) pass, matching every other gate in this file.- */-export function localWorktreeSupported(detected: string | undefined | null): boolean {- return meetsMinCliVersion(detected, MIN_LOCAL_WORKTREE_CLI_VERSION);-}-/*** Capability a daemon advertises when it implements worktree mode for* local_directory resources. Mirrors `DaemonCapabilityLocalWorktreeV1` in@@ -176,25 +152,6 @@ export function localWorktreeSupported(detected: string | undefined | null): boo*/export const LOCAL_WORKTREE_CAPABILITY = "local-worktree-v1";-/**- * Whether a runtime advertised worktree support at registration.- *- * This replaces a version comparison on purpose. A daemon without the- * implementation does not merely lose concurrency — it ignores `execution_mode`- * and edits the user's working copy, which is what the mode exists to prevent.- * Version strings could not answer that: a dev build reports a git-describe- * string that `meetsMinCliVersion` deliberately exempts, so a daemon with no- * worktree code at all passed the check (MUL-5707).- *- * Absent metadata (an older daemon that never sent the header) is `false` —- * this must fail closed, and the server enforces the same thing at claim time.- */-export function runtimeSupportsLocalWorktree(metadata: unknown): boolean {- if (!metadata || typeof metadata !== "object") return false;- const caps = (metadata as { capabilities?: unknown }).capabilities;- return Array.isArray(caps) && caps.includes(LOCAL_WORKTREE_CAPABILITY);-}-/** Minimal runtime shape this module needs; keeps callers from importing types. */type RuntimeCapabilityRow = {daemon_id?: string | null;@@ -203,17 +160,29 @@ type RuntimeCapabilityRow = {};/**- * Whether the machine behind `daemonId` currently runs a daemon that supports- * worktree mode, judged by its MOST RECENTLY SEEN runtime row.+ * Whether the machine behind `daemonId` has ADVERTISED worktree support, judged+ * by its most recently seen runtime row.*- * Deliberately not "any row advertised it". Deregistering a runtime only marks- * the row offline — its metadata survives — so a machine that once ran a- * capable daemon and then downgraded still has an old capable row beside the- * fresh incapable one, and an any-match would answer yes forever. The server's- * `daemonAdvertisesWorktree` uses the same newest-wins rule; the two must agree- * or the UI offers a mode the API will refuse.+ * Deliberately a positive signal only, and deliberately not a gate. `false`+ * means "no runtime row here says yes" — which covers a daemon that genuinely+ * cannot, a row written before the server recorded capabilities at all, and a+ * server too old to record them in the first place. Those have different+ * remedies and the client cannot reliably tell them apart: it would have to+ * infer the backend's age from data the backend wrote, and a row's silence+ * outlives the upgrade that fixed it (#7113).+ *+ * So the client stopped trying. The server is asked instead — it knows its own+ * version by construction — at every write path (create project, add resource,+ * update resource) and again at claim time, which is the gate that actually+ * keeps agents out of the user's working copy (MUL-5707). This function only+ * decides whether to PRESELECT parallel mode, where a wrong guess costs a+ * radio button, not a blocked user or a misleading instruction.+ *+ * Newest-row, not any-row: deregistering a runtime only marks it offline and+ * its metadata survives, so a machine that once advertised the capability and+ * then downgraded would otherwise keep vouching for itself forever.*/-export function daemonSupportsLocalWorktree(+export function runtimeAdvertisesLocalWorktree(runtimes: RuntimeCapabilityRow[],daemonId: string | null | undefined,): boolean {@@ -230,5 +199,8 @@ export function daemonSupportsLocalWorktree(const currentSeen = newest.last_seen_at ?? "";if (candidateSeen > currentSeen) newest = rt;}- return newest ? runtimeSupportsLocalWorktree(newest.metadata) : false;+ const metadata = newest?.metadata;+ if (!metadata || typeof metadata !== "object") return false;+ const caps = (metadata as { capabilities?: unknown }).capabilities;+ return Array.isArray(caps) && caps.includes(LOCAL_WORKTREE_CAPABILITY);}diff --git a/packages/views/locales/en/projects.json b/packages/views/locales/en/projects.jsonindex 423a3a9eca..7ac7f91f6c 100644--- a/packages/views/locales/en/projects.json+++ b/packages/views/locales/en/projects.json@@ -127,8 +127,7 @@"mode_worktree_title": "Run in parallel, isolated","mode_worktree_description": "Tasks run at the same time without touching your working copy. Each one hands back an agent/… branch in this repo for you to review and merge.","mode_worktree_needs_git": "This folder is not a git repository, so there is nowhere to put the branch. Pick a repository, or keep editing the folder directly.",- "mode_worktree_needs_upgrade": "The Multica app on the machine this folder lives on is {{current}}; running tasks in parallel needs {{min}} or newer. Update it there, then switch this on.",- "mode_version_unknown": "an older version",+ "mode_worktree_needs_server_upgrade": "Your Multica server is too old to run tasks in parallel — it would quietly run them in this folder instead. Update the server, then switch this on.","mode_cancel": "Cancel","mode_save": "Save","mode_add": "Add folder",diff --git a/packages/views/locales/ja/projects.json b/packages/views/locales/ja/projects.jsonindex a5ea91570c..57900c4294 100644--- a/packages/views/locales/ja/projects.json+++ b/packages/views/locales/ja/projects.json@@ -126,8 +126,7 @@"mode_worktree_title": "隔離して並行実行する","mode_worktree_description": "タスクは作業コピーに触れずに同時実行されます。それぞれがこのリポジトリの agent/… ブランチを返すので、レビューしてマージします。","mode_worktree_needs_git": "このフォルダは git リポジトリではないため、ブランチを作成できません。リポジトリを選ぶか、フォルダを直接編集してください。",- "mode_worktree_needs_upgrade": "このフォルダがあるマシンの Multica は {{current}} です。並行実行には {{min}} 以降が必要です。そのマシンで更新してから有効にしてください。",- "mode_version_unknown": "古いバージョン",+ "mode_worktree_needs_server_upgrade": "接続中の Multica サーバーが古いため並行実行に対応できません。このままでは、タスクがこのフォルダ内で直接実行されてしまいます。サーバーを更新してから有効にしてください。","mode_cancel": "キャンセル","mode_save": "保存","mode_add": "フォルダを追加",diff --git a/packages/views/locales/ko/projects.json b/packages/views/locales/ko/projects.jsonindex bfd3dc6831..a38f3827e4 100644--- a/packages/views/locales/ko/projects.json+++ b/packages/views/locales/ko/projects.json@@ -126,8 +126,7 @@"mode_worktree_title": "격리해서 병렬 실행","mode_worktree_description": "작업이 작업 사본을 건드리지 않고 동시에 실행됩니다. 각 작업은 이 저장소의 agent/… 브랜치를 돌려주며, 검토 후 병합하면 됩니다.","mode_worktree_needs_git": "이 폴더는 git 저장소가 아니어서 브랜치를 만들 수 없습니다. 저장소를 선택하거나 폴더를 직접 수정하세요.",- "mode_worktree_needs_upgrade": "이 폴더가 있는 컴퓨터의 Multica는 {{current}}입니다. 병렬 실행에는 {{min}} 이상이 필요합니다. 해당 컴퓨터에서 업데이트한 뒤 켜세요.",- "mode_version_unknown": "이전 버전",+ "mode_worktree_needs_server_upgrade": "연결된 Multica 서버가 오래되어 병렬 실행을 지원하지 않습니다. 이대로면 작업이 이 폴더에서 그대로 실행됩니다. 서버를 업데이트한 뒤 켜세요.","mode_cancel": "취소","mode_save": "저장","mode_add": "폴더 추가",diff --git a/packages/views/locales/zh-Hans/projects.json b/packages/views/locales/zh-Hans/projects.jsonindex 5caced7194..9eb3c6e6a1 100644--- a/packages/views/locales/zh-Hans/projects.json+++ b/packages/views/locales/zh-Hans/projects.json@@ -126,8 +126,7 @@"mode_worktree_title": "并行隔离运行","mode_worktree_description": "任务可以同时跑,互不干扰,也不碰你的工作区。每条任务的结果是这个仓库里的一个 agent/… 分支,由你 review 后合并。","mode_worktree_needs_git": "这个文件夹不是 git 仓库,分支无处可放。请选择一个仓库,或者继续直接修改这个文件夹。",- "mode_worktree_needs_upgrade": "这个文件夹所在机器上的 Multica 是 {{current}},并行运行需要 {{min}} 或更新的版本。在那台机器上升级后即可开启。",- "mode_version_unknown": "较旧的版本",+ "mode_worktree_needs_server_upgrade": "当前 Multica 服务端版本过旧,无法支持并行运行——它会把任务直接跑在这个文件夹里。升级服务端后即可开启。","mode_cancel": "取消","mode_save": "保存","mode_add": "添加文件夹",diff --git a/packages/views/modals/create-project-local-mode.test.tsx b/packages/views/modals/create-project-local-mode.test.tsxindex f4c3139406..ea9d5fec9d 100644--- a/packages/views/modals/create-project-local-mode.test.tsx+++ b/packages/views/modals/create-project-local-mode.test.tsx@@ -9,9 +9,12 @@ import { renderWithI18n } from "../test/i18n";// Runtime list drives the worktree version gate. Each test sets the reported// CLI version before rendering.let runtimeCliVersion = "9.9.9";-// Whether the fake runtime advertises worktree support. This — not the version-// string — is what the gate reads now (MUL-5707).-let runtimeAdvertisesWorktree = true;+// What the fake runtime row says about worktree support. This — not the version+// string — is what the gate reads now (MUL-5707), and the three values are+// genuinely different states: "yes", "a daemon that cannot", and a row written+// by a server too old to record capabilities at all (#7113).+let runtimeWorktreeMetadata: "advertised" | "daemon_cannot" | "server_recorded_nothing" =+ "advertised";// What the desktop validator reports for the picked folder.let pickedIsGitRepo: boolean | undefined = true;@@ -42,7 +45,13 @@ vi.mock("@tanstack/react-query", () => ({daemon_id: "daemon-1",metadata: {cli_version: runtimeCliVersion,- ...(runtimeAdvertisesWorktree ? { capabilities: ["local-worktree-v1"] } : {}),+ // A capability-aware server always writes the key — null when the+ // daemon sent no header — so its absence means the SERVER is old.+ ...(runtimeWorktreeMetadata === "advertised"+ ? { capabilities: ["local-worktree-v1"] }+ : runtimeWorktreeMetadata === "daemon_cannot"+ ? { capabilities: ["skill-bundles-v1"] }+ : {}),},},],@@ -78,6 +87,14 @@ vi.mock("@multica/core/projects", () => ({}),}));+// Whether the connected server validates execution_mode at all. Absent on every+// release before the worktree save gate.+let serverValidatesWorktree = true;+vi.mock("@multica/core/config", () => ({+ useConfigStore: (selector: (state: { localWorktreeSupported: boolean }) => unknown) =>+ selector({ localWorktreeSupported: serverValidatesWorktree }),+}));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));vi.mock("@multica/core/paths", () => ({useCurrentWorkspace: () => ({ id: "workspace-1", slug: "ws", repos: [] }),@@ -162,7 +179,8 @@ describe("CreateProjectModal — local directory execution mode", () => {beforeEach(() => {createProjectMock.mockClear();runtimeCliVersion = "9.9.9";- runtimeAdvertisesWorktree = true;+ runtimeWorktreeMetadata = "advertised";+ serverValidatesWorktree = true;pickedIsGitRepo = true;});@@ -193,10 +211,13 @@ describe("CreateProjectModal — local directory execution mode", () => {expect(screen.getByRole("button", { name: /^Direct$/i })).toBeInTheDocument();});- // A runtime that cannot run the mode must not be preselected into it, or the- // create call would be rejected by the server's version gate.- it("preselects direct when the daemon does not support it, even for a git repository", async () => {- runtimeAdvertisesWorktree = false;+ // A machine that has not advertised the capability must not be preselected+ // into parallel: the server gates this create, and a rejection would fail the+ // whole project creation over a mode the user never chose. It stays+ // SELECTABLE — an un-advertised machine may still be able to run it, and only+ // the server can say (#7113).+ it("preselects direct when the machine has not advertised the capability", async () => {+ runtimeWorktreeMetadata = "daemon_cannot";const user = userEvent.setup();renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);@@ -251,19 +272,32 @@ describe("CreateProjectModal — local directory execution mode", () => {expect(screen.getByRole("button", { name: /Change directory/i })).toBeInTheDocument();});- // The server refuses to save a worktree resource below the version floor, and- // here that rejection would fail the whole project creation — so the option- // has to be blocked before submit, not after.- it("blocks parallel mode when the daemon does not support it", async () => {- runtimeAdvertisesWorktree = false;+ it("still offers parallel mode when the machine has not advertised", async () => {+ runtimeWorktreeMetadata = "server_recorded_nothing";+ const user = userEvent.setup();+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);++ await pickLocalDirectory(user);++ expect(screen.getByRole("radio", { name: /Run in parallel, isolated/i })).not.toBeDisabled();+ });++ // The version skew this whole issue is about: newest Desktop, newest daemon,+ // a self-hosted backend from before v0.4.25. That server accepts the save and+ // silently strips execution_mode, so trusting it to reject would hand the+ // agent the user's working copy while promising isolation.+ it("blocks parallel mode against a server that cannot honour it", async () => {+ serverValidatesWorktree = false;const user = userEvent.setup();renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);await pickLocalDirectory(user);- const worktreeOption = screen.getByRole("radio", { name: /Run in parallel, isolated/i });- expect(worktreeOption).toBeDisabled();- expect(screen.getByText(/needs 0\.4\.24 or newer/i)).toBeInTheDocument();+ expect(screen.getByRole("radio", { name: /Run in parallel, isolated/i })).toBeDisabled();+ expect(screen.getByText(/Multica server is too old/i)).toBeInTheDocument();+ // And it must not have been preselected either — that would submit a mode+ // the server would silently downgrade.+ expect(screen.getByRole("button", { name: /^Direct$/i })).toBeInTheDocument();});it("blocks parallel mode for a folder that is not a git repository", async () => {diff --git a/packages/views/modals/create-project.tsx b/packages/views/modals/create-project.tsxindex 422eff4872..0d1e8292fc 100644--- a/packages/views/modals/create-project.tsx+++ b/packages/views/modals/create-project.tsx@@ -68,11 +68,10 @@ import {} from "../platform/local-directory";import { useLocalDaemonStatus } from "../platform/use-local-daemon-status";import {- MIN_LOCAL_WORKTREE_CLI_VERSION,- daemonSupportsLocalWorktree,- readRuntimeCliVersion,+ runtimeAdvertisesLocalWorktree,runtimeListOptions,} from "@multica/core/runtimes";+import { useConfigStore } from "@multica/core/config";import type { LocalDirectoryExecutionMode } from "@multica/core/types";import { LocalDirectoryModeOptions } from "../projects/components/local-directory-mode-dialog";@@ -207,35 +206,40 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {// same call that creates the project, so an un-caught rejection would fail the// whole creation — check up front and disable the option instead.const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));- const localDaemonCliVersion = daemonStatus.daemonId- ? (runtimes- .filter((rt) => rt.daemon_id === daemonStatus.daemonId)- .map((rt) => readRuntimeCliVersion(rt.metadata))- .find((v) => v && v.length > 0) ?? "")- : "";// Capability, not version: a dev-built daemon reports a git-describe string// that the version floor exempts, so the version check passed for a binary- // with no worktree implementation (MUL-5707).- const localDaemonSupportsWorktree = daemonSupportsLocalWorktree(+ // with no worktree implementation (MUL-5707). A backend too old to record the+ // capability at all is its own answer — blaming this machine for that sent a+ // user off to update the one piece already on the newest release (#7113).+ // Preselection only — the server gates the save, including on this bundled+ // create path, and rejects with a message the modal surfaces.+ const localAdvertisesWorktree = runtimeAdvertisesLocalWorktree(runtimes,daemonStatus.daemonId,);+ // One declared boolean from the live server. Servers older than the worktree+ // save gate drop execution_mode and answer 201, so "the backend will check"+ // is only true once the backend says it checks (#7113).+ const serverValidatesWorktree = useConfigStore((state) => state.localWorktreeSupported);const worktreeUnavailableReason =localIsGitRepo === false? ("not_git" as const)- : !localDaemonSupportsWorktree- ? ("daemon_outdated" as const)+ : !serverValidatesWorktree+ ? ("server_outdated" as const): undefined;// Preselection, not a default behavior change: when the folder is a git repo- // and the runtime can actually run worktree mode, parallel is the better fit,- // so it starts selected — visibly, in a control the user can flip in one- // click before creating anything. A plain folder starts on direct.+ // and the machine has advertised that it can run worktree mode, parallel is+ // the better fit, so it starts selected — visibly, in a control the user can+ // flip in one click before creating anything. A plain folder starts on+ // direct, and so does a machine that has not advertised: it may still be able+ // to (an old row proves nothing), but choosing it FOR the user is how a+ // rejected save would turn into a failed project creation.//// `localIsGitRepo === undefined` (an older desktop build that doesn't report// it) preselects direct. The asymmetry is deliberate: permissive about what// the user MAY choose, conservative about what we choose FOR them.const preselectedLocalMode: LocalDirectoryExecutionMode =- localIsGitRepo === true && worktreeUnavailableReason === undefined+ localIsGitRepo === true && localAdvertisesWorktree && worktreeUnavailableReason === undefined? "worktree": "in_place";// Never submit a mode the picker would have blocked — the folder can change@@ -899,8 +903,6 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {setLocalModeOpen(false);}}unavailableReason={worktreeUnavailableReason}- currentVersion={localDaemonCliVersion}- minVersion={MIN_LOCAL_WORKTREE_CLI_VERSION}/></PopoverContent></Popover>diff --git a/packages/views/projects/components/local-directory-hint.tsx b/packages/views/projects/components/local-directory-hint.tsxindex 85c5503706..979adac3f8 100644--- a/packages/views/projects/components/local-directory-hint.tsx+++ b/packages/views/projects/components/local-directory-hint.tsx@@ -7,6 +7,7 @@ import type { LocalDirectoryResourceRef, ProjectResource } from "@multica/core/timport { useWorkspaceId } from "@multica/core/hooks";import { useLocalDaemonStatus } from "../../platform";import { useT } from "../../i18n";+import { localDirectoryLabel } from "./local-directory-label";/*** Banner shown at the top of the issue's Activity section when the@@ -58,8 +59,7 @@ export function LocalDirectoryHint({<div className="mt-3 space-y-1 rounded-md border border-dashed bg-muted/40 px-3 py-2 text-caption text-muted-foreground">{matches.map((resource) => {const ref = resource.resource_ref;- const label = (ref.label || resource.label || ref.local_path).trim() ||- ref.local_path;+ const label = localDirectoryLabel(resource);// Anything other than an explicit "worktree" is in_place: the mode is// absent on resources created before it existed, and an unknown value// from a newer server must not claim isolation we cannot verify.diff --git a/packages/views/projects/components/local-directory-label.test.ts b/packages/views/projects/components/local-directory-label.test.tsnew file mode 100644index 0000000000..8f28035a03--- /dev/null+++ b/packages/views/projects/components/local-directory-label.test.ts@@ -0,0 +1,54 @@+// @vitest-environment node++import { describe, it, expect } from "vitest";+import { localDirectoryLabel } from "./local-directory-label";++// Canonical priority matrix for the display name of a local_directory row.+// The component suites (project-resources-rename.test.tsx) keep the wiring+// and named regressions; the read-order truth lives here.+describe("localDirectoryLabel", () => {+ const ref = (overrides: Partial<{ label: string }> = {}) => ({+ local_path: "/Users/dev/work/game-client",+ daemon_id: "d1",+ ...overrides,+ });++ it("prefers the top-level column — where renames write — over the ref copy", () => {+ expect(+ localDirectoryLabel({+ label: "Renamed Client",+ resource_ref: ref({ label: "Game Client" }),+ }),+ ).toBe("Renamed Client");+ });++ it("falls back to the ref copy: rows created by older clients have no column", () => {+ expect(+ localDirectoryLabel({+ label: null,+ resource_ref: ref({ label: "Game Client" }),+ }),+ ).toBe("Game Client");+ });++ it("shows the path when neither copy names the row — a cleared name must not resurrect", () => {+ expect(+ localDirectoryLabel({ label: null, resource_ref: ref() }),+ ).toBe("/Users/dev/work/game-client");+ });++ it("treats whitespace-only labels as absent instead of rendering a blank row", () => {+ expect(+ localDirectoryLabel({ label: " ", resource_ref: ref() }),+ ).toBe("/Users/dev/work/game-client");+ });++ it("trims the winning value", () => {+ expect(+ localDirectoryLabel({+ label: " Renamed Client ",+ resource_ref: ref({ label: "Game Client" }),+ }),+ ).toBe("Renamed Client");+ });+});diff --git a/packages/views/projects/components/local-directory-label.ts b/packages/views/projects/components/local-directory-label.tsnew file mode 100644index 0000000000..74b0289bc8--- /dev/null+++ b/packages/views/projects/components/local-directory-label.ts@@ -0,0 +1,29 @@+import type {+ LocalDirectoryResourceRef,+ ProjectResource,+} from "@multica/core/types";++/**+ * Display name for a local_directory row.+ *+ * A row's name can live in two places: the top-level `label` column (written+ * by renames since they stopped resending the ref — see+ * handleRenameLocalDirectory in project-resources-section.tsx) and the legacy+ * copy inside the ref (the only home desktop builds up to v0.4.28 knew).+ * Current servers keep the two converged on every write, but rows last+ * written by an older server can still disagree, and rows created by older+ * clients carry only the ref copy. The column outranks the ref copy because+ * it is the one current-client renames write; the path is the last resort so+ * a row never renders nameless.+ */+export function localDirectoryLabel(+ resource: Pick<ProjectResource, "label"> & {+ resource_ref: LocalDirectoryResourceRef;+ },+): string {+ const ref = resource.resource_ref;+ return (+ (resource.label || ref.label || ref.local_path).trim() ||+ ref.local_path.trim()+ );+}diff --git a/packages/views/projects/components/local-directory-mode-dialog.test.tsx b/packages/views/projects/components/local-directory-mode-dialog.test.tsxindex 4bd64346a0..f9773b3fab 100644--- a/packages/views/projects/components/local-directory-mode-dialog.test.tsx+++ b/packages/views/projects/components/local-directory-mode-dialog.test.tsx@@ -15,7 +15,6 @@ function renderDialog(overrides: {value?: LocalDirectoryExecutionMode;unavailableReason?: WorktreeUnavailableReason;- currentVersion?: string;errorMessage?: string;onConfirm?: (mode: LocalDirectoryExecutionMode) => void;} = {},@@ -29,8 +28,6 @@ function renderDialog(path="/Users/dev/work/game-client"value={overrides.value ?? "in_place"}unavailableReason={overrides.unavailableReason}- currentVersion={overrides.currentVersion}- minVersion="0.4.24"errorMessage={overrides.errorMessage}confirmLabel="Save"onConfirm={onConfirm}@@ -90,26 +87,45 @@ describe("LocalDirectoryModeDialog", () => {expect(onConfirm).toHaveBeenCalledWith("in_place");});- // The server refuses the save below the version floor; saying so up front- // beats a bare 422 after the user has already committed to the choice.- it("disables parallel mode for an outdated daemon and names both versions", () => {- renderDialog({- unavailableReason: "daemon_outdated",- currentVersion: "0.4.10",- });+ // A server older than the worktree save gate does not reject the mode — it+ // drops execution_mode, answers 201, and the task then runs in the folder the+ // user asked to isolate. Nothing downstream catches that, so the option has+ // to be closed here, and the copy has to say what is actually wrong (#7113).+ it("blocks parallel mode when the server cannot honour it", () => {+ const onConfirm = vi.fn();+ renderDialog({ unavailableReason: "server_outdated", onConfirm });- expect(worktreeOption().hasAttribute("disabled")).toBe(true);- const notice = screen.getByText(/0\.4\.10/);- expect(notice.textContent).toContain("0.4.24");- });+ const option = worktreeOption();+ expect(option.hasAttribute("disabled")).toBe(true);+ const notice = screen.getByText(/Multica server is too old/i);+ expect(notice.textContent).toMatch(/Update the server/i);- it("falls back to a readable phrase when the daemon reports no version", () => {- renderDialog({ unavailableReason: "daemon_outdated", currentVersion: "" });- expect(screen.getByText(/an older version/i)).toBeTruthy();+ fireEvent.click(option);+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ expect(onConfirm).toHaveBeenCalledWith("in_place");});+ // The client no longer predicts whether the machine can run the mode — the+ // server decides on save, and this is where its answer lands. Guessing it up+ // front is what disabled the option for a user whose machine was already on+ // the newest release, with an instruction that could not help (#7113).it("shows a server rejection inline so the dialog stays actionable", () => {- renderDialog({ errorMessage: "daemon is too old to run worktree mode" });- expect(screen.getByText(/too old to run worktree mode/i)).toBeTruthy();+ renderDialog({+ errorMessage:+ "the Multica runtime on that machine does not support it. Update the Multica app on that machine",+ });+ expect(screen.getByText(/does not support it/i)).toBeTruthy();+ });++ it("leaves parallel mode selectable for a git folder, whatever the runtime says", () => {+ const onConfirm = vi.fn();+ renderDialog({ onConfirm });++ const option = worktreeOption();+ expect(option.hasAttribute("disabled")).toBe(false);+ fireEvent.click(option);+ fireEvent.click(screen.getByRole("button", { name: "Save" }));++ expect(onConfirm).toHaveBeenCalledWith("worktree");});});diff --git a/packages/views/projects/components/local-directory-mode-dialog.tsx b/packages/views/projects/components/local-directory-mode-dialog.tsxindex a2116c5ade..c8cd3549dd 100644--- a/packages/views/projects/components/local-directory-mode-dialog.tsx+++ b/packages/views/projects/components/local-directory-mode-dialog.tsx@@ -15,14 +15,23 @@ import {import { useT } from "../../i18n/use-t";/**- * Why the worktree option may be unavailable. The two cases need different- * copy and different remedies, so they are distinct rather than one boolean:- * `not_git` is fixed by choosing a different folder, `daemon_outdated` by- * updating the app on that machine.+ * Why the worktree option may be unavailable.+ *+ * Two reasons, and neither is a guess about the machine. `not_git` the client+ * establishes by itself — the folder either has a repository to branch from or+ * it does not, and the desktop picker checked. `server_outdated` is what the+ * SERVER says about itself: whether it understands `execution_mode` at all.+ *+ * Whether the MACHINE can run the mode is deliberately absent. That is the+ * server's question, asked on every save, and a rejection comes back as+ * `errorMessage` rather than as a disabled option guessed at up front (#7113).+ * But deferring to the server is only safe once the server has said it will+ * actually check: older ones drop the field and answer 201, and the task then+ * edits the directory the user asked to isolate.** `undefined` means available.*/-export type WorktreeUnavailableReason = "not_git" | "daemon_outdated";+export type WorktreeUnavailableReason = "not_git" | "server_outdated";interface LocalDirectoryModeDialogProps {open: boolean;@@ -33,9 +42,6 @@ interface LocalDirectoryModeDialogProps {value: LocalDirectoryExecutionMode;/** Set when worktree cannot be chosen; the option renders disabled with a reason. */unavailableReason?: WorktreeUnavailableReason;- /** Daemon version strings for the outdated message. */- currentVersion?: string;- minVersion?: string;/** Server-side rejection to show inline (e.g. a 422 that only the API can detect). */errorMessage?: string;saving?: boolean;@@ -59,8 +65,6 @@ export function LocalDirectoryModeDialog({path,value,unavailableReason,- currentVersion,- minVersion,errorMessage,saving = false,confirmLabel,@@ -93,8 +97,6 @@ export function LocalDirectoryModeDialog({value={selected}onChange={setSelected}unavailableReason={unavailableReason}- currentVersion={currentVersion}- minVersion={minVersion}/>{errorMessage && (@@ -125,8 +127,6 @@ interface LocalDirectoryModeOptionsProps {value: LocalDirectoryExecutionMode;onChange: (mode: LocalDirectoryExecutionMode) => void;unavailableReason?: WorktreeUnavailableReason;- currentVersion?: string;- minVersion?: string;}/**@@ -140,8 +140,6 @@ export function LocalDirectoryModeOptions({value,onChange,unavailableReason,- currentVersion,- minVersion,}: LocalDirectoryModeOptionsProps) {const { t } = useT("projects");const worktreeDisabled = unavailableReason !== undefined;@@ -166,14 +164,8 @@ export function LocalDirectoryModeOptions({disabledReason={unavailableReason === "not_git"? t(($) => $.resources.mode_worktree_needs_git)- : unavailableReason === "daemon_outdated"- ? t(($) => $.resources.mode_worktree_needs_upgrade, {- current:- currentVersion && currentVersion.length > 0- ? currentVersion- : t(($) => $.resources.mode_version_unknown),- min: minVersion ?? "",- })+ : unavailableReason === "server_outdated"+ ? t(($) => $.resources.mode_worktree_needs_server_upgrade): undefined}onSelect={() => onChange("worktree")}diff --git a/packages/views/projects/components/project-resources-rename.test.tsx b/packages/views/projects/components/project-resources-rename.test.tsxnew file mode 100644index 0000000000..9286d1afa3--- /dev/null+++ b/packages/views/projects/components/project-resources-rename.test.tsx@@ -0,0 +1,119 @@+// @vitest-environment jsdom++import { describe, it, expect, vi, beforeEach } from "vitest";+import { screen, fireEvent, waitFor } from "@testing-library/react";+import { renderWithI18n } from "../../test/i18n";++const updateMock = vi.fn().mockResolvedValue({});++const RESOURCE = {+ id: "res-1",+ project_id: "p1",+ workspace_id: "workspace-1",+ resource_type: "local_directory",+ resource_ref: {+ local_path: "/Users/dev/work/game-client",+ daemon_id: "daemon-1",+ label: "Game Client",+ // The setting this test exists to protect.+ execution_mode: "worktree",+ },+ // A row renamed since: the top-level column holds the current name while the+ // ref still carries the one it was created with.+ label: "Renamed Client",+ position: 0,+ created_at: "2026-08-18T00:00:00Z",+ created_by: "u1",+};++vi.mock("@tanstack/react-query", () => ({+ useQuery: (options: { queryKey?: unknown[] }) => {+ const key = options?.queryKey?.[0];+ if (key === "project-resources") return { data: [RESOURCE] };+ return { data: [] };+ },+ queryOptions: (options: unknown) => options,+}));++vi.mock("@multica/core/projects", () => ({+ projectResourcesOptions: () => ({ queryKey: ["project-resources"], queryFn: vi.fn() }),+ useCreateProjectResource: () => ({ mutateAsync: vi.fn() }),+ useUpdateProjectResource: () => ({ mutateAsync: updateMock }),+ useDeleteProjectResource: () => ({ mutateAsync: vi.fn() }),+}));++// A backend that predates the capability signal: the client must assume it+// would silently drop execution_mode.+vi.mock("@multica/core/config", () => ({+ useConfigStore: (selector: (state: { localWorktreeSupported: boolean }) => unknown) =>+ selector({ localWorktreeSupported: false }),+}));++vi.mock("@multica/core/runtimes", () => ({+ runtimeListOptions: () => ({ queryKey: ["runtimes"], queryFn: vi.fn() }),+ runtimeAdvertisesLocalWorktree: () => true,+}));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));+vi.mock("@multica/core/paths", () => ({+ useCurrentWorkspace: () => ({ id: "workspace-1", slug: "ws", repos: [] }),+}));+vi.mock("../../platform/local-directory", () => ({+ isDesktopShell: () => true,+ pickDirectory: vi.fn(),+ validateLocalDirectory: vi.fn(),+}));+vi.mock("../../platform/use-local-daemon-status", () => ({+ useLocalDaemonStatus: () => ({ daemonId: "daemon-1", deviceName: "MacBook", running: true }),+}));+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++import { ProjectResourcesSection } from "./project-resources-section";++describe("ProjectResourcesSection — renaming a worktree local directory", () => {+ beforeEach(() => updateMock.mockClear());++ // The reported skew, one step further on: backend rolled back below v0.4.25+ // while the runtimes stay current — a combination the docs call supported.+ // Such a server replaces the ref with whatever it can parse, so resending it+ // during an unrelated edit drops execution_mode, answers 200, and the next+ // task edits the working copy the resource asked to isolate (#7113).+ it("sends only the label, never a ref the server could strip", async () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getByTitle(/rename/i));+ const input = screen.getByRole("textbox");+ fireEvent.change(input, { target: { value: "Client Worktree" } });+ fireEvent.keyDown(input, { key: "Enter" });++ await waitFor(() => expect(updateMock).toHaveBeenCalledTimes(1));+ const payload = updateMock.mock.calls[0]?.[0] as { data: unknown };+ expect(payload.data).toEqual({ label: "Client Worktree" });+ expect(payload.data).not.toHaveProperty("resource_ref");+ });++ // The new name has to be what the user sees afterwards, which only holds if+ // the top-level label outranks the stale one still sitting inside the ref.+ // Full read-order matrix: local-directory-label.test.ts.+ it("shows the top-level label over the one left behind in the ref", () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);+ expect(screen.getByText("Renamed Client")).toBeInTheDocument();+ expect(screen.queryByText("Game Client")).not.toBeInTheDocument();+ });++ // Clearing goes through the same label-only path as renaming: an emptied+ // input must not fall back to resending the ref either, and the server is+ // the one that drops BOTH label copies so the old name cannot resurrect.+ it("sends a label-only clear when the input is emptied", async () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getByTitle(/rename/i));+ const input = screen.getByRole("textbox");+ fireEvent.change(input, { target: { value: " " } });+ fireEvent.keyDown(input, { key: "Enter" });++ await waitFor(() => expect(updateMock).toHaveBeenCalledTimes(1));+ const payload = updateMock.mock.calls[0]?.[0] as { data: unknown };+ expect(payload.data).toEqual({ label: "" });+ expect(payload.data).not.toHaveProperty("resource_ref");+ });+});diff --git a/packages/views/projects/components/project-resources-section.tsx b/packages/views/projects/components/project-resources-section.tsxindex b37d989e4f..ab27dc5738 100644--- a/packages/views/projects/components/project-resources-section.tsx+++ b/packages/views/projects/components/project-resources-section.tsx@@ -28,11 +28,10 @@ import type {ProjectResource,} from "@multica/core/types";import {- MIN_LOCAL_WORKTREE_CLI_VERSION,- daemonSupportsLocalWorktree,- readRuntimeCliVersion,+ runtimeAdvertisesLocalWorktree,runtimeListOptions,} from "@multica/core/runtimes";+import { useConfigStore } from "@multica/core/config";import { Badge } from "@multica/ui/components/ui/badge";import { Button } from "@multica/ui/components/ui/button";import {@@ -56,6 +55,7 @@ import {LocalDirectoryModeDialog,type WorktreeUnavailableReason,} from "./local-directory-mode-dialog";+import { localDirectoryLabel } from "./local-directory-label";import { useT } from "../../i18n";import { githubShortLabel } from "../../common/github-url";@@ -129,31 +129,26 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {const desktopMode = isDesktopShell();const localDaemonId = daemonStatus.daemonId;- // Worktree mode needs a daemon new enough to implement it. An older daemon- // does not know the field exists and would run the task in place — editing- // the working copy the user asked to isolate — so the server refuses the- // save. Checking here too turns that 422 into a disabled option with a- // reason, at the moment the user is choosing.+ // Only ever used to decide what to PRESELECT. Whether the machine can run+ // worktree mode is the server's call — it knows its own version, the client+ // would have to infer it from data the server wrote, and that inference is+ // what told a user on the newest release to upgrade it (#7113). The save is+ // gated server-side and surfaced here as an inline error instead.const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));+ // The one thing the client must still check up front: whether this server+ // performs that gate at all. One declared boolean, no inference — servers+ // that predate it drop execution_mode and answer 201.+ const serverValidatesWorktree = useConfigStore((state) => state.localWorktreeSupported);// Keyed on the resource's OWN daemon, not the machine the browser happens to// be on: a resource is pinned to one machine, and its mode can legitimately// be changed from the web app or from a different device. Using the local// daemon here would report "too old" for every resource whenever the viewer// is not on that machine.// Capability, not version, and judged by the daemon's newest runtime row —- // see daemonSupportsLocalWorktree for why an any-match would keep saying yes- // after a downgrade.- const daemonSupportsWorktree = (daemonId: string | null): boolean =>- daemonSupportsLocalWorktree(runtimes, daemonId);- const cliVersionForDaemon = (daemonId: string | null): string => {- if (!daemonId) return "";- return (- runtimes- .filter((rt) => rt.daemon_id === daemonId)- .map((rt) => readRuntimeCliVersion(rt.metadata))- .find((v) => v && v.length > 0) ?? ""- );- };+ // see runtimeAdvertisesLocalWorktree for why an any-match would keep saying+ // yes after a downgrade.+ const advertisesWorktree = (daemonId: string | null) =>+ runtimeAdvertisesLocalWorktree(runtimes, daemonId);const attachedUrls = new Set(resources.filter(isGithubRef).map((r) => r.resource_ref.url),@@ -249,7 +244,8 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {// user still confirms, and existing resources keep whatever they have.mode:validation.is_git_repo === true &&- daemonSupportsWorktree(localDaemonId)+ serverValidatesWorktree &&+ advertisesWorktree(localDaemonId)? "worktree": "in_place",isGitRepo: validation.is_git_repo,@@ -333,17 +329,21 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {nextLabel: string,) => {const trimmed = nextLabel.trim();- const previous = resource.resource_ref.label ?? resource.label ?? "";- if (trimmed === previous.trim()) return;+ if (trimmed === localDirectoryLabel(resource)) return;try {+ // Top-level label ONLY — renaming must not resend resource_ref.+ //+ // The server replaces the ref wholesale with whatever it can parse, so a+ // server that predates a ref field drops it and answers 200. On a backend+ // rolled back below v0.4.25 (documented as supported while the runtimes+ // stay current) that turned "rename this folder" into "silently forget+ // this folder was isolated", and the next task edited the working copy+ // (#7113). Omitting the ref keeps the stored one untouched on every+ // server version — the same reason it must not be resent for any other+ // unrelated edit either.await updateResource.mutateAsync({resourceId: resource.id,- data: {- resource_ref: {- ...resource.resource_ref,- label: trimmed,- },- },+ data: { label: trimmed },});toast.success(t(($) => $.resources.toast_local_renamed));} catch (err) {@@ -536,10 +536,8 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {value={modeDialog.mode}unavailableReason={worktreeUnavailableReason(modeDialog.isGitRepo,- daemonSupportsWorktree(modeDialog.daemonId),+ serverValidatesWorktree,)}- currentVersion={cliVersionForDaemon(modeDialog.daemonId)}- minVersion={MIN_LOCAL_WORKTREE_CLI_VERSION}errorMessage={modeError ?? undefined}saving={modeSaving}confirmLabel={@@ -561,15 +559,19 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {* folder. `undefined` means we could not check (an older desktop build, or an* existing row whose path was validated at pick time), and is deliberately* permissive: the daemon re-checks authoritatively, so guessing "not a repo"- * here would block a perfectly valid setup. The daemon-version gate is checked- * second because upgrading is the more actionable of the two.+ * here would block a perfectly valid setup.+ *+ * Daemon capability is deliberately absent. It is the server's question, asked+ * on save; predicting it here is what produced an unfixable blocker for a user+ * already on the newest release (#7113). Deferring to the server does require+ * knowing it will answer, though — `serverValidates` is the server saying so.*/function worktreeUnavailableReason(isGitRepo: boolean | undefined,- daemonSupportsWorktree: boolean,+ serverValidates: boolean,): WorktreeUnavailableReason | undefined {if (isGitRepo === false) return "not_git";- if (!daemonSupportsWorktree) return "daemon_outdated";+ if (!serverValidates) return "server_outdated";return undefined;}@@ -685,8 +687,7 @@ function LocalDirectoryRow({const { t } = useT("projects");const ref = resource.resource_ref;const mode = executionModeOf(ref);- const display = (ref.label || resource.label || ref.local_path).trim() ||- ref.local_path;+ const display = localDirectoryLabel(resource);const isForeignDaemon =localDaemonId !== null && ref.daemon_id !== localDaemonId;const isLocalUnknown = localDaemonId === null;diff --git a/server/internal/handler/config.go b/server/internal/handler/config.goindex 58bf5c5719..4ccb350c52 100644--- a/server/internal/handler/config.go+++ b/server/internal/handler/config.go@@ -59,6 +59,22 @@ type AppConfig struct {// raw rules here: /api/config is public and may be called anonymously.FeatureFlags map[string]bool `json:"feature_flags,omitempty"`+ // LocalWorktreeSupported tells clients this server understands+ // local_directory `execution_mode` and enforces the worktree capability+ // gate when a resource is saved.+ //+ // Load-bearing for CLIENTS, not for this server. Releases before v0.4.25+ // unmarshalled the ref into a struct without the field and re-marshalled+ // it, so `execution_mode: "worktree"` was silently DROPPED and answered+ // 201 — the resource then ran in_place, editing the working copy the user+ // asked to isolate, with no gate anywhere to catch it. A new client cannot+ // tell that from success, so it has to ask first, and absent has to read as+ // "cannot honour it": every release that drops the field also omits this+ // one. Releases between that fix and this signal do gate the save but say+ // nothing, so they are treated the same way — the client cannot distinguish+ // them, and only one of the two guesses is safe.+ LocalWorktreeSupported bool `json:"local_worktree_supported"`+// ServerVersion is the running API build version, so self-hosted// operators can confirm what's deployed and include it in bug reports.// Only emitted on self-hosted deployments — omitted on the managed cloud,@@ -73,6 +89,9 @@ type AppConfig struct {// to anonymous callers — never user- or tenant-scoped data.func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {config := AppConfig{+ // A property of this build, not of the deployment: if this code is+ // running, the save gate is running with it.+ LocalWorktreeSupported: true,AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",GoogleClientID: os.Getenv("GOOGLE_CLIENT_ID"),WorkspaceCreationDisabled: os.Getenv("DISABLE_WORKSPACE_CREATION") == "true",diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.goindex 773f694ff8..2fb2ba09c5 100644--- a/server/internal/handler/config_test.go+++ b/server/internal/handler/config_test.go@@ -462,3 +462,34 @@ func TestGetConfigExposesEnabledPluginsV1Flag(t *testing.T) {t.Fatal("plugins_v1: want true with flag enabled, got false")}}++// Clients fail closed on this flag: absent covers every server that predates+// the signal, including the ones that accept a worktree resource, silently drop+// execution_mode and run the task in the user's working copy (#7113). A build+// that HAS the save gate therefore has to say so,+// unconditionally — not behind a deployment check, an env var or a feature+// flag, all of which would disable worktree mode for the users who can run it.+func TestGetConfigDeclaresLocalWorktreeSupport(t *testing.T) {+ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)+ w := httptest.NewRecorder()+ testHandler.GetConfig(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("GetConfig: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var cfg AppConfig+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {+ t.Fatalf("decode config: %v", err)+ }+ if !cfg.LocalWorktreeSupported {+ t.Fatal("this build runs the worktree save gate but does not advertise it; clients will hide the mode")+ }+ // Serialised as a real key, not omitted when false-by-accident: the client+ // distinguishes "absent" (old server) from an explicit answer.+ var raw map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {+ t.Fatalf("decode raw config: %v", err)+ }+ if _, ok := raw["local_worktree_supported"]; !ok {+ t.Fatal("local_worktree_supported missing from the JSON body")+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 83208fdd04..8306de08ae 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -661,10 +661,17 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {if resolvedCommandName == "" {resolvedCommandName = profile.CommandName}+ // Capabilities belong on this row too. It is written AFTER the+ // successful runtimes in the same request, so its last_seen_at is+ // the newest for this daemon until the first heartbeat — and the+ // worktree gates read the newest row. Omitting them made a failed+ // profile look, for that window, like a daemon that advertises+ // nothing (and now like a capability-blind server).metadata, _ := json.Marshal(map[string]any{"version": "","cli_version": req.CLIVersion,"launched_by": req.LaunchedBy,+ "capabilities": requestClientCapabilities(r),"runtime_profile_registration_error": true,"runtime_profile_failure_reason": reason,"command_name": resolvedCommandName,diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex f5d51d2583..2da7a3561b 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -976,6 +976,7 @@ func TestDaemonRegister_RecordsRuntimeProfileRegistrationFailure(t *testing.T) {},},}, testWorkspaceID, "test-daemon-profile-failure")+ req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityLocalWorktreeV1)testHandler.DaemonRegister(w, req)if w.Code != http.StatusOK {@@ -1006,6 +1007,21 @@ func TestDaemonRegister_RecordsRuntimeProfileRegistrationFailure(t *testing.T) {if meta["runtime_profile_failure_reason"] != "command not found on PATH: missing-codex" {t.Fatalf("failure reason metadata = %#v", meta["runtime_profile_failure_reason"])}+ // This row is written AFTER the successful runtimes of the same request, so+ // its last_seen_at is the newest for the daemon until the first heartbeat —+ // and the worktree gates read the newest row. A failed profile must not make+ // a capable daemon look incapable for that window, nor (on the UI side) make+ // this server look too old to record capabilities at all.+ caps, _ := meta["capabilities"].([]any)+ found := false+ for _, c := range caps {+ if c == protocol.DaemonCapabilityLocalWorktreeV1 {+ found = true+ }+ }+ if !found {+ t.Fatalf("advertised capabilities missing from failure row: %#v", meta["capabilities"])+ }}func TestDaemonRegister_WithDaemonToken_WorkspaceMismatch(t *testing.T) {diff --git a/server/internal/handler/project.go b/server/internal/handler/project.goindex 3a9bf6f5d0..46fad304f1 100644--- a/server/internal/handler/project.go+++ b/server/internal/handler/project.go@@ -331,6 +331,15 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {return}localDirSeen[ld.DaemonID] = i+ // Same worktree gate the standalone POST/PUT paths run. This+ // bundled-create surface skipped it, so a project created with a+ // worktree local_directory could store a mode the machine cannot+ // run — caught only later, by the claim gate cancelling the task.+ // It writes its own 422; it runs before the transaction, so a+ // rejection leaves nothing behind.+ if !h.requireWorktreeCapableDaemon(w, r, wsUUID, res.ResourceType, ref) {+ return+ }}}diff --git a/server/internal/handler/project_resource.go b/server/internal/handler/project_resource.goindex dadbec6804..d929a5789f 100644--- a/server/internal/handler/project_resource.go+++ b/server/internal/handler/project_resource.go@@ -7,6 +7,7 @@ import ("fmt""net/http""net/url"+ "reflect""strings""github.com/go-chi/chi/v5"@@ -296,6 +297,86 @@ func validateLocalDirectoryRef(ref json.RawMessage) (json.RawMessage, error) {return out, nil}+// localDirectoryRefLabel reads the label carried inside a local_directory ref,+// trimmed. Returns "" for a missing label or a ref that does not parse — the+// callers only compare labels, so an unreadable ref behaves like an unlabeled+// one instead of failing the write.+func localDirectoryRefLabel(ref json.RawMessage) string {+ var payload localDirectoryRef+ if err := json.Unmarshal(ref, &payload); err != nil {+ return ""+ }+ return strings.TrimSpace(payload.Label)+}++// localDirectoryRefDiffersOnlyByLabel reports whether two refs are identical+// once their labels are set aside.+//+// This is what separates "a ≤ v0.4.28 client renamed the folder" from "a client+// sent a ref it had been holding since before someone else renamed it". Both+// arrive as a full ref whose label differs from the stored one; only the first+// is a rename. The mode dialog snapshots the whole ref when it opens, so a+// second device renaming in between turns an execution-mode save into a name+// rollback unless the two are told apart.+//+// Compared as decoded values rather than bytes: the stored ref may have been+// written by a different build, so key order and spacing prove nothing. Unknown+// keys count — a difference this binary cannot interpret is still a difference,+// and calling such a request a pure rename would be a guess.+func localDirectoryRefDiffersOnlyByLabel(a, b json.RawMessage) bool {+ strip := func(raw json.RawMessage) (map[string]any, bool) {+ var fields map[string]any+ if err := json.Unmarshal(raw, &fields); err != nil {+ return nil, false+ }+ delete(fields, "label")+ return fields, true+ }+ left, ok := strip(a)+ if !ok {+ return false+ }+ right, ok := strip(b)+ if !ok {+ return false+ }+ return reflect.DeepEqual(left, right)+}++// withLocalDirectoryRefLabel returns ref with only its "label" key set (or+// removed, when label is NULL) and every other key preserved.+//+// A local_directory's display name has two homes: desktop builds up to v0.4.28+// rename by rewriting resource_ref.label, newer clients rename the top-level+// column precisely so they never resend the ref (an older server re-normalizes+// a resent ref and silently drops the fields it does not know — see+// handleRenameLocalDirectory in project-resources-section.tsx). This server is+// the only writer that sees both kinds of client, so it converges the two+// copies on every write; without that, each client generation keeps editing+// its own copy and the same row shows different names on different devices.+//+// Patch the raw map rather than round-tripping localDirectoryRef: the stored+// ref may carry fields written by a NEWER server, and re-marshaling through+// this binary's struct would drop them — the exact failure mode this PR exists+// to close. Key order and whitespace are not preserved (nor promised by JSONB);+// every key and value is.+func withLocalDirectoryRefLabel(ref json.RawMessage, label pgtype.Text) (json.RawMessage, error) {+ var fields map[string]json.RawMessage+ if err := json.Unmarshal(ref, &fields); err != nil {+ return nil, err+ }+ if label.Valid {+ encoded, err := json.Marshal(label.String)+ if err != nil {+ return nil, err+ }+ fields["label"] = encoded+ } else {+ delete(fields, "label")+ }+ return json.Marshal(fields)+}+// isAbsoluteLocalPath checks the path looks absolute on either POSIX or// Windows daemons. The server can't know which OS the daemon runs on, so we// accept the union: a leading "/" (POSIX), a UNC prefix "\\", or a drive@@ -526,7 +607,8 @@ func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request)}nextRef := json.RawMessage(existing.ResourceRef)- if rawRef, ok := raw["resource_ref"]; ok {+ rawRef, refProvided := raw["resource_ref"]+ if refProvided {normalized, err := validateAndNormalizeResourceRef(existing.ResourceType, rawRef)if err != nil {writeError(w, http.StatusBadRequest, err.Error())@@ -543,16 +625,30 @@ func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request)return}- // Gate only when the caller is changing the ref: a label/position-only- // update must not start failing because the daemon's version drifted- // after the mode was legitimately saved.- if _, refProvided := raw["resource_ref"]; refProvided {+ // A ≤ v0.4.28 client renames by resending the ref, so "the ref was sent"+ // does not mean "the execution mode was touched". Anything else about the+ // ref changing does mean it might have been.+ refRenameOnly := refProvided &&+ existing.ResourceType == "local_directory" &&+ localDirectoryRefDiffersOnlyByLabel(nextRef, existing.ResourceRef)++ // Gate only when the caller is actually changing what would run: a label or+ // position update — including an old client's rename, which carries the ref+ // along — must not start failing because the daemon's registration drifted+ // after the mode was legitimately saved. The row already says worktree; the+ // claim gate is what stops it from running somewhere that cannot.+ if refProvided && !refRenameOnly {if !h.requireWorktreeCapableDaemon(w, r, project.WorkspaceID, existing.ResourceType, nextRef) {return}}nextLabel := existing.Label+ // Tracks an explicit clear, as opposed to a column that was never set.+ // Only the former may remove the ref's legacy label copy below: rows+ // created by older clients keep their only name inside the ref, and an+ // unrelated update must not strip it just because the column is NULL.+ labelCleared := falseif rawLabel, ok := raw["label"]; ok {var labelStr *stringif err := json.Unmarshal(rawLabel, &labelStr); err != nil {@@ -561,9 +657,29 @@ func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request)}if labelStr == nil || strings.TrimSpace(*labelStr) == "" {nextLabel = pgtype.Text{}+ labelCleared = true} else {nextLabel = pgtype.Text{String: strings.TrimSpace(*labelStr), Valid: true}}+ } else if refRenameOnly {+ // No label field, and the ref differs ONLY by its embedded label: that+ // is how desktop builds up to v0.4.28 rename — they rewrite ref.label+ // and never send the column. Follow the rename into the column, or the+ // newer clients (which read the column first) keep showing the old+ // name this rename just replaced.+ //+ // A ref that also changes something else is not a rename however+ // different its label looks: the mode dialog snapshots the ref when it+ // opens, so a rename on another device in the meantime would otherwise+ // be undone by whoever saves an execution mode next.+ if refLabel := localDirectoryRefLabel(nextRef); refLabel != localDirectoryRefLabel(existing.ResourceRef) {+ if refLabel == "" {+ nextLabel = pgtype.Text{}+ labelCleared = true+ } else {+ nextLabel = pgtype.Text{String: refLabel, Valid: true}+ }+ }}nextPosition := existing.Position@@ -578,6 +694,37 @@ func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request)}}+ // Mirror the final label into the ref's legacy copy so both client+ // generations read the same name, including removing it on an explicit+ // clear — otherwise the display falls back to the name the user just+ // deleted. Rows the two-copy era left disagreeing converge on their first+ // write here. A NULL column that was never set stays out of the ref: for+ // rows created by older clients the ref copy IS the name.+ if existing.ResourceType == "local_directory" {+ // The name this request is entitled to write. Only a rename or an+ // explicit label field may change it; anything else keeps whatever the+ // row is called today, wherever that name currently lives — so a stale+ // ref snapshot cannot carry an old name back in behind an unrelated+ // edit.+ name := nextLabel+ if !nextLabel.Valid && !labelCleared {+ if stored := localDirectoryRefLabel(existing.ResourceRef); stored != "" {+ name = pgtype.Text{String: stored, Valid: true}+ }+ }+ // Rows that have never had a name at all are left alone, and so is the+ // ref on updates that do not touch it: an unrelated position change+ // must not rewrite a ref, and for old rows the ref copy IS the name.+ if refProvided || nextLabel.Valid || labelCleared {+ synced, err := withLocalDirectoryRefLabel(nextRef, name)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to update project resource")+ return+ }+ nextRef = synced+ }+ }+updated, err := h.Queries.UpdateProjectResource(r.Context(), db.UpdateProjectResourceParams{ID: existing.ID,ResourceRef: nextRef,diff --git a/server/internal/handler/project_resource_test.go b/server/internal/handler/project_resource_test.goindex f833bb702c..3265409cfb 100644--- a/server/internal/handler/project_resource_test.go+++ b/server/internal/handler/project_resource_test.go@@ -5,6 +5,7 @@ import ("encoding/json""net/http""net/http/httptest"+ "strings""testing""time"@@ -744,7 +745,10 @@ func TestProjectResourceUpdateLifecycle(t *testing.T) {t.Fatalf("decode CreateProjectResource: %v", err)}- // Update only the label; ref/position/type must stay untouched.+ // Update only the label. Path/daemon/type must stay untouched, but the+ // ref's embedded label FOLLOWS the rename: older desktop builds read (and+ // write) only that copy, so leaving it behind would show them the previous+ // name forever (MUL-6323).w = httptest.NewRecorder()req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, map[string]any{"label": "renamed",@@ -765,9 +769,12 @@ func TestProjectResourceUpdateLifecycle(t *testing.T) {if err := json.Unmarshal(updated.ResourceRef, &ref); err != nil {t.Fatalf("decode resource_ref: %v", err)}- if ref.LocalPath != "/Users/foo/work/a" || ref.DaemonID != "d1" || ref.Label != "A" {+ if ref.LocalPath != "/Users/foo/work/a" || ref.DaemonID != "d1" {t.Errorf("label-only update leaked into resource_ref: %+v", ref)}+ if ref.Label != "renamed" {+ t.Errorf("ref label should mirror the rename, got %q", ref.Label)+ }// Update the ref payload (move to a new daemon path) and bump position.w = httptest.NewRecorder()@@ -790,17 +797,29 @@ func TestProjectResourceUpdateLifecycle(t *testing.T) {if err := json.Unmarshal(updated.ResourceRef, &ref); err != nil {t.Fatalf("decode resource_ref: %v", err)}- if ref.LocalPath != "/Users/foo/work/b" || ref.DaemonID != "d2" || ref.Label != "B" {+ if ref.LocalPath != "/Users/foo/work/b" || ref.DaemonID != "d2" {t.Errorf("ref-update mismatch: %+v", ref)}if updated.Position != 5 {t.Errorf("position = %d, want 5", updated.Position)}+ // This request changes the ref's label ("renamed" → "B") AND its path and+ // daemon, so it is not a rename — a client's ref is a snapshot, and only a+ // request whose sole difference is the label can be read as "the user+ // renamed this". The name therefore stays put in both homes, and callers+ // that mean to rename say so with the top-level label field.+ // TestProjectResourceStaleRefSnapshotDoesNotRollBackARename pins why:+ // otherwise an execution-mode dialog opened before someone else's rename+ // undoes it on save. TestProjectResourceLabelConvergence pins the matrix.if updated.Label == nil || *updated.Label != "renamed" {- t.Errorf("label should survive ref edit, got %v", updated.Label)+ t.Errorf("an edit that is not a rename must not change the name, got %v", updated.Label)+ }+ if ref.Label != "renamed" {+ t.Errorf("ref copy should hold the row's current name, got %q", ref.Label)}- // Explicit null clears the outer label.+ // Explicit null clears the outer label — and the ref's copy with it, or+ // the UI would fall back to the very name the user deleted.w = httptest.NewRecorder()req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, map[string]any{"label": nil,@@ -816,6 +835,13 @@ func TestProjectResourceUpdateLifecycle(t *testing.T) {if updated.Label != nil {t.Errorf("label should be cleared, got %v", *updated.Label)}+ var clearedFields map[string]json.RawMessage+ if err := json.Unmarshal(updated.ResourceRef, &clearedFields); err != nil {+ t.Fatalf("decode cleared resource_ref: %v", err)+ }+ if _, hasLabel := clearedFields["label"]; hasLabel {+ t.Errorf("clearing the label must also drop the ref copy, got %s", updated.ResourceRef)+ }// Bad ref payload must reject with 400 (relative path).w = httptest.NewRecorder()@@ -840,6 +866,200 @@ func TestProjectResourceUpdateLifecycle(t *testing.T) {}}+// TestProjectResourceLabelConvergence pins how the server converges the two+// homes a local_directory display name historically has: the top-level label+// column (written by renames since they stopped resending the ref) and the+// legacy copy inside resource_ref (the only home desktop ≤ v0.4.28 knows,+// which those builds both read first and write renames into). The server is+// the only writer that sees both client generations, so every write must+// leave the two agreeing — otherwise each generation edits its own copy and+// the same row shows different names on different devices (MUL-6323).+func TestProjectResourceLabelConvergence(t *testing.T) {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Label convergence project",+ })+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateProject: %d %s", w.Code, w.Body.String())+ }+ var project ProjectResponse+ if err := json.NewDecoder(w.Body).Decode(&project); err != nil {+ t.Fatalf("decode CreateProject: %v", err)+ }+ defer func() {+ r := newRequest("DELETE", "/api/projects/"+project.ID, nil)+ r = withURLParam(r, "id", project.ID)+ testHandler.DeleteProject(httptest.NewRecorder(), r)+ }()++ // Created the way current clients do: name inside the ref, no column.+ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/projects/"+project.ID+"/resources", map[string]any{+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": "/Users/dev/work/game-client",+ "daemon_id": "daemon-label-convergence",+ "label": "Game Client",+ "execution_mode": "in_place",+ },+ })+ req = withURLParam(req, "id", project.ID)+ testHandler.CreateProjectResource(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateProjectResource: %d %s", w.Code, w.Body.String())+ }+ var created ProjectResourceResponse+ if err := json.NewDecoder(w.Body).Decode(&created); err != nil {+ t.Fatalf("decode CreateProjectResource: %v", err)+ }++ update := func(body map[string]any) ProjectResourceResponse {+ t.Helper()+ w := httptest.NewRecorder()+ req := newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, body)+ req = withURLParams(req, "id", project.ID, "resourceId", created.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateProjectResource %v: %d %s", body, w.Code, w.Body.String())+ }+ var resp ProjectResourceResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode UpdateProjectResource: %v", err)+ }+ return resp+ }+ refFields := func(resp ProjectResourceResponse) map[string]json.RawMessage {+ t.Helper()+ var fields map[string]json.RawMessage+ if err := json.Unmarshal(resp.ResourceRef, &fields); err != nil {+ t.Fatalf("decode resource_ref: %v", err)+ }+ return fields+ }+ refString := func(fields map[string]json.RawMessage, key string) string {+ t.Helper()+ rawValue, ok := fields[key]+ if !ok {+ return ""+ }+ var s string+ if err := json.Unmarshal(rawValue, &s); err != nil {+ t.Fatalf("ref[%q] not a string: %s", key, rawValue)+ }+ return s+ }++ // A rename from a desktop ≤ v0.4.28: the whole ref comes back with a new+ // embedded label and no label field. The column must follow, or clients+ // that read the column first keep showing the name this rename replaced.+ resp := update(map[string]any{+ "resource_ref": map[string]any{+ "local_path": "/Users/dev/work/game-client",+ "daemon_id": "daemon-label-convergence",+ "label": "Renamed On Old Desktop",+ "execution_mode": "in_place",+ },+ })+ if resp.Label == nil || *resp.Label != "Renamed On Old Desktop" {+ t.Fatalf("column should follow a legacy ref rename, got %v", resp.Label)+ }++ // Plant what an even newer server may leave in the row: a ref field this+ // binary does not know. Label writes must patch around it, not re-marshal+ // it away — dropping unknown fields on an unrelated edit is the exact+ // failure this PR closes for execution_mode on old servers.+ futureRef := json.RawMessage(`{"local_path":"/Users/dev/work/game-client","daemon_id":"daemon-label-convergence","label":"Renamed On Old Desktop","execution_mode":"in_place","future_field":{"keep":"me"}}`)+ if _, err := testHandler.Queries.UpdateProjectResource(context.Background(), db.UpdateProjectResourceParams{+ ID: parseUUID(created.ID),+ ResourceRef: futureRef,+ Label: pgtype.Text{String: "Renamed On Old Desktop", Valid: true},+ Position: 0,+ }); err != nil {+ t.Fatalf("plant future ref: %v", err)+ }++ // A rename from a current client: label only, no ref. The ref's embedded+ // copy must follow so ≤ v0.4.28 readers see the new name — with the mode+ // and the unknown field untouched.+ resp = update(map[string]any{"label": "Renamed On New Desktop"})+ if resp.Label == nil || *resp.Label != "Renamed On New Desktop" {+ t.Fatalf("label-only rename: column = %v", resp.Label)+ }+ fields := refFields(resp)+ if got := refString(fields, "label"); got != "Renamed On New Desktop" {+ t.Errorf("ref label should mirror the rename for legacy readers, got %q", got)+ }+ if got := refString(fields, "execution_mode"); got != "in_place" {+ t.Errorf("rename must not touch execution_mode, got %q", got)+ }+ if string(fields["future_field"]) != `{"keep":"me"}` {+ t.Errorf("rename must preserve unknown ref fields and their values, got %s", fields["future_field"])+ }++ // A ref resent with its embedded label UNCHANGED — the execution-mode+ // dialog spreads the stored ref back — is not a rename. It must not+ // overwrite a column rename... but this write may converge the ref copy+ // onto the column. (The resend goes through ref normalization, so this is+ // also where future_field legitimately disappears on THIS server: that is+ // the documented normalize contract for provided refs, not label code.)+ if _, err := testHandler.Queries.UpdateProjectResource(context.Background(), db.UpdateProjectResourceParams{+ ID: parseUUID(created.ID),+ ResourceRef: json.RawMessage(`{"local_path":"/Users/dev/work/game-client","daemon_id":"daemon-label-convergence","label":"Stale Ref Copy","execution_mode":"in_place"}`),+ Label: pgtype.Text{String: "Column Rename", Valid: true},+ Position: 0,+ }); err != nil {+ t.Fatalf("plant diverged row: %v", err)+ }+ resp = update(map[string]any{+ "resource_ref": map[string]any{+ "local_path": "/Users/dev/work/game-client",+ "daemon_id": "daemon-label-convergence",+ "label": "Stale Ref Copy",+ "execution_mode": "in_place",+ },+ })+ if resp.Label == nil || *resp.Label != "Column Rename" {+ t.Fatalf("unchanged ref label must not overwrite a column rename, got %v", resp.Label)+ }+ if got := refString(refFields(resp), "label"); got != "Column Rename" {+ t.Errorf("diverged ref copy should heal onto the column, got %q", got)+ }++ // Clearing the name removes BOTH copies: with either one left behind the+ // UI would resurrect the name the user just deleted.+ resp = update(map[string]any{"label": ""})+ if resp.Label != nil {+ t.Fatalf("clear: column = %v", *resp.Label)+ }+ fields = refFields(resp)+ if _, hasLabel := fields["label"]; hasLabel {+ t.Errorf("clear must drop the ref copy too, got %s", resp.ResourceRef)+ }+ if got := refString(fields, "execution_mode"); got != "in_place" {+ t.Errorf("clear must not touch execution_mode, got %q", got)+ }++ // A write that decides no label — position only — must leave the name of+ // a row whose only copy lives in the ref alone: NULL column here means+ // "never set", not "cleared".+ if _, err := testHandler.Queries.UpdateProjectResource(context.Background(), db.UpdateProjectResourceParams{+ ID: parseUUID(created.ID),+ ResourceRef: json.RawMessage(`{"local_path":"/Users/dev/work/game-client","daemon_id":"daemon-label-convergence","label":"Ref Only Name","execution_mode":"in_place"}`),+ Label: pgtype.Text{},+ Position: 0,+ }); err != nil {+ t.Fatalf("plant legacy row: %v", err)+ }+ resp = update(map[string]any{"position": 3})+ if got := refString(refFields(resp), "label"); got != "Ref Only Name" {+ t.Errorf("position-only update must not strip a ref-only name, got %q", got)+ }+ if resp.Label != nil {+ t.Errorf("position-only update invented a column label: %v", *resp.Label)+ }+}+// TestProjectResourceLocalDirectoryDaemonScopedConflict pins the project-level// conflict check for local_directory: one row per daemon per project. The// daemon-side resolver picks the first match by daemon_id, so silently@@ -1239,3 +1459,241 @@ func TestLatestDaemonCLIVersion(t *testing.T) {})}}++// The bundled create path (project + resources in one transaction) skipped the+// worktree save gate that POST/PUT /resources have always run, so a project+// could be created with a mode the machine cannot run — surfacing only later,+// as the claim gate cancelling the task.+//+// It matters more now that the client no longer predicts this answer: the UI+// leaves parallel mode selectable and lets the server rule on it (#7113), which+// only works if every write path actually asks.+func TestCreateProjectGatesWorktreeLocalDirectory(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Bundled worktree resource",+ "resources": []map[string]any{+ {+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": "/Users/dev/work/game-client",+ "daemon_id": "daemon-with-no-runtime-row",+ "execution_mode": "worktree",+ },+ },+ },+ })+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusUnprocessableEntity {+ t.Fatalf("CreateProject with un-runnable worktree resource: expected 422, got %d: %s",+ w.Code, w.Body.String())+ }+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["code"] != "daemon_version_unsupported" {+ t.Fatalf("expected the shared gate's error code, got %#v", resp["code"])+ }++ // The gate runs before the transaction opens, so the rejection must not+ // leave a half-created project behind.+ lw := httptest.NewRecorder()+ lreq := newRequest("GET", "/api/projects?workspace_id="+testWorkspaceID, nil)+ testHandler.ListProjects(lw, lreq)+ if strings.Contains(lw.Body.String(), "Bundled worktree resource") {+ t.Fatal("rejected create left a project behind")+ }+}++// createTestProjectForResources / createLocalDirectoryResourceFor build the+// fixtures the label-classification tests share, through the real handlers so+// the rows look exactly like a client's would.+func createTestProjectForResources(t *testing.T, title string) ProjectResponse {+ t.Helper()+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{"title": title})+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateProject: %d %s", w.Code, w.Body.String())+ }+ var project ProjectResponse+ if err := json.NewDecoder(w.Body).Decode(&project); err != nil {+ t.Fatalf("decode CreateProject: %v", err)+ }+ t.Cleanup(func() {+ r := newRequest("DELETE", "/api/projects/"+project.ID, nil)+ r = withURLParam(r, "id", project.ID)+ testHandler.DeleteProject(httptest.NewRecorder(), r)+ })+ return project+}++func createLocalDirectoryResourceFor(t *testing.T, projectID string, ref map[string]any) ProjectResourceResponse {+ t.Helper()+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects/"+projectID+"/resources", map[string]any{+ "resource_type": "local_directory",+ "resource_ref": ref,+ })+ req = withURLParam(req, "id", projectID)+ testHandler.CreateProjectResource(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateProjectResource: %d %s", w.Code, w.Body.String())+ }+ var created ProjectResourceResponse+ if err := json.NewDecoder(w.Body).Decode(&created); err != nil {+ t.Fatalf("decode CreateProjectResource: %v", err)+ }+ return created+}++// A resource's execution-mode dialog snapshots the whole ref when it OPENS, and+// sends it back on save. If someone renames the folder from another device in+// between, that snapshot arrives carrying a label the row no longer has — and+// reading "the ref label differs" as "an old client renamed it" would undo the+// rename, from a dialog that has nothing to do with the name.+//+// Also pins the other half of the same classification: an old client's rename+// resends the ref but changes no execution semantics, so it must not be refused+// by the worktree capability gate for a machine whose registration has drifted.+func TestProjectResourceStaleRefSnapshotDoesNotRollBackARename(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ project := createTestProjectForResources(t, "Stale mode snapshot")+ const daemonID = "daemon-stale-snapshot"++ // The row as both devices last saw it: named "Game Client", in_place.+ created := createLocalDirectoryResourceFor(t, project.ID, map[string]any{+ "local_path": "/Users/dev/work/game-client",+ "daemon_id": daemonID,+ "label": "Game Client",+ })++ update := func(body map[string]any) ProjectResourceResponse {+ t.Helper()+ w := httptest.NewRecorder()+ req := newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, body)+ req = withURLParams(req, "id", project.ID, "resourceId", created.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateProjectResource(%v): %d %s", body, w.Code, w.Body.String())+ }+ var resp ProjectResourceResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ return resp+ }+ refLabelOf := func(resp ProjectResourceResponse) string {+ t.Helper()+ var fields map[string]any+ if err := json.Unmarshal(resp.ResourceRef, &fields); err != nil {+ t.Fatalf("decode ref: %v", err)+ }+ label, _ := fields["label"].(string)+ return label+ }++ // Device B renames it. Both homes of the name now say "Renamed Client".+ renamed := update(map[string]any{"label": "Renamed Client"})+ if refLabelOf(renamed) != "Renamed Client" {+ t.Fatalf("setup: ref copy did not follow the rename: %s", renamed.ResourceRef)+ }++ // Device A, whose dialog opened before that, saves in_place → in_place with+ // its stale snapshot. The mode is what it came to change; the name is not.+ after := update(map[string]any{+ "resource_ref": map[string]any{+ "local_path": "/Users/dev/work/game-client",+ "daemon_id": daemonID,+ "label": "Game Client",+ "execution_mode": "in_place",+ },+ })+ if after.Label == nil || *after.Label != "Renamed Client" {+ t.Fatalf("a stale mode snapshot rolled back the rename: column = %v", after.Label)+ }+ if got := refLabelOf(after); got != "Renamed Client" {+ t.Errorf("stale ref label should be healed to the current name, got %q", got)+ }++ // A genuine ≤ v0.4.28 rename — ref resent, ONLY the label different — still+ // counts, and still reaches the column.+ legacy := update(map[string]any{+ "resource_ref": map[string]any{+ "local_path": "/Users/dev/work/game-client",+ "daemon_id": daemonID,+ "label": "Renamed On Old Desktop",+ "execution_mode": "in_place",+ },+ })+ if legacy.Label == nil || *legacy.Label != "Renamed On Old Desktop" {+ t.Fatalf("legacy rename should still reach the column, got %v", legacy.Label)+ }+}++// An old client renames by resending the ref, so the worktree capability gate+// would see "the ref was provided" and refuse the rename on a machine whose+// runtime registration no longer advertises the capability — failing an edit+// that changes nothing about what runs. The row already says worktree; the+// claim gate is what keeps it from running somewhere that cannot.+func TestProjectResourceLegacyRenameSkipsWorktreeGate(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ project := createTestProjectForResources(t, "Legacy rename on a worktree row")+ const daemonID = "daemon-no-runtime-row-for-rename"++ created := createLocalDirectoryResourceFor(t, project.ID, map[string]any{+ "local_path": "/Users/dev/work/game-client",+ "daemon_id": daemonID,+ "label": "Game Client",+ })+ // Plant the worktree mode directly: saving it through the API would (+ // correctly) be refused for a daemon with no capable runtime row.+ if _, err := testHandler.Queries.UpdateProjectResource(context.Background(), db.UpdateProjectResourceParams{+ ID: parseUUID(created.ID),+ ResourceRef: json.RawMessage(`{"local_path":"/Users/dev/work/game-client","daemon_id":"` + daemonID + `","label":"Game Client","execution_mode":"worktree"}`),+ Label: pgtype.Text{String: "Game Client", Valid: true},+ Position: 0,+ }); err != nil {+ t.Fatalf("plant worktree row: %v", err)+ }++ w := httptest.NewRecorder()+ req := newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, map[string]any{+ "resource_ref": map[string]any{+ "local_path": "/Users/dev/work/game-client",+ "daemon_id": daemonID,+ "label": "Renamed On Old Desktop",+ "execution_mode": "worktree",+ },+ })+ req = withURLParams(req, "id", project.ID, "resourceId", created.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("a rename that changes no execution semantics must not hit the capability gate: %d %s",+ w.Code, w.Body.String())+ }++ // And the gate still fires when the same client actually changes the mode.+ w = httptest.NewRecorder()+ req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, map[string]any{+ "resource_ref": map[string]any{+ "local_path": "/Users/dev/work/game-client",+ "daemon_id": daemonID,+ "label": "Renamed On Old Desktop",+ "execution_mode": "in_place",+ },+ })+ req = withURLParams(req, "id", project.ID, "resourceId", created.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("switching to in_place needs no capability: %d %s", w.Code, w.Body.String())+ }+}diff --git a/server/pkg/agent/worktree_capability_contract_test.go b/server/pkg/agent/worktree_capability_contract_test.gonew file mode 100644index 0000000000..2609852738--- /dev/null+++ b/server/pkg/agent/worktree_capability_contract_test.go@@ -0,0 +1,39 @@+package agent++import (+ "os"+ "path/filepath"+ "regexp"+ "testing"++ "github.com/multica-ai/multica/server/pkg/protocol"+)++// What the two sides must agree on is the capability TOKEN, not a version.+//+// This replaces a test that pinned MinLocalWorktreeCLIVersion against a+// frontend twin. That twin is gone: since MUL-5707 nothing on either side gates+// on the version, and the frontend no longer even quotes it (#7113), so the old+// contract was pinning a number the UI does not show. The server constant stays+// because the 422 payload still carries it, but it has no counterpart to match.+//+// The token does have one, and it is load-bearing in a way a version never was:+// the daemon advertises this exact string, the server stores it, and the UI+// looks for it. A typo on either side silently disables worktree mode for+// everyone, with no error anywhere — which is precisely the failure this whole+// area keeps producing.+func TestWorktreeCapabilityTokenMatchesFrontend(t *testing.T) {+ path := filepath.Join("..", "..", "..", "packages", "core", "runtimes", "cli-version.ts")+ src, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ m := regexp.MustCompile(`LOCAL_WORKTREE_CAPABILITY\s*=\s*"([^"]+)"`).FindSubmatch(src)+ if m == nil {+ t.Fatal("LOCAL_WORKTREE_CAPABILITY not found in packages/core/runtimes/cli-version.ts")+ }+ if got := string(m[1]); got != protocol.DaemonCapabilityLocalWorktreeV1 {+ t.Errorf("frontend looks for %q but the daemon advertises %q; worktree mode would be invisible to the UI",+ got, protocol.DaemonCapabilityLocalWorktreeV1)+ }+}diff --git a/server/pkg/agent/worktree_version_floor_test.go b/server/pkg/agent/worktree_version_floor_test.godeleted file mode 100644index dfc1388394..0000000000--- a/server/pkg/agent/worktree_version_floor_test.go+++ /dev/null@@ -1,28 +0,0 @@-package agent--import (- "os"- "path/filepath"- "regexp"- "testing"-)--// The worktree floor is no longer a gate — the capability is (MUL-5707). It-// survives as the version number shown to the user in the 422 payload and the-// UI hint, and those two must still quote the same release: telling someone to-// update to 0.4.24 in one place and 0.4.30 in another is its own bug.-func TestWorktreeCLIVersionFloorMatchesFrontend(t *testing.T) {- path := filepath.Join("..", "..", "..", "packages", "core", "runtimes", "cli-version.ts")- src, err := os.ReadFile(path)- if err != nil {- t.Fatalf("read %s: %v", path, err)- }- m := regexp.MustCompile(`MIN_LOCAL_WORKTREE_CLI_VERSION\s*=\s*"([^"]+)"`).FindSubmatch(src)- if m == nil {- t.Fatal("MIN_LOCAL_WORKTREE_CLI_VERSION not found in packages/core/runtimes/cli-version.ts")- }- if got := string(m[1]); got != MinLocalWorktreeCLIVersion {- t.Errorf("frontend shows %s but the server's 422 quotes %s; the update hint must name one release",- got, MinLocalWorktreeCLIVersion)- }-}