Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(update): keep user changes, name conflicts, and drop the install pill (#140)
Abdurrahman Fakhrulc54422e42dde
diff --git a/app/install-prompt.tsx b/app/install-prompt.tsxdeleted file mode 100644index e503fe94..00000000--- a/app/install-prompt.tsx+++ /dev/null@@ -1,56 +0,0 @@-"use client";--import { useEffect, useState } from "react";-import { Download, X } from "lucide-react";-import { Button } from "@/components/ui/button";--// Native install affordance. Chromium fires `beforeinstallprompt` when the PWA-// is installable; we stash it and show a one-tap "Install" pill (browsers-// otherwise bury the action in a menu). iOS Safari has no such event — it uses-// Share → Add to Home Screen, so nothing renders there. Dismiss is per-session.-type BeforeInstallPromptEvent = Event & {- prompt: () => Promise<void>;- userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;-};--export function InstallPrompt() {- const [evt, setEvt] = useState<BeforeInstallPromptEvent | null>(null);- const [hidden, setHidden] = useState(false);-- useEffect(() => {- const onPrompt = (e: Event) => {- e.preventDefault(); // keep the event so we can trigger it from our own UI- setEvt(e as BeforeInstallPromptEvent);- };- const onInstalled = () => setEvt(null);- window.addEventListener("beforeinstallprompt", onPrompt);- window.addEventListener("appinstalled", onInstalled);- return () => {- window.removeEventListener("beforeinstallprompt", onPrompt);- window.removeEventListener("appinstalled", onInstalled);- };- }, []);-- if (!evt || hidden) return null;-- const install = async () => {- await evt.prompt();- await evt.userChoice.catch(() => undefined);- setEvt(null);- };-- return (- <div data-slot="pwa-install-prompt" className="pointer-events-none fixed inset-x-0 z-[var(--z-spotlight)] flex justify-center px-4" style={{ bottom: "calc(8.5rem + var(--sai-bottom, 0px))" }}>- <div className="glass pointer-events-auto flex items-center gap-2 rounded-2xl border border-border bg-card/90 px-3 py-2 shadow-[var(--shadow-win)]">- <Download className="size-4 shrink-0 text-primary" />- <span className="text-sm">Install Manef Shell OS as an app</span>- <Button type="button" size="sm" onClick={install} className="ml-1">- Install- </Button>- <Button type="button" size="icon" variant="ghost" aria-label="Dismiss" onClick={() => setHidden(true)}>- <X className="size-4" />- </Button>- </div>- </div>- );-}diff --git a/app/layout.tsx b/app/layout.tsxindex 77785828..04980010 100644--- a/app/layout.tsx+++ b/app/layout.tsx@@ -3,7 +3,6 @@ import { headers } from "next/headers";import { GeistSans } from "geist/font/sans";import { GeistMono } from "./mono-font";import { RegisterSW } from "./register-sw";-import { InstallPrompt } from "./install-prompt";import "./globals.css";import { BootSplash } from "./boot-splash";import { publicMsoOrigin } from "@/lib/mcp/ui-config";@@ -95,7 +94,6 @@ export default async function RootLayout({<BootSplash />{children}<RegisterSW />- <InstallPrompt /></body></html>);diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex ef4e1dc8..61e6fd68 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -333,6 +333,51 @@ future archaeology task.Each MSO connector/server scope owns its own Page app catalog. Core MSO Page code must not import project identities or trusted frame origins from another server scope. Portable source ships with an empty external-app catalog. An installation may opt into reviewed apps through the bounded owner-local `~/.mso/surface-apps.json` registry (or an explicit `MSO_SURFACE_APPS_JSON` override); MSO re-reads the registry when the Page resource is read and validates each exact HTTPS origin, approved start-path prefix, renderer, sandbox, and presentation before it can enter Page CSP. The dedicated widget origin is installation-derived from `OS_MCP_UI_ORIGIN` / `OS_PUBLIC_ORIGIN`. The Block resource has no frame domains.+## Foundation vs user customizations++An update must never silently disturb a user's own work on their MSO. This section+describes the boundary that already exists; it does not create directories or a new+extension mechanism.++**MSO foundation — owned by the updater, replaced wholesale by `git pull`:**++| Path | What it is |+|---|---|+| `app/` | Next.js routes, OAuth endpoints, public install surface |+| `lib/` | Host, auth, MCP, infra and managed-app authorities |+| `components/` | Shared UI primitives used by every slice |+| `scripts/` | Install, release gates, service/updater helpers, terminal agent |+| `frontend/slices/` core | The shipped slices (`appshell`, `os-shell`, `os-settings`, …) and their contracts |+| `schemas/` | Versioned JSON schemas for portable bundles |+| `templates/` | Shipped app / skill-flow templates |++A user edit inside these paths is replaced by the next update. That is intended for+foundation code, and it is exactly why the update path must name such a file before it+is replaced (below).++**User extension points — an update must never clobber these silently:**++- **Per-user private state under `~/.mso`** — preferences, credential/integration+ connections, workflow persistence, update state and logs. It lives outside the+ checkout, so `git pull` cannot reach it and no update step may move it into the repo.+- **Their own worktree branches** — `agent/*` worktrees under `~/.cache/mso-worktrees`+ and any branch the user created. An update moves `main`; it does not rewrite, prune,+ merge or delete another branch.+- **Local commits they carry** — commits on `main` that are not on the target. MSO+ refuses to fast-forward over them and reports ahead/behind instead.++Custom *features* are therefore expressed either as state under `~/.mso` (never+overwritten) or as local commits/branches (never overwritten, only reported). A+customization made by editing foundation files directly is carried but not protected:+it is precisely what the preflight has to surface.++**The rule:** an update that would touch a user-modified file must name that file+BEFORE updating, never after. `lib/host/update-conflict.ts` implements the read-only+preflight (`git merge-tree`, no index/worktree/HEAD write) that produces the list,+`UpdateStatus.conflict` carries it to Settings, and `updateConflictPrompt()` hands the+operator a paste-ready instruction when files actually conflict. Reporting after a+failed build describes damage instead of preventing it.+## Server-native workflow graph## Organization and agent routingdiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 7489bc6b..98293c9e 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,28 @@+## 2026-10-22: Updates check the merge before refusing, and the foundation boundary is written down++A dirty or diverged checkout used to get a bare refusal, leaving a user who simply wanted the+newest MSO with a stash-or-nothing choice. `lib/host/update-conflict.ts` now runs a READ-ONLY+preflight with `git merge-tree --write-tree --name-only --no-messages HEAD <target>` (git 2.43):+that computes the merge in memory, so no index, worktree, stash or HEAD is touched, and only+throwaway tree objects land in `.git/objects`. It reports `conflicted` (what git cannot merge),+`carried` (the user's committed + uncommitted + untracked files since the merge base) and+`overlap` (carried ∩ incoming). `safe` requires a clean merge-tree exit AND no overlap, because+merge-tree reads commits and cannot prove anything about uncommitted work.++`blockingReason` keeps its `string | null` contract; the new `updateRefusal` returns the same+sentence plus `conflict`, so `UpdateStatus.conflict` reaches Settings only when the checkout is+dirty or diverged and `GET /sys/update` stays a read. Settings renders the exact file list and+copies `updateConflictPrompt()` — a plain-text instruction that names the target/current commit+and every path, tells an agent to preserve `~/.mso` and local commits, and forbids+`git push --force`, `git reset --hard` and deleting user files. `docs/ARCHITECTURE.md` now states+the foundation-vs-user-customizations boundary the user requires, with the before-not-after rule.++Coverage: 9 real-git tests in `lib/host/update-conflict.test.ts` (mkdtemp 0700 fixture) prove the+three preflight states, the no-mutation invariant (HEAD, `status --porcelain`, `ls-files`,+`stash list` identical before/after) and prompt contents, plus extended decision/status tests.+The custom PWA install pill is gone (`app/install-prompt.tsx` deleted); `RegisterSW`, the+manifest and the service worker are untouched, so installability stays a browser-menu action.+## 2026-10-21: Shell-app domain provisioning (phase 1, worker B)New `lib/surfaces/app-domain-provision.ts` provisions a public hostname for a shell-app entry:diff --git a/frontend/slices/os-settings/components/update-conflict-card.tsx b/frontend/slices/os-settings/components/update-conflict-card.tsxnew file mode 100644index 00000000..1d5800db--- /dev/null+++ b/frontend/slices/os-settings/components/update-conflict-card.tsx@@ -0,0 +1,69 @@+"use client";++import { useState } from "react";+import { Copy, TriangleAlert } from "lucide-react";+import { Button } from "@/components/ui/button";+import type { UpdateConflictReport } from "@/lib/host/update-conflict";+import { updateConflictPrompt } from "@/lib/host/update-conflict";++/**+ * What the read-only preflight found when the checkout is dirty or diverged.+ * Safe means the update keeps the user's work; unsafe means it names the files and+ * hands over a prompt an AI agent can resolve immediately.+ */+export function UpdateConflictCard({+ conflict,+ target,+ current,+}: {+ conflict: UpdateConflictReport;+ target: string;+ current: string;+}) {+ const [copied, setCopied] = useState(false);+ const files = conflict.safe+ ? conflict.carried+ : conflict.conflicted.length+ ? conflict.conflicted+ : conflict.overlap;++ return (+ <div className="space-y-2 rounded-md border border-border/60 bg-background/70 p-3">+ <p className="flex items-center gap-1.5 text-[11px] font-medium text-foreground">+ <TriangleAlert className="size-3.5" />+ {conflict.safe+ ? "Your local changes carry over cleanly"+ : "This update would collide with your local changes"}+ </p>+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ {conflict.safe+ ? "Nothing to resolve: replaying them on top of the new code is a plain merge."+ : "Resolve these before updating; the update will not overwrite them silently."}+ </p>+ {files.length > 0 && (+ <ul className="space-y-0.5 font-mono text-[10px] text-foreground/85">+ {files.slice(0, 20).map((file) => (+ <li key={file} className="break-all">{file}</li>+ ))}+ {files.length > 20 && <li>+{files.length - 20} more</li>}+ </ul>+ )}+ {!conflict.safe && (+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="w-full"+ onClick={() => {+ void navigator.clipboard+ .writeText(updateConflictPrompt(conflict, { target, current }))+ .then(() => setCopied(true))+ .catch(() => setCopied(false));+ }}+ >+ <Copy className="size-4" /> {copied ? "Prompt copied" : "Copy AI fix prompt"}+ </Button>+ )}+ </div>+ );+}diff --git a/frontend/slices/os-settings/components/update-status-card.tsx b/frontend/slices/os-settings/components/update-status-card.tsxindex faadb12e..eaa64efc 100644--- a/frontend/slices/os-settings/components/update-status-card.tsx+++ b/frontend/slices/os-settings/components/update-status-card.tsx@@ -7,6 +7,7 @@ import { ScrollArea } from "@/components/ui/scroll-area";import { Skeleton } from "@/components/ui/skeleton";import { SettingsBlock } from "@/features/shell-settings";import type { UpdateStatus } from "@/lib/host/self-update";+import { UpdateConflictCard } from "./update-conflict-card";const OK_MARKER = "UPDATE OK";@@ -139,6 +140,13 @@ export function UpdateStatusCard({update is blocked until it is pushed or reconciled.</p>)}+ {info.conflict && (info.dirty || info.ahead > 0) && (+ <UpdateConflictCard+ conflict={info.conflict}+ target={info.target ?? "origin/main"}+ current={info.current || "unknown"}+ />+ )}{!info.remoteChecked && !running && (<p className="text-[11px] leading-relaxed text-amber-500">Could not reach the remote — this is what was last fetched, notdiff --git a/lib/host/self-update-status.test.ts b/lib/host/self-update-status.test.tsindex 6417aab2..55a5557c 100644--- a/lib/host/self-update-status.test.ts+++ b/lib/host/self-update-status.test.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";-const fixture = vi.hoisted(() => ({ branch: "main", fetchFails: false, noGit: false, behind: 13, tags: "", targetSha: "7cffd11" }));+const fixture = vi.hoisted(() => ({ branch: "main", fetchFails: false, noGit: false, behind: 13, tags: "", targetSha: "7cffd11", dirty: false, ahead: 0 }));vi.mock("server-only", () => ({}));vi.mock("node:fs", () => ({ promises: { readFile: vi.fn(async () => "") } }));vi.mock("@/lib/prefs/store", () => ({ readPrefs: vi.fn(async () => ({})) }));@@ -19,8 +19,13 @@ vi.mock("node:child_process", () => ({else if (key === "rev-parse --verify origin/main^{commit}") output = fixture.targetSha;else if (key === "tag --merged origin/main --list v*") output = fixture.tags;else if (args[0] === "fetch") code = fixture.fetchFails ? 1 : 0;- else if (args[0] === "rev-list") output = `0\t${fixture.behind}`;- else if (args[0] === "diff") output = "app/page.tsx";+ else if (args[0] === "rev-list") output = `${fixture.ahead}\t${fixture.behind}`;+ else if (key === "status --porcelain") output = fixture.dirty ? "M base.txt" : "";+ else if (args[0] === "merge-base") output = "abc1234def567890abc1234def567890abc12345";+ else if (key === "diff --name-only HEAD") output = fixture.dirty ? "base.txt" : "";+ else if (args[0] === "diff" && args.length === 4) output = args[3] === "HEAD" ? "" : "app/page.tsx";+ else if (args[0] === "ls-files") output = "";+ else if (args[0] === "merge-tree") { output = "2".repeat(40); code = 0; }else if (key === "log -1 --format=%s") output = "installed build";else if (args[0] === "log" && fixture.behind) output = "7cffd11\x1flatest update\x1f2026-09-12";done(code ? { code } : null, output, "");@@ -31,6 +36,7 @@ const { getUpdateStatus, blockingReason } = await import("./self-update");beforeEach(() => {fixture.branch = "main"; fixture.fetchFails = false; fixture.noGit = false;fixture.behind = 13; fixture.tags = ""; fixture.targetSha = "7cffd11";+ fixture.dirty = false; fixture.ahead = 0;});describe("version discovery independent of restart mechanism", () => {@@ -60,6 +66,37 @@ describe("version discovery independent of restart mechanism", () => {});});+describe("conflict preflight in the status payload", () => {+ it("adds a read-only conflict report when the checkout is dirty", async () => {+ fixture.dirty = true;+ const result = await getUpdateStatus(false, "main");+ expect(result.dirty).toBe(true);+ expect(result.conflict).toMatchObject({ conflicted: [], carried: ["base.txt"], overlap: [], safe: true });+ });++ it("also preflights a diverged main, not just a dirty tree", async () => {+ fixture.ahead = 2;+ const result = await getUpdateStatus(false, "main");+ expect(result).toMatchObject({ ahead: 2, behind: 13 });+ expect(result.conflict).toMatchObject({ safe: true });+ });++ it("omits the report entirely on a clean, non-diverged checkout", async () => {+ const result = await getUpdateStatus(false, "main");+ expect(result.conflict).toBeUndefined();+ });++ it("refusal stays a string, and the structured report rides alongside it", async () => {+ fixture.dirty = true;+ const result = await getUpdateStatus(false, "main");+ const refusal = blockingReason(result, false);+ expect(typeof refusal).toBe("string");+ expect(refusal).toContain("uncommitted changes");+ expect(refusal).toContain("carry over cleanly");+ expect(result.conflict?.safe).toBe(true);+ });+});+describe("stable channel", () => {it("compares against the newest release tag, not origin/main", async () => {fixture.tags = "v0.2.0\nv0.9.0";diff --git a/lib/host/self-update.ts b/lib/host/self-update.tsindex a12cd548..98633374 100644--- a/lib/host/self-update.ts+++ b/lib/host/self-update.ts@@ -5,7 +5,8 @@ import path from "node:path";import { HostError } from "./host-error";import { offlineUpdateArgs, offlineUpdateRunning } from "./self-update-offline";import { prepareUpdateOrigin, updateGitEnv } from "./update-remote-authority";-import { blockingReason, parseCommits, updateBranchReason, type UpdateStatus } from "./update-decision";+import { blockingReason, parseCommits, updateBranchReason, updateRefusal, type UpdateStatus } from "./update-decision";+import { preflightUpdateConflicts } from "./update-conflict";import { fetchArgs } from "./self-update-channel";import type { UpdateChannel } from "@/lib/prefs/updates";import { collectUpdateFacts } from "./update-facts";@@ -39,7 +40,10 @@ import {// (scripts/self-update-auto.ts) must refuse on exactly the same facts.export type { UpdateCommit, UpdateStatus } from "./update-decision";-export { blockingReason, parseCommits, updateBranchReason };+export { blockingReason, parseCommits, updateBranchReason, updateRefusal };+export type { UpdateRefusal } from "./update-decision";+export { updateConflictPrompt, preflightUpdateConflicts } from "./update-conflict";+export type { UpdateConflictReport } from "./update-conflict";export { AUTO_UPDATE_UNIT, SELF_UPDATE_UNIT };export type { UpdateChannel };@@ -116,6 +120,15 @@ export async function getUpdateStatus(fetchRemote = true, channel?: UpdateChanne}const reason = await automaticUpdateReason(execRunner);+ const ahead = facts.ahead;+ const dirty = facts.dirty;+ // READ-ONLY preflight, and only in the two states the operator can be in by+ // choice. `git merge-tree --write-tree` computes the merge in memory: no index,+ // worktree or HEAD write, so this GET route still never mutates the repository.+ const diverged = ahead > 0 && facts.behind > 0;+ const conflict = dirty || diverged+ ? await preflightUpdateConflicts({ targetRef: facts.targetRef, runner: (args) => git(args) })+ : null;return {...base,supported: reason === null,@@ -126,16 +139,17 @@ export async function getUpdateStatus(fetchRemote = true, channel?: UpdateChanne// Only when we know both: a build with no sha baked in (an archive export, a// dev server) must not be reported as permanently stale.pendingBuild: Boolean(buildSha) && facts.head !== "unknown" && !buildSha.startsWith(facts.head) && !facts.head.startsWith(buildSha),- ahead: facts.ahead,+ ahead,behind: facts.behind,commits: facts.commits,- dirty: facts.dirty,+ dirty,running,remoteChecked: facts.remoteChecked,log,channel: effective,target: facts.targetLabel,targetFallback: facts.targetFallback,+ ...(conflict ? { conflict } : {}),};}diff --git a/lib/host/update-conflict.test.ts b/lib/host/update-conflict.test.tsnew file mode 100644index 00000000..36d511e3--- /dev/null+++ b/lib/host/update-conflict.test.ts@@ -0,0 +1,165 @@+// The preflight decides whether a user's own MSO edits survive an update. These+// tests run REAL git in a throwaway repository: merge-tree's conflict output is the+// whole contract here, and a mock would only prove the mock.+import { execFile } from "node:child_process";+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { preflightUpdateConflicts, updateConflictPrompt, type UpdateConflictReport } from "./update-conflict";++const roots: string[] = [];+afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});++function gitIn(cwd: string, args: string[]): Promise<{ code: number; stdout: string; stderr: string }> {+ return new Promise((resolve) => {+ execFile("git", args, { cwd, encoding: "utf8" }, (error, stdout, stderr) => {+ const code = typeof (error as { code?: number } | null)?.code === "number" ? (error as { code: number }).code : error ? 1 : 0;+ resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });+ });+ });+}++async function git(repo: string, ...args: string[]): Promise<string> {+ const ran = await gitIn(repo, args);+ if (ran.code !== 0) throw new Error(`git ${args.join(" ")} failed: ${ran.stderr}`);+ return ran.stdout.trim();+}++/** base commit, then an `incoming` branch that rewrites base.txt and adds new.txt. */+async function repoFixture() {+ const root = mkdtempSync(path.join(os.tmpdir(), "mso-update-conflict-"));+ chmodSync(root, 0o700);+ roots.push(root);+ const repo = path.join(root, "repo");+ mkdirSync(repo, { recursive: true });+ await git(repo, "init", "-q", "-b", "main");+ await git(repo, "config", "user.name", "MSO Test");+ await git(repo, "config", "user.email", "[email protected]");+ writeFileSync(path.join(repo, "base.txt"), "base\n");+ writeFileSync(path.join(repo, "notes.txt"), "notes\n");+ await git(repo, "add", ".");+ await git(repo, "commit", "-qm", "base");+ const base = await git(repo, "rev-parse", "HEAD");++ await git(repo, "checkout", "-q", "-b", "incoming");+ writeFileSync(path.join(repo, "base.txt"), "incoming base\n");+ writeFileSync(path.join(repo, "new.txt"), "incoming new\n");+ await git(repo, "add", ".");+ await git(repo, "commit", "-qm", "incoming change");+ const incoming = await git(repo, "rev-parse", "HEAD");+ await git(repo, "checkout", "-q", "main");+ return { root, repo, base, incoming, preflight: () => preflightUpdateConflicts({ targetRef: incoming, runner: (args) => gitIn(repo, args) }) };+}++describe("preflightUpdateConflicts", () => {+ it("reports a clean checkout as safe with nothing carried or conflicted", async () => {+ const { preflight } = await repoFixture();+ const report = await preflight();+ expect(report).toMatchObject({ conflicted: [], carried: [], overlap: [], safe: true });+ });++ it("keeps a dirty checkout safe when its files do not overlap the incoming ones", async () => {+ const { repo, preflight } = await repoFixture();+ writeFileSync(path.join(repo, "notes.txt"), "my notes\n");+ writeFileSync(path.join(repo, "mine.txt"), "my private tweak\n");+ const report = await preflight();+ expect(report.safe).toBe(true);+ expect(report.conflicted).toEqual([]);+ expect(report.carried.sort()).toEqual(["mine.txt", "notes.txt"]);+ expect(report.overlap).toEqual([]);+ });++ it("refuses to call an update safe when a dirty file overlaps an incoming path", async () => {+ const { repo, preflight } = await repoFixture();+ writeFileSync(path.join(repo, "base.txt"), "my conflicting edit\n");+ const report = await preflight();+ expect(report.safe).toBe(false);+ expect(report.overlap).toEqual(["base.txt"]);+ expect(report.carried).toEqual(["base.txt"]);+ });++ it("names the exact file git cannot merge when local commits conflict with the target", async () => {+ const { repo, incoming, preflight } = await repoFixture();+ writeFileSync(path.join(repo, "base.txt"), "my committed edit\n");+ await git(repo, "commit", "-qam", "my local commit");+ const report = await preflight();+ expect(report.safe).toBe(false);+ expect(report.conflicted).toEqual(["base.txt"]);+ expect(report.carried).toEqual(["base.txt"]);+ expect(report.overlap).toEqual(["base.txt"]);+ // The target still moves to the same commit; nothing above resolved it.+ expect(await git(repo, "rev-parse", incoming)).toBe(incoming);+ });++ it("never mutates the worktree or HEAD", async () => {+ const { repo, preflight } = await repoFixture();+ writeFileSync(path.join(repo, "base.txt"), "local edit\n");+ writeFileSync(path.join(repo, "untracked.txt"), "untracked\n");+ const headBefore = await git(repo, "rev-parse", "HEAD");+ const statusBefore = await git(repo, "status", "--porcelain");+ const filesBefore = await git(repo, "ls-files");+ const stashBefore = await git(repo, "stash", "list");++ await preflight();++ expect(await git(repo, "rev-parse", "HEAD")).toBe(headBefore);+ expect(await git(repo, "status", "--porcelain")).toBe(statusBefore);+ expect(await git(repo, "ls-files")).toBe(filesBefore);+ expect(await git(repo, "stash", "list")).toBe(stashBefore);+ });++ it("fails closed when the target ref does not exist", async () => {+ const { repo } = await repoFixture();+ const report = await preflightUpdateConflicts({ targetRef: "no-such-ref", runner: (args) => gitIn(repo, args) });+ expect(report.safe).toBe(false);+ expect(report.detail.length).toBeGreaterThan(0);+ });++ it("redacts credentials that git echoes back in its stderr", async () => {+ const report = await preflightUpdateConflicts({+ targetRef: "origin/main",+ runner: async () => ({ code: 128, stdout: "", stderr: "fatal: could not read token=ghp_abcdefghijklmnopqrstuvwxyz123456" }),+ });+ expect(report.safe).toBe(false);+ expect(report.detail).not.toContain("ghp_abcdefghijklmnopqrstuvwxyz123456");+ expect(report.detail).toContain("[redacted]");+ });+});++describe("updateConflictPrompt", () => {+ const report: UpdateConflictReport = {+ conflicted: ["app/layout.tsx", "lib/host/self-update.ts"],+ carried: ["app/layout.tsx", "config/local.json"],+ overlap: ["app/layout.tsx"],+ safe: false,+ detail: "CONFLICT (content): Merge conflict in app/layout.tsx",+ };++ it("pastes every path verbatim and refuses destructive shortcuts", () => {+ const prompt = updateConflictPrompt(report, { target: "v0.9.0", current: "e25c00d7" });+ for (const file of [...report.conflicted, ...report.carried, ...report.overlap]) {+ expect(prompt).toContain(file);+ }+ expect(prompt).toContain("v0.9.0");+ expect(prompt).toContain("e25c00d7");+ expect(prompt).toContain("git push --force");+ expect(prompt).toContain("git reset --hard");+ expect(prompt).toContain("~/.mso");+ expect(prompt).toContain("report back");+ // Plain text for a chat box, not a rendered fence.+ expect(prompt).not.toContain("```");+ });++ it("says plainly when carry-over is the only thing to do", () => {+ const safe = updateConflictPrompt(+ { conflicted: [], carried: ["mine.txt"], overlap: [], safe: true, detail: "no merge conflicts" },+ { target: "origin/main", current: "abc1234" },+ );+ expect(safe).toContain("only carry-over and overlap apply");+ expect(safe).toContain("mine.txt");+ expect(safe).toContain("Update safe to apply as-is: yes");+ });+});diff --git a/lib/host/update-conflict.ts b/lib/host/update-conflict.tsnew file mode 100644index 00000000..5834e6ff--- /dev/null+++ b/lib/host/update-conflict.ts@@ -0,0 +1,135 @@+// DOES THE USER'S MSO SURVIVE THE UPDATE? Answered before anything is touched.+//+// A user who edits their checkout and still wants the newest code should get both+// when git can replay their work, and should be told exactly which files collide+// when it cannot. That question is answered by `git merge-tree --write-tree`, which+// runs the REAL merge machinery in memory: it never writes the index, the worktree,+// or HEAD, and its only side effect is throwaway tree/blob objects in .git/objects+// that `git gc` collects. Never `git merge`, checkout, stash or reset here.+//+// Deliberately free of `server-only` and `@/` imports (same reason as+// update-decision.ts): the nightly timer decides on the same facts outside Next.+import { redactText } from "../security/redact-text";++export type UpdateConflictReport = {+ /** Files git cannot merge automatically. Empty means the update is safe. */+ conflicted: string[];+ /** Files the user changed that will be replayed on top of the new code. */+ carried: string[];+ /** Files the update rewrites that the user also touched (potential clobber). */+ overlap: string[];+ /** True when `git merge-tree` reports no conflict for the incoming ref. */+ safe: boolean;+ /** Bounded, redacted git output for diagnosis. Never a credential. */+ detail: string;+};++export type ConflictGitRunner = (args: string[]) => Promise<{ code: number; stdout: string; stderr: string }>;++const DETAIL_MAX = 800;++/** Newline-separated path list → trimmed, de-duplicated, non-empty paths. */+function paths(stdout: string): string[] {+ const seen = new Set<string>();+ for (const line of stdout.split("\n")) {+ const value = line.trim();+ if (value) seen.add(value);+ }+ return [...seen];+}++/**+ * `git merge-tree --write-tree --name-only --no-messages HEAD <ref>` output.+ *+ * Exit 0 is a clean merge and the whole stdout is the resulting tree oid. Exit 1 is+ * conflict: line 1 is a tree oid, every following line is a conflicted path.+ * Anything else is not a merge answer at all (bad ref, unrelated histories).+ */+function probe(stdout: string, code: number): { clean: boolean; conflicted: string[] } {+ const [first = "", ...rest] = stdout.split("\n").map((line) => line.trim());+ if (code === 0) return { clean: /^[0-9a-f]{40,64}$/.test(first), conflicted: [] };+ return { clean: false, conflicted: rest.filter(Boolean) };+}++export async function preflightUpdateConflicts(input: {+ /** Ref the update would move to, already resolved server-side. */+ targetRef: string;+ /** Runner used by the rest of the update path; do not spawn git directly. */+ runner: ConflictGitRunner;+}): Promise<UpdateConflictReport> {+ const { targetRef, runner } = input;+ const empty: UpdateConflictReport = { conflicted: [], carried: [], overlap: [], safe: false, detail: "" };+ const note = (parts: Array<{ stdout: string; stderr: string }>) =>+ redactText(parts.map((p) => `${p.stdout}${p.stderr}`).join("\n").trim(), DETAIL_MAX);++ // Fail closed: without a merge base there is no meaningful "carried" list, and+ // claiming safety would be a guess.+ const base = await runner(["merge-base", "--", "HEAD", targetRef]);+ const mergeBase = base.code === 0 ? base.stdout.trim() : "";+ if (!mergeBase) {+ return { ...empty, detail: note([base]) || `could not find a merge base with ${targetRef}` };+ }++ // Three sets: what the user committed since the merge base, what they changed but+ // never committed (worktree + index), and what they added untracked.+ const [committed, working, untracked, incoming] = await Promise.all([+ runner(["diff", "--name-only", mergeBase, "HEAD"]),+ runner(["diff", "--name-only", "HEAD"]),+ runner(["ls-files", "--others", "--exclude-standard"]),+ runner(["diff", "--name-only", mergeBase, targetRef]),+ ]);+ if (incoming.code !== 0) {+ return { ...empty, detail: note([incoming]) || `could not list the files ${targetRef} changes` };+ }+ const carried = [...new Set([...paths(committed.stdout), ...paths(working.stdout), ...paths(untracked.stdout)])];+ const incomingPaths = paths(incoming.stdout);+ const overlap = carried.filter((file) => incomingPaths.includes(file));++ const merged = await runner(["merge-tree", "--write-tree", "--name-only", "--no-messages", "HEAD", targetRef]);+ const { clean, conflicted } = probe(merged.stdout, merged.code);++ return {+ conflicted,+ carried,+ overlap,+ // merge-tree reads COMMITS, so it cannot prove anything about uncommitted work;+ // an overlapping path is therefore treated as unsafe rather than assumed fine.+ safe: clean && overlap.length === 0,+ detail: note([merged]) || (clean ? "no merge conflicts" : "merge-tree reported conflicts"),+ };+}++/**+ * A paste-ready instruction for a coding agent that has to finish this update by+ * hand. Plain text, no markdown fences: it is pasted into a chat, not rendered.+ */+export function updateConflictPrompt(report: UpdateConflictReport, status: { target: string; current: string }): string {+ const list = (label: string, files: string[], empty: string) =>+ `${label}\n${files.length ? files.map((file) => `- ${file}`).join("\n") : `- ${empty}`}`;++ return [+ `The MSO checkout at commit ${status.current} needs to update to ${status.target}, but the local tree cannot be merged automatically.`,+ "",+ "Help me finish this update without losing any of my changes or configuration.",+ "",+ list("Conflicted files (git cannot merge these automatically):", report.conflicted, "none — only carry-over and overlap apply"),+ "",+ list("My changes that must be preserved and carried onto the new code:", report.carried, "none"),+ "",+ list("Files the update rewrites that I also touched (possible clobber):", report.overlap, "none"),+ "",+ `Update safe to apply as-is: ${report.safe ? "yes" : "no"}`,+ "",+ "What to do:",+ "1. Inspect the conflicted and overlapping files above and resolve each conflict by hand, keeping my intent in both sides.",+ `2. Move the checkout to ${status.target} (fast-forward) and replay my carried changes on top.`,+ "3. Preserve my configuration and private state exactly: anything under ~/.mso, my .env files, and my own local commits.",+ "4. Verify the result builds and runs before declaring success, and report back exactly which files you changed and why.",+ "",+ "Do not run `git push --force`, `git reset --hard`, `git clean -fdx`, or delete any of my files.",+ "Do not drop or overwrite my changes to make the merge pass.",+ "",+ "Git output:",+ report.detail || "(none)",+ ].join("\n");+}diff --git a/lib/host/update-decision.test.ts b/lib/host/update-decision.test.tsindex 1aa8c2c3..fbafcb74 100644--- a/lib/host/update-decision.test.ts+++ b/lib/host/update-decision.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { autoUpdateGate, parseCommits, touchesUpdater, type AutoGateFacts } from "./update-decision";+import { autoUpdateGate, blockingReason, parseCommits, touchesUpdater, updateRefusal, type AutoGateFacts, type UpdateStatus } from "./update-decision";const facts = (over: Partial<AutoGateFacts> = {}): AutoGateFacts => ({auto: true,@@ -86,6 +86,47 @@ describe("autoUpdateGate", () => {});});+const status = (over: Partial<UpdateStatus> = {}): UpdateStatus => ({+ supported: true, reason: null, current: "abc1234", currentSubject: "feat: something",+ buildSha: "abc1234", pendingBuild: false, ahead: 0, behind: 3, commits: [], dirty: false,+ running: false, remoteChecked: true, log: "", target: "origin/main", ...over,+});++describe("updateRefusal", () => {+ it("keeps the reason string and stays backward compatible with blockingReason", () => {+ expect(blockingReason(status(), false)).toBeNull();+ expect(blockingReason(status({ dirty: true }), false)).toContain("uncommitted changes");+ });++ it("rides a structured conflict report alongside the unchanged dirty reason", () => {+ const conflict = {+ conflicted: [], carried: ["config/local.json"], overlap: [], safe: true, detail: "no merge conflicts",+ };+ const refusal = updateRefusal(status({ dirty: true, conflict }), false);+ expect(refusal.reason).toContain("uncommitted changes");+ expect(refusal.reason).toContain("carry over cleanly");+ expect(refusal.reason).toContain("config/local.json");+ expect(refusal.conflict).toBe(conflict);+ });++ it("names the conflicting files when the preflight says the update would collide", () => {+ const conflict = {+ conflicted: ["app/layout.tsx"], carried: ["app/layout.tsx"], overlap: ["app/layout.tsx"], safe: false, detail: "",+ };+ expect(updateRefusal(status({ dirty: true, conflict }), false).reason).toContain("app/layout.tsx");+ });++ it("carries the report on a diverged refusal and leaves clean states without one", () => {+ const conflict = {+ conflicted: ["lib/host/self-update.ts"], carried: [], overlap: [], safe: false, detail: "",+ };+ const diverged = updateRefusal(status({ ahead: 2, behind: 3, conflict }), false);+ expect(diverged.reason).toContain("diverged");+ expect(diverged.reason).toContain("lib/host/self-update.ts");+ expect(updateRefusal(status(), false)).toEqual({ reason: null, conflict: null });+ });+});+describe("touchesUpdater", () => {it("matches allowlisted updater paths only, never a prefix or a similar name", () => {expect(touchesUpdater(["lib/host/self-update.ts"])).toBe("lib/host/self-update.ts");diff --git a/lib/host/update-decision.ts b/lib/host/update-decision.tsindex dce59687..9ab4066c 100644--- a/lib/host/update-decision.ts+++ b/lib/host/update-decision.ts@@ -5,6 +5,7 @@// This module is deliberately free of `server-only` and `@/` imports: the timer's// pre-flight (scripts/self-update-auto.ts) runs it under bun, outside Next.import type { UpdateChannel } from "../prefs/updates";+import type { UpdateConflictReport } from "./update-conflict";export interface UpdateCommit {sha: string;@@ -42,6 +43,9 @@ export interface UpdateStatus {target?: string;/** Stable found no release tag at all and is tracking rolling main — said out loud. */targetFallback?: boolean;+ /** Read-only merge preflight, present only when the checkout is dirty or diverged.+ * Absent means "not investigated", never "safe". */+ conflict?: UpdateConflictReport;}/** `<sha>\x1f<subject>\x1f<iso date>` per line — a separator no subject can contain. */@@ -73,22 +77,57 @@ export function updateBranchReason(branch: string): string | null {* build that fails halfway through with the live `.next` already deleted.*/export function blockingReason(status: UpdateStatus, rebuildOnly: boolean): string | null {+ return updateRefusal(status, rebuildOnly).reason;+}++/** A refusal plus — for the two states a user can actually be in by choice, a dirty+ * tree and a diverged main — the read-only preflight that names the files. The+ * `reason` string is unchanged for every existing caller; `conflict` is extra. */+export type UpdateRefusal = {+ reason: string | null;+ /** Only when the checkout is dirty or diverged AND a preflight ran. */+ conflict: UpdateConflictReport | null;+};++const NAME_LIMIT = 8;++function names(files: readonly string[]): string {+ const shown = files.slice(0, NAME_LIMIT).join(", ");+ return files.length > NAME_LIMIT ? `${shown} (+${files.length - NAME_LIMIT} more)` : shown;+}++export function updateRefusal(status: UpdateStatus, rebuildOnly: boolean): UpdateRefusal {const target = status.target ?? "origin/main";- if (!status.supported) return status.reason ?? "this deployment cannot update itself";- if (status.running) return "an update is already running";+ if (!status.supported) return { reason: status.reason ?? "this deployment cannot update itself", conflict: null };+ if (status.running) return { reason: "an update is already running", conflict: null };+ const conflict = status.conflict ?? null;if (status.dirty) {- return "the checkout has uncommitted changes — commit or stash them on the host first, a fast-forward would refuse anyway";+ // Same sentence and same leading words as before (the Settings panel keys its+ // "dirty" remedy off "uncommitted changes"), now followed by what the preflight+ // actually found: either the exact colliding files or what carries over.+ const base = "the checkout has uncommitted changes — commit or stash them on the host first, a fast-forward would refuse anyway";+ if (!conflict) return { reason: base, conflict };+ const detail = conflict.safe+ ? `; a read-only preflight found no conflict, so these changes would carry over cleanly: ${names(conflict.carried) || "none"}`+ : `; a read-only preflight found conflicts in: ${names(conflict.conflicted.length ? conflict.conflicted : conflict.overlap)}`;+ return { reason: `${base}${detail}`, conflict };}if (!rebuildOnly && status.ahead > 0) {- return status.behind > 0- ? `local main has diverged from ${target} (ahead ${status.ahead}, behind ${status.behind}); reconcile it before updating`- : `local main is ahead of ${target} by ${status.ahead} commit(s); push or reconcile it before updating`;+ const detail = conflict && !conflict.safe+ ? `; files behind the divergence: ${names(conflict.conflicted.length ? conflict.conflicted : conflict.overlap)}`+ : "";+ return {+ reason: status.behind > 0+ ? `local main has diverged from ${target} (ahead ${status.ahead}, behind ${status.behind}); reconcile it before updating${detail}`+ : `local main is ahead of ${target} by ${status.ahead} commit(s); push or reconcile it before updating`,+ conflict,+ };}// `pendingBuild` is a reason to run even with nothing to pull: the checkout// already holds code the running process was not built from, and refusing with// "already up to date" would be describing the wrong thing as up to date.- if (!rebuildOnly && status.behind === 0 && !status.pendingBuild) return "already up to date";- return null;+ if (!rebuildOnly && status.behind === 0 && !status.pendingBuild) return { reason: "already up to date", conflict: null };+ return { reason: null, conflict: null };}/** Files whose unattended replacement can strand the host: the updater itself, itsdiff --git a/scripts/e2e/shell-notices.mjs b/scripts/e2e/shell-notices.mjsindex b52fc05e..22bd1dbb 100644--- a/scripts/e2e/shell-notices.mjs+++ b/scripts/e2e/shell-notices.mjs@@ -7,17 +7,13 @@ export async function shellNoticesJourney(page, fixture) {await page.setViewportSize(viewport);await page.goto(fixture.base);await expect(page.locator('[data-slot="shell-update-badge"]')).toBeVisible();+ // MSO no longer renders its own install pill: installability stays a browser+ // menu action, so even a fired `beforeinstallprompt` must render nothing here.await page.evaluate(() => window.dispatchEvent(new Event("beforeinstallprompt", { cancelable: true })));- const install = page.locator('[data-slot="pwa-install-prompt"]');- await expect(install).toBeVisible();- const promptBox = await install.boundingBox();- const updateBox = await page.locator('[data-slot="shell-update-badge"]').boundingBox();- expect(promptBox.y + promptBox.height).toBeLessThanOrEqual(updateBox.y);- await install.getByRole("button", { name: "Dismiss", exact: true }).click();- await expect(install).toHaveCount(0);+ await expect(page.locator('[data-slot="pwa-install-prompt"]')).toHaveCount(0);}await page.unroute(status);await page.setViewportSize({ width: 1280, height: 900 });await page.goto(fixture.base + "/integrations");- console.log("PASS install and update notices stay separate at desktop and narrow mobile widths");+ console.log("PASS the update notice stays visible and the removed install pill never renders at desktop and narrow mobile widths");}