Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(projects): set a repository's checkout ref from the UI (MUL-7504) (#8592)
Bohan Jiang9018df3efb0b
diff --git a/apps/mobile/app/(app)/[workspace]/project/[id]/add-resource.tsx b/apps/mobile/app/(app)/[workspace]/project/[id]/add-resource.tsxindex 3a6f96313a..c447a62a1e 100644--- a/apps/mobile/app/(app)/[workspace]/project/[id]/add-resource.tsx+++ b/apps/mobile/app/(app)/[workspace]/project/[id]/add-resource.tsx@@ -6,10 +6,22 @@* v1 only supports `github_repo` resource type. Loose client-side* validation: URL must look like `https://github.com/owner/repo`. Server* is the canonical validator (validateAndNormalizeResourceRef in Go).+ *+ * The optional branch is where this project's tasks START and where they open+ * their pull requests — empty means the repository's default branch, and a+ * task that passes its own ref still wins. Parity with the web/desktop attach+ * form in packages/views/projects/components/project-resources-section.tsx,+ * including declining a full-length commit id: a commit has no branch to+ * deliver back to, so one-off revisions belong on `repo checkout --ref`.*/import { useCallback, useState } from "react";import { Alert, Pressable, View } from "react-native";import { useLocalSearchParams, router } from "expo-router";+import {+ looksLikeCommitSha,+ splitGithubUrlRef,+ validateGitRef,+} from "@multica/core/github";import { Text } from "@/components/ui/text";import { TextField } from "@/components/ui/text-field";import { useCreateProjectResource } from "@/data/mutations/projects";@@ -21,17 +33,38 @@ export default function AddResourceRoute() {const createResource = useCreateProjectResource(id);const [url, setUrl] = useState("");+ const [ref, setRef] = useState("");const [label, setLabel] = useState("");- const valid = GITHUB_PATTERN.test(url.trim());+ // Someone who wants a branch copies it out of the address bar, and+ // GITHUB_PATTERN accepts the whole `.../tree/<branch>` string — which used to+ // be stored as the clone URL, a target that does not exist. Split it into the+ // two visible fields instead, so a wrong guess is correctable before saving.+ //+ // Normalising the URL is unconditional: gating it on the branch field being+ // empty meant a second pasted browse URL was stored whole. Whether to+ // overwrite the branch is the separate question, and the pasted pair wins.+ const onUrlChange = useCallback((next: string) => {+ const split = splitGithubUrlRef(next);+ setUrl(split.url);+ if (split.ref) setRef(split.ref);+ }, []);++ const refMessage = refErrorMessage(ref);+ const valid = GITHUB_PATTERN.test(url.trim()) && refMessage === null;const submitting = createResource.isPending;const onSubmit = useCallback(() => {if (!valid || submitting) return;+ const trimmedRef = ref.trim();createResource.mutate({resource_type: "github_repo",- resource_ref: { url: url.trim() },+ // Omit the key entirely when empty: an absent ref is what "use the+ // default branch" looks like on the wire.+ resource_ref: trimmedRef+ ? { url: url.trim(), ref: trimmedRef }+ : { url: url.trim() },label: label.trim() || undefined,},{@@ -44,7 +77,7 @@ export default function AddResourceRoute() {},},);- }, [valid, submitting, createResource, url, label]);+ }, [valid, submitting, createResource, url, ref, label]);return (<View className="flex-1">@@ -70,7 +103,7 @@ export default function AddResourceRoute() {<Text className="text-xs text-muted-foreground">Repository URL</Text><TextFieldvalue={url}- onChangeText={setUrl}+ onChangeText={onUrlChange}placeholder="https://github.com/owner/repo"autoCapitalize="none"autoCorrect={false}@@ -78,6 +111,24 @@ export default function AddResourceRoute() {autoFocus/></View>+ <View className="gap-1">+ <Text className="text-xs text-muted-foreground">+ Starting branch (optional)+ </Text>+ <TextField+ value={ref}+ onChangeText={setRef}+ placeholder="main"+ autoCapitalize="none"+ autoCorrect={false}+ />+ <Text+ className={`text-xs ${refMessage === null ? "text-muted-foreground" : "text-destructive"}`}+ >+ {refMessage ??+ "Tasks start from this branch and open their pull requests against it. Leave empty to use the repository's default branch."}+ </Text>+ </View><View className="gap-1"><Text className="text-xs text-muted-foreground">Label (optional)@@ -92,3 +143,27 @@ export default function AddResourceRoute() {</View>);}++/**+ * The message to show under the branch field, or null when it is acceptable.+ *+ * Mirrors refErrorMessage in+ * packages/views/projects/components/github-ref-field.tsx. The commit check+ * runs first on purpose: a commit id is a perfectly valid ref to store — what+ * makes it wrong here is that this field names a branch to deliver back to.+ */+function refErrorMessage(value: string): string | null {+ if (looksLikeCommitSha(value)) {+ return "That's a commit, not a branch. Tasks deliver back to the branch they start from — for a one-off revision, pass --ref to multica repo checkout.";+ }+ const validation = validateGitRef(value);+ if (validation.ok) return null;+ switch (validation.reason) {+ case "too_long":+ return "Use at most 255 characters.";+ case "invalid_characters":+ return "A branch name can't contain spaces or any of ~ ^ : ? * [ \\";+ default:+ return "Not a valid branch name.";+ }+}diff --git a/apps/mobile/components/project/project-resources-section.tsx b/apps/mobile/components/project/project-resources-section.tsxindex ac171b6ab8..1f53a1276d 100644--- a/apps/mobile/components/project/project-resources-section.tsx+++ b/apps/mobile/components/project/project-resources-section.tsx@@ -123,6 +123,21 @@ function ResourceRow({{describeResource(resource)}</Text>) : null}+ {/* Its own line rather than appended to the URL: a custom label already+ takes the first slot, and this is the one project setting that+ silently changes what every task starts from. */}+ {checkoutRefOf(resource) ? (+ <View className="flex-row items-center gap-1">+ <Ionicons+ name="git-branch-outline"+ size={11}+ color={THEME[colorScheme].mutedForeground}+ />+ <Text className="text-xs text-muted-foreground" numberOfLines={1}>+ {checkoutRefOf(resource)}+ </Text>+ </View>+ ) : null}</View></Pressable>);@@ -146,3 +161,18 @@ function getResourceUrl(resource: ProjectResource): string | null {function describeResource(resource: ProjectResource): string {return getResourceUrl(resource) ?? resource.resource_type;}++/**+ * The repo's pinned checkout ref, or null when tasks use the default branch.+ *+ * Matches the web/desktop badge in+ * packages/views/projects/components/project-resources-section.tsx — a ref set+ * on any client has to be visible on every client, or the two disagree about+ * what the project is configured to do.+ */+function checkoutRefOf(resource: ProjectResource): string | null {+ if (resource.resource_type !== "github_repo") return null;+ const ref = resource.resource_ref as GithubRepoResourceRef | undefined;+ const value = ref?.ref?.trim();+ return value ? value : null;+}diff --git a/e2e/project-resource-ref.spec.ts b/e2e/project-resource-ref.spec.tsnew file mode 100644index 0000000000..da903e2fe6--- /dev/null+++ b/e2e/project-resource-ref.spec.ts@@ -0,0 +1,62 @@+import { test, expect } from "@playwright/test";+import { loginAsDefault, waitForPageText } from "./helpers";++const REPO = "https://github.com/multica-ai/multica";++/**+ * The checkout ref of a github_repo project resource, end to end.+ *+ * Covers what only the full stack can show: the ref survives project creation,+ * comes back on the project page, and an edit persists — the server replaces+ * resource_ref wholesale rather than deep-merging, so a payload that drops the+ * URL is a class of bug the component tests alone cannot see.+ */+test("pins, edits and clears a repository's checkout ref", async ({ page }) => {+ const slug = await loginAsDefault(page);++ await page.goto(`/${slug}/projects`, { waitUntil: "domcontentloaded" });+ await waitForPageText(page, "Projects");+ await page.getByRole("button", { name: /new project/i }).first().click();++ // TitleEditor is a contenteditable, not an <input> with a placeholder attr.+ await page.getByRole("textbox", { name: /project title/i }).fill("Release line");+ await page.getByRole("button", { name: /repos/i }).first().click();+ await page.getByPlaceholder(/github\.com\/owner\/repo/i).fill(REPO);+ await page.getByLabel(/starting branch/i).fill("release/2026-09");+ await page.getByRole("button", { name: /^add$/i }).click();+ await page.getByRole("button", { name: /^create project$/i }).click();++ await waitForPageText(page, "Release line");+ await expect(page.getByText("release/2026-09")).toBeVisible({ timeout: 15000 });++ // Editing an attached resource — the affordance the UI never had.+ await page.getByTitle(/change the branch tasks work on/i).first().click();+ await expect(page.getByText(/which branch should tasks work on/i)).toBeVisible();++ // A ref git could not resolve is refused before it is stored, rather than+ // failing minutes later inside a task with a repo-cache error.+ await page.getByLabel(/starting branch/i).fill("main..dev");+ await expect(page.getByRole("button", { name: /^save$/i })).toBeDisabled();++ await page.getByLabel(/starting branch/i).fill("v1.4.0");+ await page.getByRole("button", { name: /^save$/i }).click();+ await expect(page.getByText("v1.4.0")).toBeVisible({ timeout: 10000 });+ await expect(page.getByText("release/2026-09")).toHaveCount(0);++ // The saved value survives a reload — i.e. it reached the database, and the+ // URL rode along with it rather than being replaced away.+ await page.reload({ waitUntil: "domcontentloaded" });+ await expect(page.getByText("v1.4.0")).toBeVisible({ timeout: 15000 });+ await expect(page.getByText("multica-ai/multica")).toBeVisible();++ // Clearing goes back to the repository's default branch.+ await page.getByTitle(/change the branch tasks work on/i).first().click();+ await page.getByLabel(/starting branch/i).fill("");+ await page.getByRole("button", { name: /^save$/i }).click();+ await expect(page.getByText("v1.4.0")).toHaveCount(0, { timeout: 10000 });+ await expect(page.getByText("multica-ai/multica")).toBeVisible();+ // Not an empty row: an unpinned repo says which branch it uses, so clearing+ // is confirmable rather than indistinguishable from the setting not existing.+ // Exact text, because the success toast also says "Back to the default branch".+ await expect(page.getByText("Default branch", { exact: true })).toBeVisible();+});diff --git a/packages/core/github/index.ts b/packages/core/github/index.tsindex 5602216d05..387a5f39ab 100644--- a/packages/core/github/index.ts+++ b/packages/core/github/index.ts@@ -2,3 +2,4 @@ export * from "./queries";export * from "./pull-request-status";export * from "./settings";export * from "./use-github-settings";+export * from "./repo-ref";diff --git a/packages/core/github/repo-ref.test.ts b/packages/core/github/repo-ref.test.tsnew file mode 100644index 0000000000..a8b9d904e1--- /dev/null+++ b/packages/core/github/repo-ref.test.ts@@ -0,0 +1,150 @@+// @vitest-environment node+import { describe, it, expect } from "vitest";+import {+ GIT_REF_MAX_LENGTH,+ looksLikeCommitSha,+ splitGithubUrlRef,+ validateGitRef,+} from "./repo-ref";++describe("validateGitRef", () => {+ it("accepts an empty ref as 'use the default branch'", () => {+ expect(validateGitRef("")).toEqual({ ok: true });+ expect(validateGitRef(" ")).toEqual({ ok: true });+ });++ it.each([+ ["a plain branch", "main"],+ ["a slashed branch", "release/2026-09"],+ ["a deeply slashed branch", "team/alice/feat/new-thing"],+ ["a semver tag", "v1.2.3"],+ ["a short SHA", "a1b2c3d"],+ ["a full SHA", "5e0b1cfa0a7d6a1a0f4b3f2e1d0c9b8a7f6e5d4c"],+ ["a branch with dots inside", "release.2026.09"],+ ["a branch with a hyphenated tail", "fix/MUL-7504-pin-ref"],+ ])("accepts %s", (_label, ref) => {+ expect(validateGitRef(ref)).toEqual({ ok: true });+ });++ it.each([+ ["a space", "my branch"],+ ["a tilde", "main~1"],+ ["a caret", "main^"],+ ["a colon", "origin:main"],+ ["a question mark", "main?"],+ ["an asterisk", "refs/heads/*"],+ ["a backslash", "feat\\thing"],+ ["an interior control character", "ma\nin"],+ ])("rejects %s", (_label, ref) => {+ expect(validateGitRef(ref)).toEqual({ ok: false, reason: "invalid_characters" });+ });++ it.each([+ ["a range", "main..dev"],+ ["reflog syntax", "main@{1}"],+ ["a lone at-sign", "@"],+ ["a leading slash", "/main"],+ ["a trailing slash", "main/"],+ ["a doubled slash", "feat//thing"],+ ["a leading dot", ".hidden"],+ ["a trailing dot", "main."],+ ["a lock suffix", "main.lock"],+ ["a lock suffix on an inner segment", "feat.lock/thing"],+ ["a dot-prefixed inner segment", "feat/.hidden"],+ ])("rejects %s", (_label, ref) => {+ expect(validateGitRef(ref)).toEqual({ ok: false, reason: "invalid_format" });+ });++ it("rejects a ref past the length cap but accepts one exactly at it", () => {+ expect(validateGitRef("a".repeat(GIT_REF_MAX_LENGTH))).toEqual({ ok: true });+ expect(validateGitRef("a".repeat(GIT_REF_MAX_LENGTH + 1))).toEqual({+ ok: false,+ reason: "too_long",+ });+ });+});++describe("splitGithubUrlRef", () => {+ it("splits a browse URL into clone URL and ref", () => {+ expect(splitGithubUrlRef("https://github.com/multica-ai/multica/tree/main")).toEqual({+ url: "https://github.com/multica-ai/multica",+ ref: "main",+ });+ });++ it("keeps a multi-segment branch together", () => {+ expect(+ splitGithubUrlRef("https://github.com/multica-ai/multica/tree/release/2026-09"),+ ).toEqual({+ url: "https://github.com/multica-ai/multica",+ ref: "release/2026-09",+ });+ });++ it("drops a .git suffix before /tree and a trailing slash after the ref", () => {+ expect(+ splitGithubUrlRef("https://github.com/multica-ai/multica.git/tree/main/"),+ ).toEqual({ url: "https://github.com/multica-ai/multica", ref: "main" });+ });++ it("leaves a plain clone URL untouched", () => {+ for (const url of [+ "https://github.com/multica-ai/multica",+ "https://github.com/multica-ai/multica.git",+ "[email protected]:multica-ai/multica.git",+ "https://gitlab.com/owner/repo/tree/main",+ ]) {+ expect(splitGithubUrlRef(url)).toEqual({ url });+ }+ });++ it("leaves /blob and /pull URLs alone — neither names a checkout baseline", () => {+ const blob = "https://github.com/multica-ai/multica/blob/main/README.md";+ const pull = "https://github.com/multica-ai/multica/pull/8572";+ expect(splitGithubUrlRef(blob)).toEqual({ url: blob });+ expect(splitGithubUrlRef(pull)).toEqual({ url: pull });+ });++ it("does not split when the extracted ref would be invalid", () => {+ const url = "https://github.com/multica-ai/multica/tree/main..dev";+ expect(splitGithubUrlRef(url)).toEqual({ url });+ });++ it("trims surrounding whitespace from a pasted URL", () => {+ expect(splitGithubUrlRef(" https://github.com/o/r/tree/dev ")).toEqual({+ url: "https://github.com/o/r",+ ref: "dev",+ });+ });+});++describe("looksLikeCommitSha", () => {+ it("recognises full-length object ids", () => {+ expect(looksLikeCommitSha("5e0b1cfa0a7d6a1a0f4b3f2e1d0c9b8a7f6e5d4c")).toBe(true);+ expect(looksLikeCommitSha("5E0B1CFA0A7D6A1A0F4B3F2E1D0C9B8A7F6E5D4C")).toBe(true);+ expect(looksLikeCommitSha("a".repeat(64))).toBe(true);+ expect(looksLikeCommitSha(" " + "b".repeat(40) + " ")).toBe(true);+ });++ it("leaves anything that could plausibly be a branch alone", () => {+ for (const value of [+ "main",+ "release/2026-09",+ "v1.2.3",+ "a1b2c3d", // a short SHA is also a legal branch name — not our call to make+ "deadbeef",+ "a".repeat(39),+ "a".repeat(41),+ "g".repeat(40), // not hex+ "",+ ]) {+ expect(looksLikeCommitSha(value)).toBe(false);+ }+ });++ it("is independent of validateGitRef — a SHA is still a valid ref to store", () => {+ const sha = "5e0b1cfa0a7d6a1a0f4b3f2e1d0c9b8a7f6e5d4c";+ expect(validateGitRef(sha)).toEqual({ ok: true });+ expect(looksLikeCommitSha(sha)).toBe(true);+ });+});diff --git a/packages/core/github/repo-ref.ts b/packages/core/github/repo-ref.tsnew file mode 100644index 0000000000..f8726c03b2--- /dev/null+++ b/packages/core/github/repo-ref.ts@@ -0,0 +1,126 @@+/**+ * Checkout-ref helpers for `github_repo` project resources.+ *+ * The ref pins where a project's tasks START — `multica repo checkout` falls+ * back to the remote default branch when it is empty, and an explicit+ * `--ref` on the command line still wins over it. It is not a promise that+ * work lands on that branch, and it does not retarget pull requests.+ *+ * Lives in core (not views) because the mobile app needs the same rules and+ * cannot import from the web-only package.+ */++/**+ * Git's own limit is the filesystem's, but a loose ref path has to fit in a+ * file name. 255 is the conservative ceiling every platform honors, and it is+ * far past any real branch name — the cap exists to stop a paste of an entire+ * document from reaching the database, not to police naming.+ */+export const GIT_REF_MAX_LENGTH = 255;++export type GitRefInvalidReason =+ | "too_long"+ | "invalid_characters"+ | "invalid_format";++export type GitRefValidation =+ | { ok: true }+ | { ok: false; reason: GitRefInvalidReason };++/**+ * Reject input git itself could never resolve, and nothing more.+ *+ * Mirrors the subset of `git check-ref-format` that applies to a ref a user+ * types: it must accept every branch, tag and commit SHA we advertise, so the+ * rules here are about SHAPE only. Whether the ref exists on the remote is a+ * different question answered at checkout time — the daemon may be offline and+ * the repository may be private, so existence must never gate saving config.+ *+ * An empty ref is valid: it means "use the repository's default branch".+ */+export function validateGitRef(ref: string): GitRefValidation {+ const value = ref.trim();+ if (value === "") return { ok: true };+ if (value.length > GIT_REF_MAX_LENGTH) return { ok: false, reason: "too_long" };++ // ASCII control characters, DEL, space, and the characters git reserves for+ // its own revision syntax. Scanned by code point rather than matched with a+ // regex so the control range stays readable (and lintable) as a comparison.+ const RESERVED = "~^:?*[\\";+ for (const char of value) {+ const code = char.codePointAt(0)!;+ if (code <= 0x20 || code === 0x7f || RESERVED.includes(char)) {+ return { ok: false, reason: "invalid_characters" };+ }+ }++ // Path-shape rules. `@{` is reflog syntax; a lone `@` is shorthand for HEAD;+ // `..` would read as a range; `.lock` is what git names its lock files.+ if (+ value.includes("..") ||+ value.includes("@{") ||+ value === "@" ||+ value.startsWith("/") ||+ value.endsWith("/") ||+ value.includes("//") ||+ value.startsWith(".") ||+ value.endsWith(".") ||+ value.endsWith(".lock") ||+ value.split("/").some((segment) => segment.startsWith(".") || segment.endsWith(".lock"))+ ) {+ return { ok: false, reason: "invalid_format" };+ }++ return { ok: true };+}++/**+ * True when the value can only be a commit SHA, never a branch name.+ *+ * Git cannot tell a branch from a tag from a commit by looking at the string —+ * `v1.2.3` is a legal branch name and `main` is a legal tag — and answering+ * properly means asking the remote, which the product deliberately does not do.+ * A full-length hex object id is the one exception: it is unambiguous, and it+ * is what someone pastes when they mean "this exact commit".+ *+ * That matters because a pinned starting point is also the branch a task+ * delivers back to, and a commit has nothing to merge into. So the UI, which+ * asks for a branch, declines this one shape and points at the per-task+ * `--ref` escape hatch instead. The stored grammar (validateGitRef, mirrored+ * server-side) stays permissive: the CLI and API still accept tags and commits,+ * because the daemon resolves all three and always has.+ */+export function looksLikeCommitSha(value: string): boolean {+ const trimmed = value.trim();+ // SHA-1 object ids are 40 hex chars; git's SHA-256 transition uses 64.+ return /^[0-9a-f]{40}$|^[0-9a-f]{64}$/i.test(trimmed);+}++/**+ * Split a pasted GitHub "browse" URL into the clone URL plus the ref it points at.+ *+ * Someone who wants a branch reaches for the URL bar first, and+ * `https://github.com/owner/repo/tree/release/2026-09` is what they copy. Left+ * alone that whole string was stored as the repository URL — a clone target+ * that does not exist. Splitting it is what the user meant.+ *+ * Only `/tree/<ref>` is recognised: `/blob/…` and `/pull/…` point at a file or+ * a PR rather than a checkout baseline, so those are left untouched for the+ * URL validator to reject or accept on its own terms.+ *+ * A multi-segment ref (`release/2026-09`) is rejoined — GitHub's own URLs are+ * ambiguous between `feat/x` the branch and `feat` the branch plus `x` the+ * directory, and the branch reading is the useful one here. A wrong guess is+ * visible and editable in the field before it is saved.+ */+export function splitGithubUrlRef(input: string): { url: string; ref?: string } {+ const value = input.trim();+ const match = value.match(+ /^(https?:\/\/(?:www\.)?github\.com\/[^/\s]+\/[^/\s]+?)(?:\.git)?\/tree\/(.+)$/i,+ );+ const [, cloneUrl, rawRef] = match ?? [];+ if (!cloneUrl || !rawRef) return { url: value };+ const ref = rawRef.replace(/\/+$/, "");+ if (!ref || validateGitRef(ref).ok === false) return { url: value };+ return { url: cloneUrl, ref };+}diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.jsonindex 1272896430..022cd3e1b7 100644--- a/packages/views/locales/en/modals.json+++ b/packages/views/locales/en/modals.json@@ -137,7 +137,8 @@"local_clear": "Clear","local_pick_failed": "Could not open the directory picker.","local_invalid_dir": "This directory can't be used. Pick another.",- "local_hint": "Agents on other machines won't see this path — they'll fail to start. Use repos for shared work."+ "local_hint": "Agents on other machines won't see this path — they'll fail to start. Use repos for shared work.",+ "repos_ref_default": "Default branch"},"create_issue": {"sr_manual": "New Issue",diff --git a/packages/views/locales/en/projects.json b/packages/views/locales/en/projects.jsonindex 5253a4fffc..4231b49769 100644--- a/packages/views/locales/en/projects.json+++ b/packages/views/locales/en/projects.json@@ -136,7 +136,25 @@"mode_badge_worktree_tooltip": "Runs execute at the same time in their own git worktree and hand back a branch. Your working copy is untouched.","toast_local_mode_updated": "Execution mode updated","toast_local_mode_update_failed": "Could not update the execution mode",- "mode_badge_in_place": "Direct"+ "mode_badge_in_place": "Direct",+ "ref_label": "Starting branch",+ "ref_placeholder": "main",+ "ref_hint": "Tasks start from this branch and open their pull requests against it. Leave empty to use the repository's default branch.",+ "ref_error_too_long": "Use at most 255 characters.",+ "ref_error_characters": "A git ref can't contain spaces or any of ~ ^ : ? * [ \\",+ "ref_error_format": "Not a valid branch, tag, or commit.",+ "ref_dialog_title": "Which branch should tasks work on?",+ "ref_dialog_description": "New tasks in this project check out this branch and open their pull requests against it. Work already underway keeps the branch it started on.",+ "ref_cancel": "Cancel",+ "ref_save": "Save",+ "ref_edit_tooltip": "Change the branch tasks work on",+ "ref_badge_tooltip": "Tasks start from {{ref}} and deliver back to it.",+ "toast_ref_updated": "Branch updated",+ "toast_ref_cleared": "Back to the default branch",+ "toast_ref_update_failed": "Could not update the branch",+ "ref_error_commit": "That's a commit, not a branch. Tasks deliver back to the branch they start from — for a one-off revision, pass --ref to multica repo checkout.",+ "ref_default_label": "Default branch",+ "ref_default_tooltip": "No branch set — tasks use whatever the repository's default branch is at the time."},"delete_dialog": {"title": "Delete project",diff --git a/packages/views/locales/fr/modals.json b/packages/views/locales/fr/modals.jsonindex f6ea703d00..86963cd30d 100644--- a/packages/views/locales/fr/modals.json+++ b/packages/views/locales/fr/modals.json@@ -137,7 +137,8 @@"local_clear": "Effacer","local_pick_failed": "Impossible d'ouvrir le sélecteur de répertoire.","local_invalid_dir": "Ce répertoire ne peut pas être utilisé. Choisissez-en un autre.",- "local_hint": "Les agents des autres machines ne verront pas ce chemin — ils ne pourront pas démarrer. Utilisez des dépôts pour le travail partagé."+ "local_hint": "Les agents des autres machines ne verront pas ce chemin — ils ne pourront pas démarrer. Utilisez des dépôts pour le travail partagé.",+ "repos_ref_default": "Branche par défaut"},"create_issue": {"sr_manual": "Nouvelle tâche",diff --git a/packages/views/locales/fr/projects.json b/packages/views/locales/fr/projects.jsonindex ab48017a27..52cc9e5c03 100644--- a/packages/views/locales/fr/projects.json+++ b/packages/views/locales/fr/projects.json@@ -136,7 +136,25 @@"mode_badge_worktree_tooltip": "Les exécutions ont lieu simultanément dans leur propre worktree git et restituent une branche. Votre copie de travail reste intacte.","toast_local_mode_updated": "Mode d'exécution mis à jour","toast_local_mode_update_failed": "Impossible de mettre à jour le mode d'exécution",- "mode_badge_in_place": "Direct"+ "mode_badge_in_place": "Direct",+ "ref_label": "Branche de départ",+ "ref_placeholder": "main",+ "ref_hint": "Les tâches démarrent depuis cette branche et y ouvrent leurs pull requests. Laissez vide pour utiliser la branche par défaut du dépôt.",+ "ref_error_too_long": "255 caractères maximum.",+ "ref_error_characters": "Une réf git ne peut pas contenir d'espace ni les caractères ~ ^ : ? * [ \\",+ "ref_error_format": "Branche, tag ou commit invalide.",+ "ref_dialog_title": "Sur quelle branche les tâches doivent-elles travailler ?",+ "ref_dialog_description": "Les nouvelles tâches de ce projet récupèrent cette branche et y ouvrent leurs pull requests. Le travail déjà engagé conserve la branche sur laquelle il a démarré.",+ "ref_cancel": "Annuler",+ "ref_save": "Enregistrer",+ "ref_edit_tooltip": "Changer la branche de travail des tâches",+ "ref_badge_tooltip": "Les tâches démarrent depuis {{ref}} et y livrent leur travail.",+ "toast_ref_updated": "Branche mise à jour",+ "toast_ref_cleared": "Retour à la branche par défaut",+ "toast_ref_update_failed": "Impossible de mettre à jour la branche",+ "ref_error_commit": "Ceci est un commit, pas une branche. Les tâches livrent sur la branche depuis laquelle elles démarrent — pour une révision ponctuelle, utilisez multica repo checkout --ref.",+ "ref_default_label": "Branche par défaut",+ "ref_default_tooltip": "Aucune branche définie — les tâches utilisent la branche par défaut du dépôt au moment voulu."},"delete_dialog": {"title": "Supprimer le projet",diff --git a/packages/views/locales/ja/modals.json b/packages/views/locales/ja/modals.jsonindex c01db03ac1..5e25d98aee 100644--- a/packages/views/locales/ja/modals.json+++ b/packages/views/locales/ja/modals.json@@ -135,7 +135,8 @@"local_clear": "クリア","local_pick_failed": "ディレクトリ選択画面を開けませんでした。","local_invalid_dir": "このディレクトリは使用できません。別のものを選択してください。",- "local_hint": "他のマシンのエージェントはこのパスを参照できず、起動に失敗します。共有作業にはリポジトリを使用してください。"+ "local_hint": "他のマシンのエージェントはこのパスを参照できず、起動に失敗します。共有作業にはリポジトリを使用してください。",+ "repos_ref_default": "デフォルトブランチ"},"create_issue": {"sr_manual": "新規タスク",diff --git a/packages/views/locales/ja/projects.json b/packages/views/locales/ja/projects.jsonindex 8d38275404..16f229b067 100644--- a/packages/views/locales/ja/projects.json+++ b/packages/views/locales/ja/projects.json@@ -135,7 +135,25 @@"mode_badge_worktree_tooltip": "実行はそれぞれの git ワークツリーで並行して進み、ブランチとして成果を返します。作業コピーは変更されません。","toast_local_mode_updated": "実行モードを更新しました","toast_local_mode_update_failed": "実行モードを更新できませんでした",- "mode_badge_in_place": "直接"+ "mode_badge_in_place": "直接",+ "ref_label": "起点ブランチ",+ "ref_placeholder": "main",+ "ref_hint": "タスクはこのブランチから開始し、プルリクエストもここへ作成します。空欄の場合はリポジトリのデフォルトブランチを使用します。",+ "ref_error_too_long": "255 文字以内で入力してください。",+ "ref_error_characters": "git ref にスペースや ~ ^ : ? * [ \\ は使用できません",+ "ref_error_format": "有効なブランチ、タグ、コミットではありません。",+ "ref_dialog_title": "タスクはどのブランチで作業しますか?",+ "ref_dialog_description": "このプロジェクトで新しく開始するタスクはこのブランチをチェックアウトし、プルリクエストもここへ作成します。進行中の作業は開始時のブランチのままです。",+ "ref_cancel": "キャンセル",+ "ref_save": "保存",+ "ref_edit_tooltip": "タスクが作業するブランチを変更",+ "ref_badge_tooltip": "タスクは {{ref}} から開始し、このブランチへ成果を返します。",+ "toast_ref_updated": "ブランチを更新しました",+ "toast_ref_cleared": "デフォルトブランチに戻しました",+ "toast_ref_update_failed": "ブランチを更新できませんでした",+ "ref_error_commit": "これはコミットであり、ブランチではありません。タスクは開始したブランチへ成果を返します。特定のリビジョンだけが必要な場合は multica repo checkout --ref を使ってください。",+ "ref_default_label": "デフォルトブランチ",+ "ref_default_tooltip": "ブランチ未設定 — タスクはその時点のリポジトリのデフォルトブランチを使用します。"},"delete_dialog": {"title": "プロジェクトを削除",diff --git a/packages/views/locales/ko/modals.json b/packages/views/locales/ko/modals.jsonindex f53b235099..a53e2957dd 100644--- a/packages/views/locales/ko/modals.json+++ b/packages/views/locales/ko/modals.json@@ -135,7 +135,8 @@"local_clear": "지우기","local_pick_failed": "디렉터리 선택 창을 열 수 없습니다.","local_invalid_dir": "이 디렉터리는 사용할 수 없습니다. 다른 디렉터리를 선택하세요.",- "local_hint": "다른 기기의 에이전트는 이 경로를 볼 수 없어 시작에 실패합니다. 공유 작업에는 저장소를 사용하세요."+ "local_hint": "다른 기기의 에이전트는 이 경로를 볼 수 없어 시작에 실패합니다. 공유 작업에는 저장소를 사용하세요.",+ "repos_ref_default": "기본 브랜치"},"create_issue": {"sr_manual": "새 태스크",diff --git a/packages/views/locales/ko/projects.json b/packages/views/locales/ko/projects.jsonindex 06e6c990cf..64eec6ad19 100644--- a/packages/views/locales/ko/projects.json+++ b/packages/views/locales/ko/projects.json@@ -135,7 +135,25 @@"mode_badge_worktree_tooltip": "실행이 각자의 git 워크트리에서 동시에 진행되고 브랜치로 결과를 돌려줍니다. 작업 사본은 변경되지 않습니다.","toast_local_mode_updated": "실행 모드를 업데이트했습니다","toast_local_mode_update_failed": "실행 모드를 업데이트하지 못했습니다",- "mode_badge_in_place": "직접"+ "mode_badge_in_place": "직접",+ "ref_label": "시작 브랜치",+ "ref_placeholder": "main",+ "ref_hint": "작업은 이 브랜치에서 시작하고 풀 리퀘스트도 이 브랜치로 엽니다. 비워 두면 저장소의 기본 브랜치를 사용합니다.",+ "ref_error_too_long": "255자 이내로 입력하세요.",+ "ref_error_characters": "git ref에는 공백이나 ~ ^ : ? * [ \\ 문자를 사용할 수 없습니다",+ "ref_error_format": "유효한 브랜치, 태그 또는 커밋이 아닙니다.",+ "ref_dialog_title": "작업은 어느 브랜치에서 진행하나요?",+ "ref_dialog_description": "이 프로젝트에서 새로 시작하는 작업은 이 브랜치를 체크아웃하고 풀 리퀘스트도 여기로 엽니다. 이미 진행 중인 작업은 시작한 브랜치를 유지합니다.",+ "ref_cancel": "취소",+ "ref_save": "저장",+ "ref_edit_tooltip": "작업이 진행되는 브랜치 변경",+ "ref_badge_tooltip": "작업이 {{ref}}에서 시작하고 이 브랜치로 결과를 전달합니다.",+ "toast_ref_updated": "브랜치를 업데이트했습니다",+ "toast_ref_cleared": "기본 브랜치로 되돌렸습니다",+ "toast_ref_update_failed": "브랜치를 업데이트하지 못했습니다",+ "ref_error_commit": "이것은 브랜치가 아니라 커밋입니다. 작업은 시작한 브랜치로 결과를 전달합니다. 일회성 리비전이 필요하면 multica repo checkout --ref를 사용하세요.",+ "ref_default_label": "기본 브랜치",+ "ref_default_tooltip": "브랜치가 설정되지 않음 — 작업은 그 시점의 저장소 기본 브랜치를 사용합니다."},"delete_dialog": {"title": "프로젝트 삭제",diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.jsonindex 9bedf9d5a7..804c1238d1 100644--- a/packages/views/locales/zh-Hans/modals.json+++ b/packages/views/locales/zh-Hans/modals.json@@ -135,7 +135,8 @@"local_clear": "清除","local_pick_failed": "无法打开目录选择器。","local_invalid_dir": "该目录不可用,请重新选择。",- "local_hint": "其他机器上的智能体看不到这个路径,会启动失败。需要协作请用仓库模式。"+ "local_hint": "其他机器上的智能体看不到这个路径,会启动失败。需要协作请用仓库模式。",+ "repos_ref_default": "默认分支"},"create_issue": {"sr_manual": "新建任务",diff --git a/packages/views/locales/zh-Hans/projects.json b/packages/views/locales/zh-Hans/projects.jsonindex a59a065a19..621b671a87 100644--- a/packages/views/locales/zh-Hans/projects.json+++ b/packages/views/locales/zh-Hans/projects.json@@ -135,7 +135,25 @@"mode_badge_worktree_tooltip": "运行在各自的 git worktree 中并行执行,并以分支形式交付结果。你的工作区不会被改动。","toast_local_mode_updated": "已更新执行方式","toast_local_mode_update_failed": "无法更新执行方式",- "mode_badge_in_place": "原地"+ "mode_badge_in_place": "原地",+ "ref_label": "起始分支",+ "ref_placeholder": "main",+ "ref_hint": "任务从这条分支开始,PR 也默认提到这里。留空则使用仓库默认分支。",+ "ref_error_too_long": "最多 255 个字符。",+ "ref_error_characters": "git ref 不能包含空格或 ~ ^ : ? * [ \\ 这些字符",+ "ref_error_format": "不是有效的分支、Tag 或 Commit。",+ "ref_dialog_title": "任务在哪条分支上工作?",+ "ref_dialog_description": "本项目新开始的任务会检出这条分支,PR 也提到这里。已经在进行的任务仍留在它当初的分支上。",+ "ref_cancel": "取消",+ "ref_save": "保存",+ "ref_edit_tooltip": "修改任务工作的分支",+ "ref_badge_tooltip": "任务从 {{ref}} 开始,并交付回这条分支。",+ "toast_ref_updated": "分支已更新",+ "toast_ref_cleared": "已恢复为默认分支",+ "toast_ref_update_failed": "无法更新分支",+ "ref_error_commit": "这是一个 commit,不是分支。任务会交付回它起始的分支 —— 只需要某次修订,请用 multica repo checkout --ref。",+ "ref_default_label": "默认分支",+ "ref_default_tooltip": "未设置分支 —— 任务使用仓库当时的默认分支。"},"delete_dialog": {"title": "删除项目",diff --git a/packages/views/modals/create-project.test.tsx b/packages/views/modals/create-project.test.tsxindex 74b9d2b3a5..a7d983f20c 100644--- a/packages/views/modals/create-project.test.tsx+++ b/packages/views/modals/create-project.test.tsx@@ -1,6 +1,6 @@import React from "react";import { describe, expect, it, vi } from "vitest";-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { renderWithI18n } from "../test/i18n";@@ -16,8 +16,10 @@ vi.mock("@tanstack/react-query", () => ({queryOptions: (options: unknown) => options,}));+const createProjectMock = vi.hoisted(() => vi.fn().mockResolvedValue({ id: "p1" }));+vi.mock("@multica/core/projects/mutations", () => ({- useCreateProject: () => ({ mutateAsync: vi.fn() }),+ useCreateProject: () => ({ mutateAsync: createProjectMock }),}));vi.mock("@multica/core/projects", () => ({@@ -67,20 +69,46 @@ vi.mock("../navigation", () => ({}));vi.mock("../editor", () => {- const ContentEditor = React.forwardRef<HTMLTextAreaElement, { placeholder?: string }>(- ({ placeholder }, ref) => <textarea ref={ref} placeholder={placeholder} />,- );+ // Exposes the imperative handle the modal actually calls on submit+ // (getMarkdown). A plain textarea ref makes every submit throw, which is+ // invisible until a test clicks Create Project.+ const ContentEditor = React.forwardRef<+ { getMarkdown: () => string },+ { placeholder?: string }+ >(({ placeholder }, ref) => {+ const inner = React.useRef<HTMLTextAreaElement>(null);+ React.useImperativeHandle(ref, () => ({+ getMarkdown: () => inner.current?.value ?? "",+ }));+ return <textarea ref={inner} placeholder={placeholder} />;+ });ContentEditor.displayName = "ContentEditor";return {ContentEditor,+ // Wires onSubmit to Enter the way the real editor does. Without it the+ // keyboard path into handleSubmit is untestable, and that path bypasses+ // the submit button's disabled state entirely.TitleEditor: ({placeholder,onChange,+ onSubmit,}: {placeholder?: string;onChange?: (value: string) => void;- }) => <input placeholder={placeholder} onChange={(e) => onChange?.(e.target.value)} />,+ onSubmit?: () => void;+ }) => (+ <input+ placeholder={placeholder}+ onChange={(e) => onChange?.(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ onSubmit?.();+ }+ }}+ />+ ),};});@@ -201,6 +229,144 @@ describe("CreateProjectModal", () => {expect(screen.getByRole("button", { name: "Due date" })).toBeInTheDocument();});+ // A project that tracks one delivery line has to be able to say so while it+ // is being created — otherwise its very first tasks start from the default+ // branch and the setting is something to discover afterwards.+ it("attaches a repository with the checkout ref typed beside it", async () => {+ createProjectMock.mockClear();+ const user = userEvent.setup();+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);++ await user.type(screen.getByPlaceholderText(/project title/i), "Release 2026-09");+ await user.type(+ screen.getByPlaceholderText(/github\.com\/owner\/repo/i),+ apiRepoUrl,+ );+ await user.type(+ screen.getByLabelText(/starting branch/i),+ "release/2026-09",+ );+ await user.click(screen.getByRole("button", { name: /^add$/i }));+ await user.click(screen.getByRole("button", { name: /^create project$/i }));++ expect(createProjectMock).toHaveBeenCalledTimes(1);+ const payload = createProjectMock.mock.calls[0]?.[0] as {+ resources?: Array<{ resource_type: string; resource_ref: Record<string, unknown> }>;+ };+ expect(payload.resources).toEqual([+ {+ resource_type: "github_repo",+ resource_ref: { url: apiRepoUrl, ref: "release/2026-09" },+ },+ ]);+ });++ it("omits the ref key for a repository left on its default branch", async () => {+ createProjectMock.mockClear();+ const user = userEvent.setup();+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);++ await user.type(screen.getByPlaceholderText(/project title/i), "Plain project");+ await user.type(+ screen.getByPlaceholderText(/github\.com\/owner\/repo/i),+ apiRepoUrl,+ );+ await user.click(screen.getByRole("button", { name: /^add$/i }));+ await user.click(screen.getByRole("button", { name: /^create project$/i }));++ const payload = createProjectMock.mock.calls[0]?.[0] as {+ resources?: Array<{ resource_ref: Record<string, unknown> }>;+ };+ expect(payload.resources?.[0]?.resource_ref).toEqual({ url: apiRepoUrl });+ });++ // Regression: the submit gate only ever checked the custom-URL field, so a+ // branch edited on an ALREADY SELECTED repo could carry a commit id past a+ // visible inline error. The server accepts SHAs by design, so nothing+ // downstream would have caught it.+ it("refuses to create while any selected repo's branch is rejected", async () => {+ createProjectMock.mockClear();+ const user = userEvent.setup();+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);++ await user.type(screen.getByPlaceholderText(/project title/i), "Bad branch");+ await user.click(+ screen.getByRole("button", { name: (name) => name.includes(apiRepoUrl) }),+ );++ // The per-repo branch editor, reached from the selected-repo row.+ await user.click(screen.getByRole("button", { name: /default branch/i }));+ await user.type(+ screen.getByLabelText(/starting branch/i),+ "5e0b1cfa0a7d6a1a0f4b3f2e1d0c9b8a7f6e5d4c",+ );+ expect(screen.getByText(/commit, not a branch/i)).toBeTruthy();++ const create = screen.getByRole("button", {+ name: /^create project$/i,+ }) as HTMLButtonElement;+ expect(create.disabled).toBe(true);+ await user.click(create);+ expect(createProjectMock).not.toHaveBeenCalled();+ });++ // The same gate has to hold for the keyboard path — TitleEditor's onSubmit+ // calls handleSubmit directly, bypassing the button's disabled state.+ it("refuses on keyboard submit too, not just the disabled button", async () => {+ createProjectMock.mockClear();+ const user = userEvent.setup();+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);++ await user.type(screen.getByPlaceholderText(/project title/i), "Bad branch");+ await user.click(+ screen.getByRole("button", { name: (name) => name.includes(apiRepoUrl) }),+ );+ await user.click(screen.getByRole("button", { name: /default branch/i }));+ await user.type(+ screen.getByLabelText(/starting branch/i),+ "5e0b1cfa0a7d6a1a0f4b3f2e1d0c9b8a7f6e5d4c",+ );++ fireEvent.keyDown(screen.getByPlaceholderText(/project title/i), { key: "Enter" });+ expect(createProjectMock).not.toHaveBeenCalled();+ });++ // Regression: the /tree/ split was gated on the branch field being empty, so+ // a SECOND pasted browse URL was stored whole — a clone target that does not+ // exist. Normalising the URL is unconditional; only the branch value is a+ // question of whether to overwrite.+ it("normalises a pasted browse URL even when a branch is already filled in", async () => {+ createProjectMock.mockClear();+ const user = userEvent.setup();+ renderWithI18n(<CreateProjectModal onClose={vi.fn()} />);++ await user.type(screen.getByPlaceholderText(/project title/i), "Second paste");+ const urlField = screen.getByPlaceholderText(/github\.com\/owner\/repo/i);+ await user.clear(urlField);+ await user.paste("https://github.com/multica-ai/one/tree/release/2026-09");+ expect((urlField as HTMLInputElement).value).toBe("https://github.com/multica-ai/one");+ expect((screen.getByLabelText(/starting branch/i) as HTMLInputElement).value).toBe(+ "release/2026-09",+ );++ // Changing your mind about which repo: the whole pair is replaced.+ await user.clear(urlField);+ await user.paste("https://github.com/multica-ai/two/tree/main");+ expect((urlField as HTMLInputElement).value).toBe("https://github.com/multica-ai/two");+ expect((screen.getByLabelText(/starting branch/i) as HTMLInputElement).value).toBe("main");++ await user.click(screen.getByRole("button", { name: /^add$/i }));+ await user.click(screen.getByRole("button", { name: /^create project$/i }));++ const payload = createProjectMock.mock.calls[0]?.[0] as {+ resources?: Array<{ resource_ref: Record<string, unknown> }>;+ };+ expect(payload.resources?.[0]?.resource_ref).toEqual({+ url: "https://github.com/multica-ai/two",+ ref: "main",+ });+ });+it("filters workspace repositories by search text", async () => {const user = userEvent.setup();diff --git a/packages/views/modals/create-project.tsx b/packages/views/modals/create-project.tsxindex 87c2db54f6..52effd8e52 100644--- a/packages/views/modals/create-project.tsx+++ b/packages/views/modals/create-project.tsx@@ -29,6 +29,7 @@ import {PROJECT_STATUS_ORDER,PROJECT_PRIORITY_ORDER,} from "@multica/core/projects/config";+import { splitGithubUrlRef } from "@multica/core/github";import { useWorkspaceId } from "@multica/core/hooks";import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";@@ -61,6 +62,10 @@ import { ProjectStartDatePicker } from "../projects/components/project-start-datimport { ProjectDueDatePicker } from "../projects/components/project-due-date-picker";import { PillButton } from "../common/pill-button";import { githubShortLabel } from "../common/github-url";+import {+ GithubRefField,+ githubRefHasError,+} from "../projects/components/github-ref-field";import {isDesktopShell,pickDirectory,@@ -166,9 +171,15 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {// created. Stored as URLs (not full ProjectResource rows) — they're not// persisted until handleSubmit fires the createProjectResource calls.const [selectedRepos, setSelectedRepos] = useState<string[]>([]);+ // Checkout ref per selected repo URL, absent when the repo starts from its+ // default branch. Keyed by URL rather than folded into selectedRepos so+ // toggling a repo off and on again does not silently drop the ref.+ const [repoRefs, setRepoRefs] = useState<Record<string, string>>({});const [repoPopoverOpen, setRepoPopoverOpen] = useState(false);const [repoSearch, setRepoSearch] = useState("");const [customRepoUrl, setCustomRepoUrl] = useState("");+ const [customRepoRef, setCustomRepoRef] = useState("");+ const [editingRefFor, setEditingRefFor] = useState<string | null>(null);const workspaceRepos = workspace?.repos ?? [];const repoQuery = repoSearch.trim().toLowerCase();const filteredWorkspaceRepos = workspaceRepos.filter((repo) =>@@ -318,8 +329,19 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {const createProject = useCreateProject();+ // Every selected repo's branch, not just the one in the add field. A branch+ // edited on an already-selected row goes through setRepoRef and used to+ // reach the payload with only an inline error to show for it — the server+ // accepts commit ids by design, so nothing downstream would have caught it.+ const hasRejectedRepoRef = selectedRepos.some((url) =>+ githubRefHasError(repoRefs[url] ?? ""),+ );+const handleSubmit = async () => {+ // Checked here as well as on the button: TitleEditor's onSubmit calls this+ // directly, so a disabled button alone leaves the keyboard path open.if (!title.trim() || submitting) return;+ if (sourceMode === "repos" && hasRejectedRepoRef) return;// `sourceMode` decides which side's stash gets persisted — the other// side is silently dropped, so repos picked then abandoned for local// mode don't leak into the project.@@ -327,10 +349,15 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {| Array<{ resource_type: "github_repo" | "local_directory"; resource_ref: Record<string, unknown> }>| undefined;if (sourceMode === "repos" && selectedRepos.length > 0) {- resources = selectedRepos.map((url) => ({- resource_type: "github_repo" as const,- resource_ref: { url },- }));+ resources = selectedRepos.map((url) => {+ const ref = repoRefs[url]?.trim();+ return {+ resource_type: "github_repo" as const,+ // Omit the key entirely when empty: an absent ref is what "use the+ // default branch" looks like on the wire.+ resource_ref: ref ? { url, ref } : { url },+ };+ });} else if (sourceMode === "local" &&selectedLocalPath &&@@ -386,9 +413,47 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {const addCustomRepo = () => {const url = customRepoUrl.trim();- if (!url) return;+ const ref = customRepoRef.trim();+ if (!url || githubRefHasError(ref)) return;setSelectedRepos((prev) => (prev.includes(url) ? prev : [...prev, url]));+ setRepoRefs((prev) => {+ if (!ref) {+ const { [url]: _dropped, ...rest } = prev;+ return rest;+ }+ return { ...prev, [url]: ref };+ });setCustomRepoUrl("");+ setCustomRepoRef("");+ };++ // Someone who wants a branch copies it out of the address bar, so a pasted+ // .../tree/<branch> URL is split into its two halves rather than added whole+ // as a clone URL that does not exist. Both halves land in visible fields, so+ // a wrong guess is obvious before the project is created.+ //+ // Normalising the URL is unconditional. Gating it on the branch field being+ // empty meant a second pasted browse URL — changing your mind about which+ // repo — was stored whole, producing a clone target that does not exist.+ // Whether to overwrite the BRANCH is the separate question, and the pasted+ // pair wins: the branch field only appears once a URL is present, so a value+ // sitting in it came from the previous URL, not from something the user+ // typed ahead of time.+ const handleCustomRepoUrlChange = (next: string) => {+ const split = splitGithubUrlRef(next);+ setCustomRepoUrl(split.url);+ if (split.ref) setCustomRepoRef(split.ref);+ };++ const setRepoRef = (url: string, ref: string) => {+ const trimmed = ref.trim();+ setRepoRefs((prev) => {+ if (!trimmed) {+ const { [url]: _dropped, ...rest } = prev;+ return rest;+ }+ return { ...prev, [url]: trimmed };+ });};return (@@ -781,24 +846,37 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {e.preventDefault();addCustomRepo();}}- className="flex items-center gap-1.5 pt-1 border-t"+ className="space-y-1.5 pt-1 border-t">- <input- type="text"- value={customRepoUrl}- onChange={(e) => setCustomRepoUrl(e.target.value)}- placeholder={t(($) => $.create_project.repos_url_placeholder)}- className="flex-1 bg-transparent text-caption px-2 py-1 outline-none placeholder:text-muted-foreground"- />- <Button- type="submit"- size="sm"- variant="ghost"- className="h-6 px-2 text-caption"- disabled={!customRepoUrl.trim()}- >- {t(($) => $.create_project.repos_add)}- </Button>+ <div className="flex items-center gap-1.5">+ <input+ type="text"+ value={customRepoUrl}+ onChange={(e) => handleCustomRepoUrlChange(e.target.value)}+ placeholder={t(($) => $.create_project.repos_url_placeholder)}+ className="flex-1 min-w-0 bg-transparent text-caption px-2 py-1 outline-none placeholder:text-muted-foreground"+ />+ <Button+ type="submit"+ size="sm"+ variant="ghost"+ className="h-6 px-2 text-caption"+ disabled={!customRepoUrl.trim() || githubRefHasError(customRepoRef)}+ >+ {t(($) => $.create_project.repos_add)}+ </Button>+ </div>+ {/* Only once a URL is entered: an empty form should still+ read as one field, and the default branch is the right+ answer often enough that this must not look like a+ second required step. */}+ {customRepoUrl.trim() && (+ <GithubRefField+ id="create-project-repo-ref"+ value={customRepoRef}+ onChange={setCustomRepoRef}+ />+ )}</form>{selectedRepos.length > 0 && (<div className="space-y-1 pt-1 border-t">@@ -806,19 +884,52 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {{t(($) => $.create_project.repos_selected)}</div>{selectedRepos.map((url) => (- <div- key={url}- className="flex items-center gap-2 text-caption"- >- <GithubIcon className="size-3 text-muted-foreground" />- <RepoUrlText url={url} />- <button- type="button"- onClick={() => toggleRepo(url)}- className="text-muted-foreground hover:text-foreground"- >- <XIcon className="size-3" />- </button>+ <div key={url} className="space-y-1">+ <div className="flex items-center gap-2 text-caption">+ <GithubIcon className="size-3 shrink-0 text-muted-foreground" />+ <RepoUrlText url={url} />+ {/* The ref rides beside the repo it belongs to,+ not in one field for the whole list: each repo+ can start somewhere different. */}+ <button+ type="button"+ onClick={() =>+ setEditingRefFor(editingRefFor === url ? null : url)+ }+ className={cn(+ "flex shrink-0 items-center gap-1 rounded-sm px-1 py-0.5 text-micro transition-colors hover:bg-accent",+ repoRefs[url]+ ? "text-foreground"+ : "text-muted-foreground",+ )}+ >+ <GitBranch className="size-3" />+ <span className="max-w-24 truncate">+ {repoRefs[url] ??+ t(($) => $.create_project.repos_ref_default)}+ </span>+ </button>+ <button+ type="button"+ onClick={() => {+ toggleRepo(url);+ if (editingRefFor === url) setEditingRefFor(null);+ }}+ className="shrink-0 text-muted-foreground hover:text-foreground"+ >+ <XIcon className="size-3" />+ </button>+ </div>+ {editingRefFor === url && (+ <div className="pl-5">+ <GithubRefField+ value={repoRefs[url] ?? ""}+ onChange={(next) => setRepoRef(url, next)}+ onSubmit={() => setEditingRefFor(null)}+ autoFocus+ />+ </div>+ )}</div>))}</div>@@ -984,7 +1095,11 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {<Buttonsize="sm"onClick={handleSubmit}- disabled={!title.trim() || submitting}+ disabled={+ !title.trim() ||+ submitting ||+ (sourceMode === "repos" && hasRejectedRepoRef)+ }className="shrink-0">{submitting ? t(($) => $.create_project.submitting) : t(($) => $.create_project.submit)}diff --git a/packages/views/projects/components/github-ref-dialog.tsx b/packages/views/projects/components/github-ref-dialog.tsxnew file mode 100644index 0000000000..f188424070--- /dev/null+++ b/packages/views/projects/components/github-ref-dialog.tsx@@ -0,0 +1,105 @@+"use client";++import { useEffect, useState } from "react";+import { TriangleAlert } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { GithubRefField, githubRefHasError } from "./github-ref-field";+import { useT } from "../../i18n/use-t";+import { githubShortLabel } from "../../common/github-url";++interface GithubRefDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Repository being configured, so the user knows which row this edits. */+ url: string;+ /** Current ref; empty means the repository's default branch. */+ value: string;+ /** Server-side rejection to show inline. */+ errorMessage?: string;+ saving?: boolean;+ onConfirm: (ref: string) => void;+}++/**+ * Sets the branch an already attached `github_repo` resource works on.+ *+ * A dialog rather than an inline field: unlike renaming a row, this changes+ * where every future task in the project starts AND where it delivers, and+ * that is worth a sentence the row has no space for. The same sentence has to+ * say what it does not do — the ref is read when a task is claimed, so work+ * already underway keeps the branch it started on.+ */+export function GithubRefDialog({+ open,+ onOpenChange,+ url,+ value,+ errorMessage,+ saving = false,+ onConfirm,+}: GithubRefDialogProps) {+ const { t } = useT("projects");+ const [draft, setDraft] = useState(value);++ // Re-sync on reopen, otherwise the previous row's ref is what shows.+ useEffect(() => {+ if (open) setDraft(value);+ }, [open, value]);++ const invalid = githubRefHasError(draft);++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t(($) => $.resources.ref_dialog_title)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.resources.ref_dialog_description)}+ </DialogDescription>+ </DialogHeader>++ <div className="rounded-md bg-muted px-2.5 py-1.5 font-mono text-micro text-muted-foreground break-all">+ {githubShortLabel(url)}+ </div>++ <GithubRefField+ id="github-ref"+ value={draft}+ onChange={setDraft}+ onSubmit={() => {+ if (!invalid && !saving) onConfirm(draft.trim());+ }}+ autoFocus+ />++ {errorMessage && (+ <div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-caption text-destructive">+ <TriangleAlert className="size-3.5 mt-0.5 shrink-0" />+ <span>{errorMessage}</span>+ </div>+ )}++ <DialogFooter>+ <Button+ variant="ghost"+ onClick={() => onOpenChange(false)}+ disabled={saving}+ >+ {t(($) => $.resources.ref_cancel)}+ </Button>+ <Button onClick={() => onConfirm(draft.trim())} disabled={saving || invalid}>+ {t(($) => $.resources.ref_save)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/projects/components/github-ref-field.tsx b/packages/views/projects/components/github-ref-field.tsxnew file mode 100644index 0000000000..7fd1a3c322--- /dev/null+++ b/packages/views/projects/components/github-ref-field.tsx@@ -0,0 +1,123 @@+"use client";++import { useId } from "react";+import {+ looksLikeCommitSha,+ validateGitRef,+ type GitRefInvalidReason,+} from "@multica/core/github";+import { useT } from "../../i18n/use-t";++/**+ * Free-text entry for the branch a project's tasks work on.+ *+ * Asks for a BRANCH specifically, though the stored field accepts any ref the+ * daemon can resolve. The reason is delivery: a pinned starting point is also+ * where tasks open their pull requests, and a tag or a commit has nothing to+ * merge back into. Tags and commits remain reachable per task through+ * `multica repo checkout --ref`, which is where a one-off revision belongs.+ *+ * That promise cannot be enforced here — `v1.2.3` is a legal branch name and+ * `main` is a legal tag, so telling them apart means asking the remote, which+ * the product deliberately does not do. The one shape that is unambiguous is a+ * full-length object id, and only that is declined.+ *+ * Free text rather than a dropdown for the same reason: nothing in the product+ * can list a repository's branches today — the server never touches the+ * repository, and the daemon holding the bare caches may be offline or lack+ * access to a private repo.+ *+ * Shared by the create-project modal and the resource panel so the same+ * decision reads the same way wherever it is made.+ */+export function GithubRefField({+ value,+ onChange,+ onSubmit,+ autoFocus,+ id: providedId,+}: {+ value: string;+ onChange: (next: string) => void;+ /** Enter in the field — lets a dialog save without reaching for the mouse. */+ onSubmit?: () => void;+ autoFocus?: boolean;+ /** Optional stable id; one is generated when omitted. */+ id?: string;+}) {+ const { t } = useT("projects");+ // Generated rather than required, because a caller that renders one field+ // PER REPO cannot supply a static id and would otherwise pass none — which+ // silently detaches the label from its input and leaves the field unnamed+ // for a screen reader and untargetable by getByLabelText.+ const generatedId = useId();+ const id = providedId ?? generatedId;+ const error = refErrorMessage(value, t);++ return (+ <div className="space-y-1">+ <label htmlFor={id} className="text-caption font-medium">+ {t(($) => $.resources.ref_label)}+ </label>+ <input+ id={id}+ type="text"+ value={value}+ autoFocus={autoFocus}+ onChange={(e) => onChange(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && onSubmit) {+ e.preventDefault();+ onSubmit();+ }+ }}+ spellCheck={false}+ autoCapitalize="none"+ autoCorrect="off"+ placeholder={t(($) => $.resources.ref_placeholder)}+ aria-invalid={error !== null}+ aria-describedby={`${id}-hint`}+ className="h-8 w-full rounded-md border bg-transparent px-2 font-mono text-caption outline-none placeholder:font-sans placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring aria-invalid:border-destructive"+ />+ <p+ id={`${id}-hint`}+ className={`text-micro ${error ? "text-destructive" : "text-muted-foreground"}`}+ >+ {error ?? t(($) => $.resources.ref_hint)}+ </p>+ </div>+ );+}++/** True when the field holds something this form will not submit. */+export function githubRefHasError(value: string): boolean {+ return validateGitRef(value).ok === false || looksLikeCommitSha(value);+}++/** The message to show, or null when the value is acceptable. */+function refErrorMessage(+ value: string,+ t: ReturnType<typeof useT<"projects">>["t"],+): string | null {+ // Checked before the grammar: a SHA is a perfectly valid ref to store, so+ // validateGitRef passes it. What makes it wrong HERE is that this field+ // names a branch to deliver to.+ if (looksLikeCommitSha(value)) return t(($) => $.resources.ref_error_commit);+ const validation = validateGitRef(value);+ if (validation.ok) return null;+ return grammarErrorMessage(validation.reason, t);+}++function grammarErrorMessage(+ reason: GitRefInvalidReason,+ t: ReturnType<typeof useT<"projects">>["t"],+): string {+ switch (reason) {+ case "too_long":+ return t(($) => $.resources.ref_error_too_long);+ case "invalid_characters":+ return t(($) => $.resources.ref_error_characters);+ case "invalid_format":+ return t(($) => $.resources.ref_error_format);+ }+}diff --git a/packages/views/projects/components/project-resources-github-ref.test.tsx b/packages/views/projects/components/project-resources-github-ref.test.tsxnew file mode 100644index 0000000000..4396abbd46--- /dev/null+++ b/packages/views/projects/components/project-resources-github-ref.test.tsx@@ -0,0 +1,303 @@+// @vitest-environment jsdom++import { describe, it, expect, vi, beforeEach } from "vitest";+import { screen, fireEvent, waitFor, within } from "@testing-library/react";+import { renderWithI18n } from "../../test/i18n";++const updateMock = vi.fn().mockResolvedValue({});+const createMock = vi.fn().mockResolvedValue({});++const PINNED = {+ id: "res-1",+ project_id: "p1",+ workspace_id: "workspace-1",+ resource_type: "github_repo",+ resource_ref: {+ url: "https://github.com/multica-ai/multica",+ ref: "release/2026-09",+ },+ // A custom name, which is what used to hide the ref: the row rendered+ // `label || owner/repo @ ref`, so naming a repo erased the one signal that+ // its tasks do not start from the default branch.+ label: "Release line",+ position: 0,+ created_at: "2026-09-19T00:00:00Z",+ created_by: "u1",+};++// The common case: no ref, so tasks use the repository's default branch.+const PLAIN = {+ id: "res-2",+ project_id: "p1",+ workspace_id: "workspace-1",+ resource_type: "github_repo",+ resource_ref: { url: "https://github.com/multica-ai/docs" },+ label: null,+ position: 1,+ created_at: "2026-09-19T00: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: [PINNED, PLAIN] };+ return { data: [] };+ },+ queryOptions: (options: unknown) => options,+}));++vi.mock("@multica/core/projects", () => ({+ projectResourcesOptions: () => ({ queryKey: ["project-resources"], queryFn: vi.fn() }),+ useCreateProjectResource: () => ({ mutateAsync: createMock, isPending: false }),+ useUpdateProjectResource: () => ({ mutateAsync: updateMock }),+ useDeleteProjectResource: () => ({ mutateAsync: vi.fn() }),+}));++vi.mock("@multica/core/config", () => ({+ useConfigStore: (selector: (state: { localWorktreeSupported: boolean }) => unknown) =>+ selector({ localWorktreeSupported: true }),+}));+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: () => false,+ pickDirectory: vi.fn(),+ validateLocalDirectory: vi.fn(),+}));+vi.mock("../../platform/use-local-daemon-status", () => ({+ useLocalDaemonStatus: () => ({ daemonId: null, deviceName: null, running: false }),+}));+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++import { ProjectResourcesSection } from "./project-resources-section";++describe("ProjectResourcesSection — github_repo checkout ref", () => {+ beforeEach(() => {+ updateMock.mockClear();+ createMock.mockClear();+ });++ it("shows the ref beside a repo that has a custom label", () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);+ expect(screen.getByText("Release line")).toBeTruthy();+ expect(screen.getByText("release/2026-09")).toBeTruthy();+ });++ it("saves a new ref while preserving the rest of the stored ref", async () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getAllByTitle(/change the branch tasks work on/i)[0]!);+ const input = screen.getByLabelText(/starting branch/i);+ fireEvent.change(input, { target: { value: "release/2026-10" } });+ fireEvent.click(screen.getByRole("button", { name: /^save$/i }));++ await waitFor(() => expect(updateMock).toHaveBeenCalledTimes(1));+ const payload = updateMock.mock.calls[0]?.[0] as {+ resourceId: string;+ data: { resource_ref: Record<string, unknown> };+ };+ expect(payload.resourceId).toBe("res-1");+ // The URL must ride along: the server replaces the whole ref rather than+ // deep-merging, so an edit that sends only `ref` is a 400 at best and+ // drops the repository at worst.+ expect(payload.data.resource_ref).toEqual({+ url: "https://github.com/multica-ai/multica",+ ref: "release/2026-10",+ });+ });++ it("clearing the field drops the key so tasks fall back to the default branch", async () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getAllByTitle(/change the branch tasks work on/i)[0]!);+ fireEvent.change(screen.getByLabelText(/starting branch/i), {+ target: { value: "" },+ });+ fireEvent.click(screen.getByRole("button", { name: /^save$/i }));++ await waitFor(() => expect(updateMock).toHaveBeenCalledTimes(1));+ const payload = updateMock.mock.calls[0]?.[0] as {+ data: { resource_ref: Record<string, unknown> };+ };+ expect(payload.data.resource_ref).toEqual({+ url: "https://github.com/multica-ai/multica",+ ref: undefined,+ });+ });++ it("refuses to save a ref git could never resolve", async () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getAllByTitle(/change the branch tasks work on/i)[0]!);+ fireEvent.change(screen.getByLabelText(/starting branch/i), {+ target: { value: "main..dev" },+ });++ const save = screen.getByRole("button", { name: /^save$/i }) as HTMLButtonElement;+ expect(save.disabled).toBe(true);+ expect(screen.getByText(/not a valid branch, tag, or commit/i)).toBeTruthy();+ fireEvent.click(save);+ expect(updateMock).not.toHaveBeenCalled();+ });++ it("attaches a repo with the ref typed alongside its URL", async () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getByRole("button", { name: /add resource/i }));+ const urlInput = screen.getByLabelText(/attach a github repo/i);+ fireEvent.change(urlInput, {+ target: { value: "https://github.com/multica-ai/other" },+ });+ fireEvent.change(screen.getByLabelText(/starting branch/i), {+ target: { value: "main" },+ });+ fireEvent.click(screen.getByRole("button", { name: /^add$/i }));++ await waitFor(() => expect(createMock).toHaveBeenCalledTimes(1));+ expect(createMock.mock.calls[0]?.[0]).toEqual({+ resource_type: "github_repo",+ resource_ref: { url: "https://github.com/multica-ai/other", ref: "main" },+ });+ });++ it("splits a pasted /tree/ URL into the repo and the branch it points at", async () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getByRole("button", { name: /add resource/i }));+ // What someone copies out of the address bar when they want a branch.+ // Stored whole, this is a clone URL that does not exist.+ fireEvent.change(screen.getByLabelText(/attach a github repo/i), {+ target: { value: "https://github.com/multica-ai/other/tree/release/2026-09" },+ });++ const urlInput = screen.getByLabelText(/attach a github repo/i) as HTMLInputElement;+ const refInput = screen.getByLabelText(/starting branch/i) as HTMLInputElement;+ expect(urlInput.value).toBe("https://github.com/multica-ai/other");+ expect(refInput.value).toBe("release/2026-09");++ fireEvent.click(screen.getByRole("button", { name: /^add$/i }));+ await waitFor(() => expect(createMock).toHaveBeenCalledTimes(1));+ expect(createMock.mock.calls[0]?.[0]).toEqual({+ resource_type: "github_repo",+ resource_ref: {+ url: "https://github.com/multica-ai/other",+ ref: "release/2026-09",+ },+ });+ });++ // Regression: the split was gated on the branch field being empty, so a+ // SECOND pasted browse URL went in whole as the clone URL.+ it("normalises a pasted browse URL even when a branch is already filled in", async () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getByRole("button", { name: /add resource/i }));+ const urlInput = () => screen.getByLabelText(/attach a github repo/i) as HTMLInputElement;+ const refInput = () => screen.getByLabelText(/starting branch/i) as HTMLInputElement;++ fireEvent.change(urlInput(), {+ target: { value: "https://github.com/multica-ai/one/tree/release/2026-09" },+ });+ expect(urlInput().value).toBe("https://github.com/multica-ai/one");+ expect(refInput().value).toBe("release/2026-09");++ fireEvent.change(urlInput(), {+ target: { value: "https://github.com/multica-ai/two/tree/main" },+ });+ expect(urlInput().value).toBe("https://github.com/multica-ai/two");+ expect(refInput().value).toBe("main");++ fireEvent.click(screen.getByRole("button", { name: /^add$/i }));+ await waitFor(() => expect(createMock).toHaveBeenCalledTimes(1));+ expect(createMock.mock.calls[0]?.[0]).toEqual({+ resource_type: "github_repo",+ resource_ref: { url: "https://github.com/multica-ai/two", ref: "main" },+ });+ });++ it("omits the ref key entirely when the field is left empty", async () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getByRole("button", { name: /add resource/i }));+ fireEvent.change(screen.getByLabelText(/attach a github repo/i), {+ target: { value: "https://github.com/multica-ai/other" },+ });+ fireEvent.click(screen.getByRole("button", { name: /^add$/i }));++ await waitFor(() => expect(createMock).toHaveBeenCalledTimes(1));+ expect(createMock.mock.calls[0]?.[0]).toEqual({+ resource_type: "github_repo",+ resource_ref: { url: "https://github.com/multica-ai/other" },+ });+ });++ it("blocks attaching when the ref is invalid, without touching the URL field", () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getByRole("button", { name: /add resource/i }));+ fireEvent.change(screen.getByLabelText(/attach a github repo/i), {+ target: { value: "https://github.com/multica-ai/other" },+ });+ fireEvent.change(screen.getByLabelText(/starting branch/i), {+ target: { value: "bad ref" },+ });++ const add = screen.getByRole("button", { name: /^add$/i }) as HTMLButtonElement;+ expect(add.disabled).toBe(true);+ fireEvent.click(add);+ expect(createMock).not.toHaveBeenCalled();+ });++ // Clearing a branch used to make the line vanish, which reads the same as+ // the setting never having existed. An unpinned repo says so instead.+ it("says 'Default branch' when nothing is pinned, rather than showing nothing", () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ // `.group` is the row root; the link's immediate parent is only its top line.+ const pinnedRow = screen.getByText("Release line").closest(".group") as HTMLElement;+ expect(within(pinnedRow).queryByText("release/2026-09")).toBeTruthy();+ expect(within(pinnedRow).queryByText(/default branch/i)).toBeNull();++ const plainRow = screen.getByText("multica-ai/docs").closest(".group") as HTMLElement;+ expect(within(plainRow).queryByText(/default branch/i)).toBeTruthy();+ expect(within(plainRow).queryByText("release/2026-09")).toBeNull();+ });++ // The field asks for a branch because a pinned start is also the PR target,+ // and a commit has nothing to merge back into. Only a full-length object id+ // is refused — `v1.2.3` is a legal branch name, so the rest cannot be told+ // apart without asking the remote, which the product does not do.+ it("declines a pasted commit id and points at the per-task escape hatch", () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getAllByTitle(/change the branch tasks work on/i)[0]!);+ fireEvent.change(screen.getByLabelText(/starting branch/i), {+ target: { value: "5e0b1cfa0a7d6a1a0f4b3f2e1d0c9b8a7f6e5d4c" },+ });++ const save = screen.getByRole("button", { name: /^save$/i }) as HTMLButtonElement;+ expect(save.disabled).toBe(true);+ expect(screen.getByText(/commit, not a branch/i)).toBeTruthy();+ expect(screen.getByText(/--ref/)).toBeTruthy();+ expect(updateMock).not.toHaveBeenCalled();+ });++ it("still accepts a tag-shaped name — it could be a branch, and only the remote knows", async () => {+ renderWithI18n(<ProjectResourcesSection projectId="p1" />);++ fireEvent.click(screen.getAllByTitle(/change the branch tasks work on/i)[0]!);+ fireEvent.change(screen.getByLabelText(/starting branch/i), {+ target: { value: "v1.4.0" },+ });+ fireEvent.click(screen.getByRole("button", { name: /^save$/i }));++ await waitFor(() => expect(updateMock).toHaveBeenCalledTimes(1));+ });+});diff --git a/packages/views/projects/components/project-resources-section.tsx b/packages/views/projects/components/project-resources-section.tsxindex ab27dc5738..e1804af070 100644--- a/packages/views/projects/components/project-resources-section.tsx+++ b/packages/views/projects/components/project-resources-section.tsx@@ -19,6 +19,7 @@ import {useDeleteProjectResource,useUpdateProjectResource,} from "@multica/core/projects";+import { splitGithubUrlRef } from "@multica/core/github";import { useWorkspaceId } from "@multica/core/hooks";import { useCurrentWorkspace } from "@multica/core/paths";import type {@@ -55,6 +56,8 @@ import {LocalDirectoryModeDialog,type WorktreeUnavailableReason,} from "./local-directory-mode-dialog";+import { GithubRefDialog } from "./github-ref-dialog";+import { GithubRefField, githubRefHasError } from "./github-ref-field";import { localDirectoryLabel } from "./local-directory-label";import { useT } from "../../i18n";import { githubShortLabel } from "../../common/github-url";@@ -102,6 +105,10 @@ type ModeDialogState = {label?: string;};+type RefDialogState = {+ resource: ProjectResource & { resource_ref: GithubRepoResourceRef };+};+export function ProjectResourcesSection({ projectId }: { projectId: string }) {const { t } = useT("projects");const wsId = useWorkspaceId();@@ -114,6 +121,9 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {const [modeDialog, setModeDialog] = useState<ModeDialogState | null>(null);const [modeSaving, setModeSaving] = useState(false);const [modeError, setModeError] = useState<string | null>(null);+ const [refDialog, setRefDialog] = useState<RefDialogState | null>(null);+ const [refSaving, setRefSaving] = useState(false);+ const [refError, setRefError] = useState<string | null>(null);const { data: resources = [] } = useQuery(projectResourcesOptions(wsId, projectId),@@ -173,11 +183,13 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {const filteredRepos =workspace?.repos?.filter((repo) => repo.url.toLowerCase().includes(repoQuery)) ?? [];- const handleAttach = async (url: string) => {+ const handleAttach = async (url: string, ref?: string) => {try {await createResource.mutateAsync({resource_type: "github_repo",- resource_ref: { url },+ // Omit the key entirely when empty rather than sending "": an absent+ // ref is what "use the default branch" looks like on the wire.+ resource_ref: ref ? { url, ref } : { url },});toast.success(t(($) => $.resources.toast_attached));} catch (err) {@@ -311,6 +323,45 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {}};+ const handleSaveRef = async (nextRef: string) => {+ if (!refDialog || refSaving) return;+ const ref = refDialog.resource.resource_ref;+ if ((ref.ref ?? "") === nextRef) {+ setRefDialog(null);+ return;+ }+ setRefSaving(true);+ setRefError(null);+ try {+ await updateResource.mutateAsync({+ resourceId: refDialog.resource.id,+ data: {+ // Spread first so the url and any other ref field survive the edit —+ // the server replaces the whole ref, it does not deep-merge. Clearing+ // drops the key, which is how the default branch is restored.+ resource_ref: nextRef+ ? { ...ref, ref: nextRef }+ : { ...ref, ref: undefined },+ },+ });+ toast.success(+ nextRef+ ? t(($) => $.resources.toast_ref_updated)+ : t(($) => $.resources.toast_ref_cleared),+ );+ setRefDialog(null);+ } catch (err) {+ // Keep the dialog open so the rejected value is still there to fix.+ setRefError(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.resources.toast_ref_update_failed),+ );+ } finally {+ setRefSaving(false);+ }+ };+const handleRemove = async (resource: ProjectResource) => {try {await deleteResource.mutateAsync(resource.id);@@ -383,6 +434,10 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {localDaemonId={localDaemonId}canEdit={desktopMode}onRemove={() => handleRemove(resource)}+ onEditGithubRef={(target) => {+ setRefError(null);+ setRefDialog({ resource: target });+ }}onRenameLocalDirectory={handleRenameLocalDirectory}onEditLocalDirectoryMode={(target) => {setModeError(null);@@ -483,8 +538,8 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {</>)}<CustomRepoForm- onSubmit={async (url) => {- await handleAttach(url);+ onSubmit={async (url, ref) => {+ await handleAttach(url, ref);setAddOpen(false);}}/>@@ -523,6 +578,22 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {)}</div>)}+ {refDialog && (+ <GithubRefDialog+ open+ onOpenChange={(next) => {+ if (!next) {+ setRefDialog(null);+ setRefError(null);+ }+ }}+ url={refDialog.resource.resource_ref.url}+ value={refDialog.resource.resource_ref.ref ?? ""}+ errorMessage={refError ?? undefined}+ saving={refSaving}+ onConfirm={(next) => void handleSaveRef(next)}+ />+ )}{modeDialog && (<LocalDirectoryModeDialogopen@@ -580,6 +651,9 @@ interface ResourceRowProps {localDaemonId: string | null;canEdit: boolean;onRemove: () => void;+ onEditGithubRef: (+ resource: ProjectResource & { resource_ref: GithubRepoResourceRef },+ ) => void;onRenameLocalDirectory: (resource: ProjectResource & { resource_ref: LocalDirectoryResourceRef },nextLabel: string,@@ -594,40 +668,78 @@ function ResourceRow({localDaemonId,canEdit,onRemove,+ onEditGithubRef,onRenameLocalDirectory,onEditLocalDirectoryMode,}: ResourceRowProps) {const { t } = useT("projects");if (isGithubRef(resource)) {const ref = resource.resource_ref;- const display = resource.label || (ref.ref ? `${githubShortLabel(ref.url)} @ ${ref.ref}` : githubShortLabel(ref.url));+ const display = resource.label || githubShortLabel(ref.url);const tooltip = ref.ref ? `${ref.url}\nref: ${ref.ref}` : ref.url;return (- <div className="flex items-center gap-2 text-caption group">- <FolderGit className="size-3.5 text-muted-foreground shrink-0" />+ <div className="text-caption group">+ <div className="flex items-center gap-2">+ <FolderGit className="size-3.5 text-muted-foreground shrink-0" />+ <Tooltip>+ <TooltipTrigger+ render={+ <a+ href={ref.url}+ target="_blank"+ rel="noopener noreferrer"+ className="truncate min-w-0 flex-1 hover:underline"+ >+ {display}+ </a>+ }+ />+ <TooltipContent side="top" className="whitespace-pre-line">{tooltip}</TooltipContent>+ </Tooltip>+ <button+ type="button"+ onClick={() => onEditGithubRef(resource)}+ className="opacity-0 group-hover:opacity-100 transition-opacity rounded-sm p-0.5 hover:bg-accent"+ title={t(($) => $.resources.ref_edit_tooltip)}+ >+ <GitBranch className="size-3 text-muted-foreground" />+ </button>+ <button+ type="button"+ onClick={onRemove}+ className="opacity-0 group-hover:opacity-100 transition-opacity rounded-sm p-0.5 hover:bg-accent"+ title={t(($) => $.resources.remove_tooltip)}+ >+ <Trash2 className="size-3 text-muted-foreground" />+ </button>+ </div>+ {/* Its own line rather than appended to the link text: a custom label+ takes that slot, and this panel is narrow enough that an inline+ badge truncates the repository name away — which is exactly when+ someone needs to read both.++ Rendered even when nothing is pinned, showing "Default branch".+ Without it, clearing a branch makes the line vanish, which reads+ the same as the setting never having existed — there is no way to+ confirm from the panel that the repo is deliberately on its+ default, or that this row has a branch setting at all. */}<Tooltip><TooltipTriggerrender={- <a- href={ref.url}- target="_blank"- rel="noopener noreferrer"- className="truncate flex-1 hover:underline"- >- {display}- </a>+ <div className="flex items-center gap-1 pl-[1.375rem] text-micro text-muted-foreground">+ <GitBranch className="size-3 shrink-0" />+ <span className="truncate">+ {ref.ref || t(($) => $.resources.ref_default_label)}+ </span>+ </div>}/>- <TooltipContent side="top" className="whitespace-pre-line">{tooltip}</TooltipContent>+ <TooltipContent side="top">+ {ref.ref+ ? t(($) => $.resources.ref_badge_tooltip, { ref: ref.ref })+ : t(($) => $.resources.ref_default_tooltip)}+ </TooltipContent></Tooltip>- <button- type="button"- onClick={onRemove}- className="opacity-0 group-hover:opacity-100 transition-opacity rounded-sm p-0.5 hover:bg-accent"- title={t(($) => $.resources.remove_tooltip)}- >- <Trash2 className="size-3 text-muted-foreground" />- </button></div>);}@@ -816,41 +928,71 @@ function LocalDirectoryRow({function CustomRepoForm({onSubmit,}: {- onSubmit: (url: string) => Promise<void> | void;+ onSubmit: (url: string, ref?: string) => Promise<void> | void;}) {const { t } = useT("projects");const [url, setUrl] = useState("");+ const [ref, setRef] = useState("");const [submitting, setSubmitting] = useState(false);+ const refInvalid = githubRefHasError(ref);++ // Someone who wants a branch copies it out of the address bar, so a pasted+ // .../tree/<branch> URL is split into its two halves here rather than stored+ // whole as a clone URL that does not exist. The result lands in the visible+ // fields, so a wrong guess is obvious before anything is saved.+ //+ // Normalising the URL is unconditional. Gating it on the branch field being+ // empty meant a second pasted browse URL was stored whole. Whether to+ // overwrite the BRANCH is the separate question, and the pasted pair wins:+ // the branch field only appears once a URL is present, so a value sitting in+ // it came from the previous URL rather than from something typed ahead.+ const handleUrlChange = (next: string) => {+ const split = splitGithubUrlRef(next);+ setUrl(split.url);+ if (split.ref) setRef(split.ref);+ };+const handle = async (e: React.FormEvent) => {e.preventDefault();- const trimmed = url.trim();- if (!trimmed) return;+ const trimmedUrl = url.trim();+ const trimmedRef = ref.trim();+ if (!trimmedUrl || refInvalid) return;setSubmitting(true);try {- await onSubmit(trimmed);+ await onSubmit(trimmedUrl, trimmedRef || undefined);setUrl("");+ setRef("");} finally {setSubmitting(false);}};return (- <form onSubmit={handle} className="flex items-center gap-1.5 pt-1 border-t">- <input- type="text"- value={url}- onChange={(e) => setUrl(e.target.value)}- placeholder={t(($) => $.resources.url_placeholder)}- className="flex-1 bg-transparent text-caption px-2 py-1 outline-none placeholder:text-muted-foreground"- />- <Button- type="submit"- size="sm"- variant="ghost"- className="h-6 px-2 text-caption"- disabled={!url.trim() || submitting}- >- {t(($) => $.resources.url_submit)}- </Button>+ <form onSubmit={handle} className="space-y-1.5 pt-1 border-t">+ <div className="flex items-center gap-1.5">+ <input+ type="text"+ value={url}+ onChange={(e) => handleUrlChange(e.target.value)}+ aria-label={t(($) => $.resources.popover_title)}+ placeholder={t(($) => $.resources.url_placeholder)}+ className="flex-1 min-w-0 bg-transparent text-caption px-2 py-1 outline-none placeholder:text-muted-foreground"+ />+ <Button+ type="submit"+ size="sm"+ variant="ghost"+ className="h-6 px-2 text-caption"+ disabled={!url.trim() || refInvalid || submitting}+ >+ {t(($) => $.resources.url_submit)}+ </Button>+ </div>+ {/* Only after a URL is entered: an empty attach form should still read as+ one field, and the default branch is the right answer often enough+ that this must not look like a second required step. */}+ {url.trim() && (+ <GithubRefField id="attach-repo-ref" value={ref} onChange={setRef} />+ )}</form>);}diff --git a/server/internal/daemon/execenv/runtime_config_repo_ref_test.go b/server/internal/daemon/execenv/runtime_config_repo_ref_test.gonew file mode 100644index 0000000000..1f38471fa8--- /dev/null+++ b/server/internal/daemon/execenv/runtime_config_repo_ref_test.go@@ -0,0 +1,202 @@+package execenv++import (+ "strings"+ "testing"+)++// A project pins a repo to a branch because its work lives on that line+// (MUL-7504). The daemon already checks the repo out there, so the two things+// the BRIEF has to add are the ones the agent cannot infer from a working+// directory: which line it is on, and that delivery goes back to the same one.+//+// The second matters most. Nothing in the platform creates pull requests —+// `gh pr create` is the agent's own call, and without --base it targets the+// repository's default branch. A PR opened that way asks to merge into the+// wrong place AND carries every commit the pinned branch has that the default+// lacks.+func TestRepositoriesSectionCarriesPinnedRefAndDeliveryTarget(t *testing.T) {+ t.Parallel()+ ctx := TaskContextForEnv{+ IssueID: "i-1", AgentName: "Eve", AgentID: "eve-1",+ Repos: []RepoContextForEnv{+ {URL: "https://github.com/multica-ai/multica", Ref: "release/2026-09"},+ },+ }+ out := buildMetaSkillContent("claude", ctx)++ if !strings.Contains(out, "https://github.com/multica-ai/multica (starts from `release/2026-09`)") {+ t.Errorf("Repositories section should name the pinned ref beside its repo; got:\n%s", out)+ }+ if !strings.Contains(out, "gh pr create --base") {+ t.Errorf("brief should tell the agent to target the same branch when delivering; got:\n%s", out)+ }+ // A pin is already applied on checkout. An agent that re-passes --ref to+ // "get back to" the branch is doing redundant work at best, and pinning a+ // stale value at worst.+ if !strings.Contains(out, "do not pass `--ref` to get back to it") {+ t.Errorf("brief should say the checkout is already at the pinned ref; got:\n%s", out)+ }+}++// The delivery rule is stated only when something is actually pinned. An+// unpinned workspace repo already starts from its default branch, and+// `gh pr create` already targets that — an unconditional --base instruction+// would be noise in the common case.+func TestRepositoriesSectionOmitsDeliveryRuleWhenNothingIsPinned(t *testing.T) {+ t.Parallel()+ ctx := TaskContextForEnv{+ IssueID: "i-1", AgentName: "Eve", AgentID: "eve-1",+ Repos: []RepoContextForEnv{+ {URL: "https://github.com/multica-ai/multica", Description: "the platform"},+ },+ }+ out := buildMetaSkillContent("claude", ctx)++ if !strings.Contains(out, "https://github.com/multica-ai/multica — the platform") {+ t.Errorf("unpinned repo should still render its description; got:\n%s", out)+ }+ if strings.Contains(out, "starts from") || strings.Contains(out, "gh pr create --base") {+ t.Errorf("no repo is pinned, so the brief must not mention a starting point or --base; got:\n%s", out)+ }+}++// A pin is not necessarily a branch — the field accepts anything git resolves,+// and neither the server nor the daemon can tell a branch from a tag or a+// commit without asking the remote, which the product deliberately does not do.+// A tag has no branch to merge back into, so the delivery rule has to be stated+// conditionally rather than as "always --base whatever is pinned".+func TestDeliveryRuleDoesNotAssumeThePinIsABranch(t *testing.T) {+ t.Parallel()+ ctx := TaskContextForEnv{+ IssueID: "i-1", AgentName: "Eve", AgentID: "eve-1",+ Repos: []RepoContextForEnv{{URL: "https://github.com/o/r", Ref: "v1.4.0"}},+ }+ out := buildMetaSkillContent("claude", ctx)++ if !strings.Contains(out, "tag or a commit rather than a branch") {+ t.Errorf("brief should carve out the tag/commit case; got:\n%s", out)+ }+ if !strings.Contains(out, "confirm the target branch") {+ t.Errorf("brief should tell the agent to confirm rather than guess a base; got:\n%s", out)+ }+}++// The Project Context bullet used to read as though --ref were how you reach+// the configured revision. It is not: the daemon applies it, and --ref is the+// override. An agent following the old wording would re-specify a value it+// already had — and would keep using a stale one after the project changed.+func TestProjectContextSaysThePinIsAlreadyApplied(t *testing.T) {+ t.Parallel()+ ctx := TaskContextForEnv{+ IssueID: "i-1", AgentName: "Eve", AgentID: "eve-1",+ ProjectID: "p-1", ProjectTitle: "Release line",+ ProjectResources: []ProjectResourceForEnv{{+ ResourceType: "github_repo",+ ResourceRef: []byte(`{"url":"https://github.com/o/r","ref":"release/2026-09"}`),+ }},+ }+ out := buildMetaSkillContent("claude", ctx)++ if !strings.Contains(out, "checked out there automatically") {+ t.Errorf("Project Context should say the configured start is applied for you; got:\n%s", out)+ }+ if !strings.Contains(out, "only to override it") {+ t.Errorf("Project Context should frame --ref as the override; got:\n%s", out)+ }+}++// A resumed task can outlive a change to the project's starting point. The+// checkout is kept as it was — holding work branched off the OLD value — while+// the brief, rebuilt from the current claim, names the new one. An agent that+// retargeted on the brief alone would deliver the old line's work into the new+// line, and would contradict what the edit dialog promises: work already+// underway keeps the branch it started on.+//+// The brief cannot resolve this itself; whether a checkout was reused is only+// known once `repo checkout` runs. So it warns, and is careful about what it+// claims the checkout can tell the agent — see the next test.+func TestDeliveryRuleWarnsAboutAKeptCheckout(t *testing.T) {+ t.Parallel()+ ctx := TaskContextForEnv{+ IssueID: "i-1", AgentName: "Eve", AgentID: "eve-1",+ Repos: []RepoContextForEnv{{URL: "https://github.com/o/r", Ref: "release/b"}},+ }+ out := buildMetaSkillContent("claude", ctx)++ if !strings.Contains(out, "KEPT an existing checkout") {+ t.Errorf("brief should name the kept-checkout case; got:\n%s", out)+ }+ if !strings.Contains(out, "Do not retarget it to a starting point listed above") {+ t.Errorf("brief should say the listed starting point is not authoritative on a resume; got:\n%s", out)+ }+}++// A kept checkout reports the branch the worktree is ON — the task's own+// `agent/...` branch, resolved by `git symbolic-ref`. That is the HEAD of a+// pull request, never its base, and nothing in the result carries the ref the+// branch was cut from.+//+// An earlier revision of this text said to deliver "to the branch it actually+// started from, which the checkout names". An agent following that would read+// the `agent/...` branch and pass it as --base, producing a pull request whose+// base equals its head. The brief must not name the checkout as a source for+// the original target at all.+func TestKeptCheckoutIsNotOfferedAsTheDeliveryTarget(t *testing.T) {+ t.Parallel()+ ctx := TaskContextForEnv{+ IssueID: "i-1", AgentName: "Eve", AgentID: "eve-1",+ Repos: []RepoContextForEnv{{URL: "https://github.com/o/r", Ref: "release/b"}},+ }+ out := buildMetaSkillContent("claude", ctx)++ if strings.Contains(out, "which the checkout names") {+ t.Errorf("brief must not point at the checkout for the original target; got:\n%s", out)+ }+ if !strings.Contains(out, "head of a pull request, never its base") {+ t.Errorf("brief should say what the reported branch actually is; got:\n%s", out)+ }+ // The sources that DO settle it.+ if !strings.Contains(out, "the base of its existing pull request") {+ t.Errorf("brief should point at the existing PR's base; got:\n%s", out)+ }+ if !strings.Contains(out, "ask if neither settles it") {+ t.Errorf("brief should tell the agent to ask rather than guess; got:\n%s", out)+ }+}++// The resume warning does NOT ride with the pin. A project cleared back to its+// default branch renders no starting point at all, yet a task resumed after+// that change still holds a checkout cut from the old one — so gating the+// warning on `pinned` would drop it exactly where the mismatch is invisible.+func TestResumeWarningSurvivesTheStartingPointBeingCleared(t *testing.T) {+ t.Parallel()+ ctx := TaskContextForEnv{+ IssueID: "i-1", AgentName: "Eve", AgentID: "eve-1",+ Repos: []RepoContextForEnv{{URL: "https://github.com/o/r"}}, // A -> cleared+ }+ out := buildMetaSkillContent("claude", ctx)++ if !strings.Contains(out, "KEPT an existing checkout") {+ t.Errorf("resume warning must survive a cleared starting point; got:\n%s", out)+ }+ // The pinned-only halves stay out: there is no branch to target, and+ // nothing listed above to be warned off retargeting to.+ if strings.Contains(out, "gh pr create --base") {+ t.Errorf("nothing is pinned, so the --base rule is noise; got:\n%s", out)+ }+ if strings.Contains(out, "Do not retarget it to a starting point listed above") {+ t.Errorf("nothing is listed above, so the sentence points at nothing; got:\n%s", out)+ }+}++// No repos, nothing to say — the section is skipped whole.+func TestResumeWarningAbsentWithoutRepos(t *testing.T) {+ t.Parallel()+ out := buildMetaSkillContent("claude", TaskContextForEnv{+ IssueID: "i-1", AgentName: "Eve", AgentID: "eve-1",+ })+ if strings.Contains(out, "KEPT an existing checkout") {+ t.Errorf("no repositories, so no checkout guidance; got:\n%s", out)+ }+}diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex 5a711ecbaf..21ca3b92f3 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -423,12 +423,66 @@ func writeRepositories(b *strings.Builder, ctx TaskContextForEnv) {}b.WriteString("## Repositories\n\n")b.WriteString("Available in this workspace — `multica repo checkout <url> [--ref <branch-or-sha>]` to fetch (creates a repository checkout on a dedicated branch).\n\n")+ pinned := falsefor _, repo := range ctx.Repos {+ line := "- " + repo.URLif repo.Description != "" {- fmt.Fprintf(b, "- %s — %s\n", repo.URL, repo.Description)- } else {- fmt.Fprintf(b, "- %s\n", repo.URL)+ line += " — " + repo.Description+ }+ // The ref is already applied by the daemon on checkout. It is printed+ // here so the agent knows which line of work it is on without running+ // `git branch` first, and — more importantly — so it can target the+ // same branch when it delivers. Without this the repo reads as if it+ // were on the default branch.+ if ref := strings.TrimSpace(repo.Ref); ref != "" {+ pinned = true+ line += fmt.Sprintf(" (starts from `%s`)", ref)}+ b.WriteString(line + "\n")+ }+ if pinned {+ // A project pins a repo because its work lives on that line, so a pull+ // request that silently targets the repo's default branch is wrong+ // twice over: it asks to merge into the wrong place, and its diff+ // carries every commit the pinned branch has that the default lacks.+ // `gh pr create` defaults to the repo default branch, so the agent has+ // to pass --base itself — nothing in the platform sets it.+ //+ // Stated conditionally because a pin is not necessarily a branch: the+ // field accepts anything git resolves, and a tag or commit has no+ // branch to merge back into. Neither the server nor the daemon can+ // tell the three apart without asking the remote, which the product+ // deliberately does not do, so the agent resolves it at the point it+ // already has the repository in hand.+ b.WriteString("\nA repository that starts from a branch is already checked out there — do not pass `--ref` to get back to it. ")+ b.WriteString("Deliver to the same line: open pull requests with `gh pr create --base <that-branch>`. ")+ b.WriteString("If what it starts from is a tag or a commit rather than a branch, treat it as a starting point only and confirm the target branch before opening a pull request.\n")+ }+ // Stated for ANY repo, pinned or not, because it protects work that began+ // under a setting this brief can no longer see. A project cleared back to+ // its default branch renders no starting point at all, yet a task resumed+ // afterwards still holds a checkout cut from the old one — so gating this+ // on `pinned` would drop the warning exactly where the mismatch is+ // invisible.+ //+ // What it must NOT do is name a source for the original target. A kept+ // checkout reports the branch the worktree is ON, which is the task's own+ // `agent/...` branch — the HEAD of a pull request, never its base. Nothing+ // in the checkout result carries the ref that branch was cut from. Telling+ // the agent to read the target "from the checkout" produces a base equal+ // to the head; the honest instruction is to keep the target the work+ // already had, and to ask when nothing states it.+ if len(ctx.Repos) > 0 {+ b.WriteString("\nIf `multica repo checkout` reports that it KEPT an existing checkout, you are continuing work that began earlier — possibly before this project was last reconfigured. ")+ b.WriteString("The branch it names is the branch your work sits ON: the head of a pull request, never its base. It does not record where that work was meant to land. ")+ b.WriteString("Keep delivering where this work was already going — the base of its existing pull request, or the target the task states — and ask if neither settles it.")+ if pinned {+ // Only meaningful when something IS listed above. With the+ // starting point cleared there is nothing to be retargeted to,+ // and the sentence would point at a line that is not there.+ b.WriteString(" Do not retarget it to a starting point listed above: that is the project's current setting, which may have changed since this work began.")+ }+ b.WriteString("\n")}b.WriteString("\n")}@@ -456,7 +510,8 @@ func writeProjectContext(b *strings.Builder, ctx TaskContextForEnv) {fmt.Fprintf(b, "- %s\n", formatProjectResource(r))}b.WriteString("\nResources are pointers — open them only when relevant to the task. ")- b.WriteString("For `github_repo` resources, use `multica repo checkout <url>` to fetch the code. Add `--ref <branch-or-sha>` when a task or handoff names an exact revision.\n\n")+ b.WriteString("For `github_repo` resources, use `multica repo checkout <url>` to fetch the code. ")+ b.WriteString("A resource listing a starting point is checked out there automatically — pass `--ref <branch-or-sha>` only to override it, when a task or handoff names a different revision.\n\n")} else {b.WriteString("This project has no resources attached yet.\n\n")}diff --git a/server/internal/handler/project_resource.go b/server/internal/handler/project_resource.goindex 6756d34a7f..525a6fb7e0 100644--- a/server/internal/handler/project_resource.go+++ b/server/internal/handler/project_resource.go@@ -105,6 +105,9 @@ func validateGithubRepoRef(ref json.RawMessage) (json.RawMessage, error) {}payload.DefaultBranchHint = strings.TrimSpace(payload.DefaultBranchHint)payload.Ref = strings.TrimSpace(payload.Ref)+ if err := validateGitRef(payload.Ref); err != nil {+ return nil, fmt.Errorf("github_repo: %w", err)+ }out, err := json.Marshal(payload)if err != nil {return nil, err@@ -404,6 +407,60 @@ func isDriveLetter(b byte) bool {return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')}+// gitRefMaxLength caps the stored checkout ref. Git's own limit is the+// filesystem's, but a loose ref has to fit in a file name, so 255 is the+// conservative ceiling every platform honors — far past any real branch name.+// The cap exists to stop a pasted document from reaching the database, not to+// police naming.+const gitRefMaxLength = 255++// validateGitRef rejects input git itself could never resolve, and nothing+// more. It mirrors the subset of `git check-ref-format` that applies to a ref a+// user types, so every branch, tag and commit SHA we advertise stays+// acceptable — the check is about SHAPE only.+//+// Whether the ref exists on the remote is a different question, answered at+// checkout time by the daemon. It must not gate saving project config: the+// daemon may be offline, the repository may be private, and the server cannot+// inspect the repository at all. An empty ref is valid and means "use the+// repository's default branch".+//+// Keep in sync with validateGitRef in packages/core/github/repo-ref.ts, which+// gives the same verdict in the UI before the request is sent.+func validateGitRef(ref string) error {+ if ref == "" {+ return nil+ }+ if len(ref) > gitRefMaxLength {+ return fmt.Errorf("ref must be at most %d characters", gitRefMaxLength)+ }+ // ASCII control characters, DEL, space, and the characters git reserves+ // for its own revision syntax.+ for _, r := range ref {+ if r <= ' ' || r == '\x7f' || strings.ContainsRune("~^:?*[\\", r) {+ return errors.New("ref must not contain spaces, control characters, or any of ~ ^ : ? * [ \\")+ }+ }+ // Path-shape rules. "@{" is reflog syntax, a lone "@" is shorthand for+ // HEAD, ".." would read as a range, and ".lock" is what git names its own+ // lock files.+ if strings.Contains(ref, "..") ||+ strings.Contains(ref, "@{") ||+ ref == "@" ||+ strings.HasPrefix(ref, "/") ||+ strings.HasSuffix(ref, "/") ||+ strings.Contains(ref, "//") ||+ strings.HasSuffix(ref, ".") {+ return errors.New("ref is not a valid branch, tag, or commit")+ }+ for _, segment := range strings.Split(ref, "/") {+ if strings.HasPrefix(segment, ".") || strings.HasSuffix(segment, ".lock") {+ return errors.New("ref is not a valid branch, tag, or commit")+ }+ }+ return nil+}+// isValidGitRepoURL accepts the three forms a user can paste from GitHub's// "Code" menu: https://, ssh:// (with explicit scheme), and the scp-like// shorthand `git@host:owner/repo.git`. The check is intentionally lax — we arediff --git a/server/internal/handler/project_resource_test.go b/server/internal/handler/project_resource_test.goindex 3265409cfb..70a441363c 100644--- a/server/internal/handler/project_resource_test.go+++ b/server/internal/handler/project_resource_test.go@@ -1697,3 +1697,185 @@ func TestProjectResourceLegacyRenameSkipsWorktreeGate(t *testing.T) {t.Fatalf("switching to in_place needs no capability: %d %s", w.Code, w.Body.String())}}++// TestValidateGitRef pins the shape-only contract for a github_repo checkout+// ref: every branch, tag and SHA we tell users they can type must pass, and+// only input git itself could never resolve is rejected. Existence on the+// remote is deliberately NOT checked here — the server cannot see the+// repository, and a private repo or an offline daemon must not block saving+// project configuration.+//+// Mirrors packages/core/github/repo-ref.test.ts.+func TestValidateGitRef(t *testing.T) {+ good := []string{+ "", // empty means "use the repository's default branch"+ "main",+ "release/2026-09",+ "team/alice/feat/new-thing",+ "v1.2.3",+ "a1b2c3d",+ "5e0b1cfa0a7d6a1a0f4b3f2e1d0c9b8a7f6e5d4c",+ "release.2026.09",+ "fix/MUL-7504-pin-ref",+ strings.Repeat("a", gitRefMaxLength),+ }+ bad := []string{+ "my branch", // space+ "main~1", // revision syntax+ "main^", // revision syntax+ "origin:main", // revision syntax+ "main?",+ "refs/heads/*",+ "feat\\thing",+ "ma\nin", // interior control character+ "main..dev", // reads as a range+ "main@{1}", // reflog syntax+ "@", // shorthand for HEAD+ "/main",+ "main/",+ "feat//thing",+ ".hidden",+ "main.",+ "main.lock",+ "feat.lock/thing",+ "feat/.hidden",+ strings.Repeat("a", gitRefMaxLength+1),+ }+ for _, s := range good {+ if err := validateGitRef(s); err != nil {+ t.Errorf("validateGitRef(%q) = %v, want nil", s, err)+ }+ }+ for _, s := range bad {+ if err := validateGitRef(s); err == nil {+ t.Errorf("validateGitRef(%q) = nil, want an error", s)+ }+ }+}++// A bad ref must be refused at save time with a 400, not stored and left to+// blow up mid-task: the daemon surfaces an unresolvable ref as a 500 whose+// message points at its local repo cache, minutes after the person who typed+// it has moved on.+func TestProjectResourceRejectsInvalidCheckoutRef(t *testing.T) {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Invalid ref project",+ })+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateProject: expected 201, got %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() {+ req := newRequest("DELETE", "/api/projects/"+project.ID, nil)+ req = withURLParam(req, "id", project.ID)+ testHandler.DeleteProject(httptest.NewRecorder(), req)+ }()++ create := func(ref string) *httptest.ResponseRecorder {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects/"+project.ID+"/resources", map[string]any{+ "resource_type": "github_repo",+ "resource_ref": map[string]any{+ "url": "https://github.com/multica-ai/multica",+ "ref": ref,+ },+ })+ req = withURLParam(req, "id", project.ID)+ testHandler.CreateProjectResource(w, req)+ return w+ }++ if w := create("main..dev"); w.Code != http.StatusBadRequest {+ t.Fatalf("create with invalid ref: expected 400, got %d: %s", w.Code, w.Body.String())+ }++ // The valid-ref path still works, and the ref round-trips.+ w = create("release/2026-09")+ if w.Code != http.StatusCreated {+ t.Fatalf("create with valid ref: expected 201, got %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)+ }+ var stored githubRepoRef+ if err := json.Unmarshal(created.ResourceRef, &stored); err != nil {+ t.Fatalf("decode stored ref: %v", err)+ }+ if stored.Ref != "release/2026-09" {+ t.Fatalf("stored ref = %q, want %q", stored.Ref, "release/2026-09")+ }++ // Update is gated by the same rule, and a rejected update leaves the+ // stored ref alone rather than half-applying.+ w = httptest.NewRecorder()+ req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, map[string]any{+ "resource_ref": map[string]any{+ "url": "https://github.com/multica-ai/multica",+ "ref": "not a ref",+ },+ })+ req = withURLParams(req, "id", project.ID, "resourceId", created.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("update with invalid ref: expected 400, got %d: %s", w.Code, w.Body.String())+ }++ w = httptest.NewRecorder()+ req = newRequest("GET", "/api/projects/"+project.ID+"/resources", nil)+ req = withURLParam(req, "id", project.ID)+ testHandler.ListProjectResources(w, req)+ var list struct {+ Resources []ProjectResourceResponse `json:"resources"`+ Total int `json:"total"`+ }+ if err := json.NewDecoder(w.Body).Decode(&list); err != nil {+ t.Fatalf("decode ListProjectResources: %v", err)+ }+ if len(list.Resources) != 1 {+ t.Fatalf("expected 1 resource, got %d", len(list.Resources))+ }+ var afterReject githubRepoRef+ if err := json.Unmarshal(list.Resources[0].ResourceRef, &afterReject); err != nil {+ t.Fatalf("decode stored ref after rejected update: %v", err)+ }+ if afterReject.Ref != "release/2026-09" {+ t.Fatalf("ref after rejected update = %q, want it unchanged at %q", afterReject.Ref, "release/2026-09")+ }++ // Clearing the ref is how a user goes back to the default branch.+ w = httptest.NewRecorder()+ req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, map[string]any{+ "resource_ref": map[string]any{+ "url": "https://github.com/multica-ai/multica",+ "ref": "",+ },+ })+ req = withURLParams(req, "id", project.ID, "resourceId", created.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("clear ref: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var cleared ProjectResourceResponse+ if err := json.NewDecoder(w.Body).Decode(&cleared); err != nil {+ t.Fatalf("decode cleared: %v", err)+ }+ // Fresh struct on purpose: json.Unmarshal leaves a field untouched when+ // its key is absent, and "ref" is omitempty — reusing `stored` here would+ // read back the previous value and pass no matter what the server wrote.+ var clearedRef githubRepoRef+ if err := json.Unmarshal(cleared.ResourceRef, &clearedRef); err != nil {+ t.Fatalf("decode cleared ref: %v", err)+ }+ if clearedRef.Ref != "" {+ t.Fatalf("ref after clear = %q, want empty", clearedRef.Ref)+ }+ if clearedRef.URL != "https://github.com/multica-ai/multica" {+ t.Fatalf("url after clearing the ref = %q, want it preserved", clearedRef.URL)+ }+}