Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.
TypeScript agentai-agentai-agentsai-assistantandroidautomationchatgptcoding-agentcomputer-usedesktop-appelectronllmlocal-firstmcpmulti-agentollamaopenaiprivacyself-hostedtypescript
feat(workspaces): offer to install Git where a feature needs it (macOS, Linux)
leen.zhou14120b0f9480
diff --git a/apps/desktop/src/renderer/features/chat/messages/ChatMessage.tsx b/apps/desktop/src/renderer/features/chat/messages/ChatMessage.tsxindex eccd870..b85e242 100644--- a/apps/desktop/src/renderer/features/chat/messages/ChatMessage.tsx+++ b/apps/desktop/src/renderer/features/chat/messages/ChatMessage.tsx@@ -19,7 +19,7 @@ import { BotAvatar, botAvatarLook, useSettings, useT } from "@pibot/renderer-kitimport { MessageRoutineProposals } from "@pibot/routines/ui";import { MessageSkillProposals, TeachTrialReturn } from "@pibot/skills/ui";import { Button, Card } from "@pibot/ui";-import { TurnCard } from "@pibot/workspaces/ui";+import { GitInstallCard, TurnCard } from "@pibot/workspaces/ui";import { type CSSProperties, memo, type ReactNode, useCallback, useMemo, useState } from "react";import { RunReceipt } from "../../receipt/RunReceipt.tsx";import styles from "../chat.module.css";@@ -394,6 +394,7 @@ export const ChatMessage = memo(function ChatMessage({{!preview && message.role === "assistant" && message.status !== "streaming" && (<AgentReplyFacts usage={message.usage} />)}+ {!preview && gitSetupCard(message.usage) && <GitInstallCard context="parallel" />}{!preview &&(turn && !turn.last ? (receipt(false)@@ -566,3 +567,10 @@ const RoutineNoticeLine = memo(function RoutineNoticeLine({</p>);});++/** A plan's turns notice that also offers to install Git (written by the program, once per plan). */+function gitSetupCard(usage: Message["usage"]) {+ return (+ !!usage && typeof usage === "object" && !Array.isArray(usage) && usage.gitSetup === "parallel"+ );+}diff --git a/packages/client-core/src/audit/presentation.ts b/packages/client-core/src/audit/presentation.tsindex a872077..dc722b4 100644--- a/packages/client-core/src/audit/presentation.ts+++ b/packages/client-core/src/audit/presentation.ts@@ -144,6 +144,8 @@ const kindGroups: Record<AuditKind, readonly [AuditGroup, ...AuditGroup[]]> = {// Preparing a runtime installs a skill's dependencies, so it belongs beside the skill it serves."skill.runtime.prepared": ["connectors"],"skill.downloaded": ["connectors"],+ // A system installer the user started from a Git card; it ran outside the sandbox.+ "git.install": ["run"],"memory.changed": ["run"],"credential.saved": ["web"],"credential.updated": ["web"],@@ -896,6 +898,14 @@ export function auditResult(tone: reason === "ok" ? "ok" : reason === "skill_link_cancelled" ? "muted" : "danger",};}+ if (entry.kind === "git.install") {+ const reason = detail.reasonCode;+ if (reason === "started") return { text: t("activity.running"), tone: "muted" };+ if (reason === "cancelled") return { text: t("audit.result.cancelled"), tone: "muted" };+ return reason === "installed"+ ? { text: t("activity.done"), tone: "ok" }+ : { text: t("activity.failed"), tone: "danger" };+ }if (entry.kind === "grant.created" || entry.kind === "grant.revoked")return {text: t(entry.kind === "grant.created" ? "audit.result.remembered" : "audit.result.revoked"),diff --git a/packages/execution/src/git/git-install.ts b/packages/execution/src/git/git-install.tsnew file mode 100644index 0000000..086e4cd--- /dev/null+++ b/packages/execution/src/git/git-install.ts@@ -0,0 +1,216 @@+import { spawn } from "node:child_process";+import { constants } from "node:fs";+import { access, readFile } from "node:fs/promises";+import { posix } from "node:path";+import { findGit, type GitProcessOptions } from "./git-process.ts";++export type GitPackageManager = "apt-get" | "dnf" | "pacman" | "zypper";++/**+ * How this computer gets Git system-wide (maintainers 2026-11-21): macOS opens Apple's own+ * Command Line Tools installer, Linux uses the distribution's package manager through polkit.+ * Windows ships MinGit in its installer, so it never installs anything here.+ */+export type GitInstallPlan =+ | { kind: "xcode"; command: string; manualCommand: string }+ | {+ kind: "package";+ manager: GitPackageManager;+ /** What runs, without the elevation prefix (shown on the card). */+ command: string;+ /** What the user can type in a terminal when the polkit prompt is unavailable. */+ manualCommand: string;+ program: string;+ args: string[];+ /** Fixed pkexec path, or absent when the computer has none. */+ elevate?: string;+ }+ | { kind: "manual" }+ | { kind: "unsupported" };++export type GitInstallOutcome =+ | { outcome: "started" | "installed"; exitCode: number | null }+ | { outcome: "denied" | "failed" | "no_elevation"; exitCode: number | null };++const MANAGERS: Record<GitPackageManager, { args: string[]; distros: string[] }> = {+ "apt-get": { args: ["install", "-y", "git"], distros: ["debian", "ubuntu"] },+ dnf: { args: ["install", "-y", "git"], distros: ["fedora", "rhel", "centos"] },+ pacman: { args: ["-S", "--noconfirm", "git"], distros: ["arch"] },+ zypper: { args: ["--non-interactive", "install", "git"], distros: ["opensuse", "suse", "sles"] },+};+const ORDER = Object.keys(MANAGERS) as GitPackageManager[];+// Fixed system locations only: a PATH lookup could pick a planted program that then runs as root.+const SYSTEM_BIN = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"];+const XCODE_SELECT = "/usr/bin/xcode-select";+const INSTALL_TIMEOUT_MS = 20 * 60_000;++async function executable(path: string) {+ try {+ await access(path, constants.X_OK);+ return true;+ } catch {+ // Absent is the expected answer for most candidates.+ return false;+ }+}++async function systemProgram(name: string) {+ for (const dir of SYSTEM_BIN) {+ const path = posix.join(dir, name);+ if (await executable(path)) return path;+ }+ return undefined;+}++/** ID and ID_LIKE tokens of /etc/os-release, most specific first. */+export function osReleaseFamilies(text: string) {+ const fields = new Map<string, string>();+ for (const line of text.split("\n")) {+ const match = /^\s*(ID|ID_LIKE)\s*=\s*(.*)\s*$/.exec(line);+ if (match?.[1] && match[2] !== undefined)+ fields.set(match[1], match[2].replace(/^["']|["']$/g, "").toLowerCase());+ }+ return [fields.get("ID") ?? "", ...(fields.get("ID_LIKE") ?? "").split(/\s+/)].filter((token) =>+ /^[a-z0-9._-]{1,64}$/.test(token),+ );+}++function managerFor(families: readonly string[]) {+ for (const family of families)+ for (const manager of ORDER)+ if (MANAGERS[manager].distros.some((id) => family === id || family.startsWith(`${id}-`)))+ return manager;+ return undefined;+}++/** Reads only fixed system files; never spawns. */+export async function gitInstallPlan(platform: NodeJS.Platform): Promise<GitInstallPlan> {+ if (platform === "darwin")+ return {+ kind: "xcode",+ command: "xcode-select --install",+ manualCommand: "xcode-select --install",+ };+ if (platform !== "linux") return { kind: "unsupported" };+ const release = await readFile("/etc/os-release", "utf8").catch(() =>+ // Older systems keep it only under /usr/lib; neither existing just means no distro hint.+ readFile("/usr/lib/os-release", "utf8").catch(() => ""),+ );+ const preferred = managerFor(osReleaseFamilies(release));+ const candidates = preferred ? [preferred, ...ORDER.filter((m) => m !== preferred)] : ORDER;+ for (const manager of candidates) {+ const program = await systemProgram(manager);+ if (!program) continue;+ const args = MANAGERS[manager].args;+ const command = [manager, ...args].join(" ");+ const elevate = await systemProgram("pkexec");+ return {+ kind: "package",+ manager,+ command,+ manualCommand: `sudo ${command}`,+ program,+ args,+ ...(elevate ? { elevate } : {}),+ };+ }+ return { kind: "manual" };+}++/** `git --version` of a fixed executable, outside any repository; undefined when it cannot run. */+export function gitVersion(program: string, signal: AbortSignal): Promise<string | undefined> {+ return new Promise((resolve) => {+ let out = "";+ const child = spawn(program, ["--version"], {+ cwd: "/",+ env: { PATH: SYSTEM_BIN.join(":"), LC_ALL: "C", LANG: "C", GIT_CONFIG_NOSYSTEM: "1" },+ stdio: ["ignore", "pipe", "ignore"],+ signal: AbortSignal.any([signal, AbortSignal.timeout(10_000)]),+ windowsHide: true,+ });+ child.stdout?.on("data", (chunk: Buffer) => {+ if (out.length < 256) out += chunk.toString("utf8");+ });+ // A failure to run is answered as "no version"; the caller still knows Git exists.+ child.once("error", () => resolve(undefined));+ child.once("close", (code) =>+ resolve(code === 0 ? /git version (\S{1,60})/.exec(out)?.[1] : undefined),+ );+ });+}++/**+ * Runs the system installer once, outside the sandbox: the user's click on the card is the+ * confirmation, and the caller audits it. Output is discarded (it never reaches logs).+ * macOS: xcode-select only opens Apple's installer window and returns; the caller then waits+ * for Git to appear. Linux: the package manager runs under pkexec and finishes before return.+ */+export async function runGitInstaller(+ plan: GitInstallPlan,+ options: { platform: NodeJS.Platform; env: Readonly<NodeJS.ProcessEnv>; signal: AbortSignal },+): Promise<GitInstallOutcome> {+ if (plan.kind === "manual" || plan.kind === "unsupported")+ return { outcome: "failed", exitCode: null };+ if (plan.kind === "package" && !plan.elevate) return { outcome: "no_elevation", exitCode: null };+ const [program, args] =+ plan.kind === "xcode"+ ? [XCODE_SELECT, ["--install"]]+ : [plan.elevate as string, [plan.program, ...plan.args]];+ // pkexec's GUI agent and Apple's installer need the desktop session; nothing else is passed.+ const session = ["DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS"]+ .map((name) => [name, options.env[name]] as const)+ .filter(+ (entry): entry is readonly [string, string] => !!entry[1] && !/[\0\r\n]/.test(entry[1]),+ );+ const runtime = options.env.XDG_RUNTIME_DIR;+ const env: NodeJS.ProcessEnv = {+ PATH: SYSTEM_BIN.join(":"),+ LANG: options.env.LANG && /^[\w.@-]{1,64}$/.test(options.env.LANG) ? options.env.LANG : "C",+ ...Object.fromEntries(session),+ ...(runtime && posix.isAbsolute(runtime) ? { XDG_RUNTIME_DIR: runtime } : {}),+ ...(options.env.HOME && posix.isAbsolute(options.env.HOME) ? { HOME: options.env.HOME } : {}),+ };+ const exitCode = await new Promise<number | null>((resolve) => {+ const child = spawn(program, args, {+ cwd: "/",+ env,+ stdio: "ignore",+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(INSTALL_TIMEOUT_MS)]),+ windowsHide: true,+ });+ child.once("error", () => resolve(null));+ child.once("close", (code) => resolve(code));+ });+ if (plan.kind === "xcode")+ // Exit 1 also covers "already installed / an update is pending": the caller's poll decides.+ return exitCode === 0 || exitCode === 1+ ? { outcome: "started", exitCode }+ : { outcome: "failed", exitCode };+ if (exitCode === 0) return { outcome: "installed", exitCode };+ // pkexec: 126 = the user dismissed the password dialog, 127 = not authorized / no agent.+ return {+ outcome: exitCode === 126 || exitCode === 127 ? "denied" : "failed",+ exitCode,+ };+}++/** Polls the fixed Git locations until one appears, the deadline passes or the signal aborts. */+export async function waitForGit(+ options: Pick<GitProcessOptions, "platform" | "env" | "resourcesDir">,+ input: { signal: AbortSignal; timeoutMs: number; intervalMs?: number },+) {+ const deadline = Date.now() + input.timeoutMs;+ for (;;) {+ const found = await findGit(options);+ if (found || input.signal.aborted || Date.now() >= deadline) return found;+ await new Promise<void>((resolve) => {+ const timer = setTimeout(done, input.intervalMs ?? 3000);+ function done() {+ clearTimeout(timer);+ input.signal.removeEventListener("abort", done);+ resolve();+ }+ input.signal.addEventListener("abort", done, { once: true });+ });+ }+}diff --git a/packages/execution/src/git/git-read.ts b/packages/execution/src/git/git-read.tsindex c3a7624..86e8ce8 100644--- a/packages/execution/src/git/git-read.ts+++ b/packages/execution/src/git/git-read.ts@@ -281,7 +281,11 @@ export function createGitReader(options: GitReaderOptions) {let disposed = false;function locate() {- program ??= findGit(options);+ // Only a found Git is remembered: the user may install one while Pi Bot runs (git-install.ts).+ program ??= findGit(options).then((found) => {+ if (!found) program = undefined;+ return found;+ });return program;}async function acquire(signal: AbortSignal) {diff --git a/packages/execution/src/index.ts b/packages/execution/src/index.tsindex 64d1e23..51e2925 100644--- a/packages/execution/src/index.ts+++ b/packages/execution/src/index.ts@@ -125,10 +125,20 @@ export type {GitHookPlan,GitHookPrepareInput,} from "./git/git-hook-types.ts";+export {+ type GitInstallOutcome,+ type GitInstallPlan,+ type GitPackageManager,+ gitInstallPlan,+ gitVersion,+ runGitInstaller,+ waitForGit,+} from "./git/git-install.ts";export * from "./git/git-network.ts";export { prepareGitOutput } from "./git/git-output.ts";export { GitOutputSourceError } from "./git/git-output-error.ts";export { gitOutputIntent } from "./git/git-output-intent.ts";+export { findGit } from "./git/git-process.ts";export {createGitReader,type GitReader,diff --git a/packages/orchestration/src/conversations/groups/group-plan-merges.ts b/packages/orchestration/src/conversations/groups/group-plan-merges.tsindex e456d6a..5a03ff2 100644--- a/packages/orchestration/src/conversations/groups/group-plan-merges.ts+++ b/packages/orchestration/src/conversations/groups/group-plan-merges.ts@@ -27,6 +27,8 @@ export class GroupPlanMerges {private timer?: ReturnType<typeof setInterval>;private stopped = false;private readonly noted = new Set<string>();+ /** Plans that already showed the 「安装 Git」 card; one card per plan is enough. */+ private readonly gitCards = new Set<string>();constructor(private readonly engine: WorkflowEngine) {}private get service(): GroupService {@@ -241,6 +243,14 @@ export class GroupPlanMerges {step.stepId;const zh = this.service.deps.chat.currentLanguage() === "zh";const why = turnsReason(reason, zh);+ // Maintainers 2026-11-21: without Git the plan offers to install it, once, at this point.+ const plan = record.budgetRootRunId ?? record.id;+ const gitCard = reason === "git_unavailable" && !this.gitCards.has(plan);+ if (gitCard) {+ this.gitCards.add(plan);+ if (this.gitCards.size > 200)+ this.gitCards.delete(this.gitCards.values().next().value as string);+ }new MessagesRepo(this.service.deps.db).create({conversationId: group.conversationId,botId: record.coordinatorBotId,@@ -251,7 +261,10 @@ export class GroupPlanMerges {: `“${title}” takes turns in the group folder: ${why}.`,),status: "done",- usage: { groupWorkflowStatus: { workflowRunId: record.id } },+ usage: {+ groupWorkflowStatus: { workflowRunId: record.id },+ ...(gitCard ? { gitSetup: "parallel" } : {}),+ },});this.service.changed(record.groupId, "updated");}diff --git a/packages/protocol-base/src/permissions/audit.ts b/packages/protocol-base/src/permissions/audit.tsindex fd00d58..ccbbd30 100644--- a/packages/protocol-base/src/permissions/audit.ts+++ b/packages/protocol-base/src/permissions/audit.ts@@ -109,6 +109,9 @@ export const AuditKindSchema = z.enum([// A skill's runtime environment was prepared, failed, or removed. Counts and a reason// code only; the command text and its output stay in the environment's log file."skill.runtime.prepared",+ // The user asked Pi Bot to install Git system-wide (started, then how it ended); the command+ // text and outcome only, never the installer's output.+ "git.install","memory.changed",// Saved website accounts. Site, display name and Bots only; never the secret."credential.saved",diff --git a/packages/protocol/test/schemas.test.ts b/packages/protocol/test/schemas.test.tsindex 38a8933..929a21d 100644--- a/packages/protocol/test/schemas.test.ts+++ b/packages/protocol/test/schemas.test.ts@@ -2725,6 +2725,23 @@ const methodCases = {badParams: { conversationKey: `group:${id}`, topicId: id },badResult: { runIds: [1] },},+ "changes.gitStatus": {+ params: {},+ result: { state: "available", version: "2.39.5" },+ badParams: { force: true },+ badResult: { state: "absent" },+ },+ "changes.gitInstall": {+ params: {},+ result: {+ state: "installing",+ installer: "package",+ command: "dnf install -y git",+ manualCommand: "sudo dnf install -y git",+ },+ badParams: { manager: "dnf" },+ badResult: { state: "failed", reason: "unknown" },+ },"changes.reviewers": {params: { conversationKey: `dm:${id}` },result: {diff --git a/packages/workspaces-contract/src/api/changes.ts b/packages/workspaces-contract/src/api/changes.tsindex 9b64e01..98a3f41 100644--- a/packages/workspaces-contract/src/api/changes.ts+++ b/packages/workspaces-contract/src/api/changes.ts@@ -40,6 +40,20 @@ const scopedTarget = <T extends z.ZodRawShape>(shape: T) =>.strictObject({ ...targetFields, ...shape }).refine((p) => validTarget(p as { conversationKey: string; topicId?: string }));const ok = z.strictObject({ ok: z.literal(true) });+const shortText = z.string().min(1).max(200);+export const GitSetupStatusSchema = z.strictObject({+ state: z.enum(["available", "missing", "installing", "failed", "unsupported"]),+ version: z.string().max(100).optional(),+ /** xcode: Apple's Command Line Tools; package: the system package manager; manual: neither found. */+ installer: z.enum(["xcode", "package", "manual"]).optional(),+ /** What Pi Bot runs, e.g. "dnf install -y git". */+ command: shortText.optional(),+ /** What the user can run in a terminal instead, e.g. "sudo dnf install -y git". */+ manualCommand: shortText.optional(),+ /** Why the last attempt did not end with Git. */+ reason: z.enum(["denied", "failed", "no_elevation", "timeout", "cancelled"]).optional(),+});+export type GitSetupStatus = z.infer<typeof GitSetupStatusSchema>;export const ChangesMethods = {"changes.reveal": {params: z.union([@@ -283,6 +297,17 @@ export const ChangesMethods = {}),result: ok,},+ /**+ * Whether this computer has Git, and how Pi Bot would install it (maintainers 2026-11-21). Every+ * call looks again, so it doubles as 「再检查」. Windows ships Git and answers "unsupported".+ */+ "changes.gitStatus": { params: z.strictObject({}), result: GitSetupStatusSchema },+ /**+ * The user clicked 「安装」 on the card: starts the system installer outside the sandbox and+ * returns at once ("installing"); the card polls changes.gitStatus. A second click while one+ * runs gets the same "installing" answer, never a second installer.+ */+ "changes.gitInstall": { params: z.strictObject({}), result: GitSetupStatusSchema },} as const;export const ChangesEvents = {/** Coalesced, at most once per second per folder; diff text is fetched on demand, never pushed. */diff --git a/packages/workspaces-contract/src/i18n/changes.ts b/packages/workspaces-contract/src/i18n/changes.tsindex 5f55f09..7c5f18d 100644--- a/packages/workspaces-contract/src/i18n/changes.ts+++ b/packages/workspaces-contract/src/i18n/changes.ts@@ -89,6 +89,32 @@ export const changesZh = {"changes.repo.noGitBody":"这台电脑上没找到 Git,所以只能看每一轮改了什么。装好 Git 后就能看全部未提交的改动、撤回和提交。","changes.repo.installGit": "下载 Git",+ "changes.git.title": "Pi Bot 需要安装 Git",+ "changes.git.why": "为什么",+ "changes.git.what": "会做什么",+ "changes.git.where": "装在哪里",+ "changes.git.whyParallel":+ "这几步要同时做,各自需要一个独立工作区,这要用到 Git。不装的话,它们会轮流做。",+ "changes.git.whyChanges": "查看全部未提交的改动、撤回和提交都要用到 Git。",+ "changes.git.whatMac": "打开 Apple 的「命令行开发者工具」安装窗口(系统自带,约几分钟)",+ "changes.git.whatLinux": "用系统包管理器安装(这台电脑:{command}),系统会要你输入管理员密码",+ "changes.git.whatLinuxGeneric": "用系统包管理器安装 Git",+ "changes.git.whereValue": "系统位置,所有程序都能用",+ "changes.git.note": "这一步在沙箱外运行系统安装程序,只在你点「安装」后执行,并记入「记录」。",+ "changes.git.later": "以后再说(先轮流做)",+ "changes.git.laterPlain": "以后再说",+ "changes.git.install": "安装",+ "changes.git.installing": "正在安装 Git…(装好前先轮流做)",+ "changes.git.installingPlain": "正在安装 Git…",+ "changes.git.installingMac": "在 Apple 的安装窗口里点「安装」继续。",+ "changes.git.installed": "Git 已安装({version})· 之后的步骤可以同时做",+ "changes.git.installedNoVersion": "Git 已安装 · 之后的步骤可以同时做",+ "changes.git.installedPlain": "Git 已安装({version})",+ "changes.git.installedPlainNoVersion": "Git 已安装",+ "changes.git.failed": "没装上:可以在终端里运行 {command},装好后点「再检查」",+ "changes.git.failedGeneric": "没装上:可以用系统包管理器安装 Git,装好后点「再检查」",+ "changes.git.recheck": "再检查",+ "changes.git.error": "没能开始安装,请再试一次。","changes.repo.readonly": "只读","changes.repo.running": "{name}正在运行","changes.repo.subdirectory":@@ -466,6 +492,36 @@ export const changesEn: { [K in keyof typeof changesZh]: string } = {"changes.repo.noGitBody":"Git isn't installed on this computer, so only each turn's changes are shown. Install Git to see all uncommitted changes, discard and commit.","changes.repo.installGit": "Get Git",+ "changes.git.title": "Pi Bot needs to install Git",+ "changes.git.why": "Why",+ "changes.git.what": "What it does",+ "changes.git.where": "Where it goes",+ "changes.git.whyParallel":+ "These steps run at the same time, each in its own workspace, which needs Git. Without it they take turns.",+ "changes.git.whyChanges": "Seeing all uncommitted changes, discarding and committing need Git.",+ "changes.git.whatMac":+ "Opens Apple's Command Line Developer Tools installer (part of macOS, a few minutes)",+ "changes.git.whatLinux":+ "Installs it with the system package manager (on this computer: {command}); the system asks for an administrator password",+ "changes.git.whatLinuxGeneric": "Installs Git with the system package manager",+ "changes.git.whereValue": "A system location every program can use",+ "changes.git.note":+ "This runs the system installer outside the sandbox, only after you click Install, and is written to the Log.",+ "changes.git.later": "Not now (take turns)",+ "changes.git.laterPlain": "Not now",+ "changes.git.install": "Install",+ "changes.git.installing": "Installing Git… (steps take turns until it's ready)",+ "changes.git.installingPlain": "Installing Git…",+ "changes.git.installingMac": "Click Install in Apple's installer window to continue.",+ "changes.git.installed": "Git is installed ({version}) · later steps can run at the same time",+ "changes.git.installedNoVersion": "Git is installed · later steps can run at the same time",+ "changes.git.installedPlain": "Git is installed ({version})",+ "changes.git.installedPlainNoVersion": "Git is installed",+ "changes.git.failed": "Not installed: run {command} in a terminal, then click Check again",+ "changes.git.failedGeneric":+ "Not installed: install Git with the system package manager, then click Check again",+ "changes.git.recheck": "Check again",+ "changes.git.error": "Couldn't start the install. Try again.","changes.repo.readonly": "Read-only","changes.repo.running": "{name} is running","changes.repo.subdirectory":diff --git a/packages/workspaces-contract/src/index.ts b/packages/workspaces-contract/src/index.tsindex 5776c11..384cdd0 100644--- a/packages/workspaces-contract/src/index.ts+++ b/packages/workspaces-contract/src/index.ts@@ -3,7 +3,12 @@ import { type ChangesEvents, ChangesMethods } from "./api/changes.ts";import { FileCheckpointMethods } from "./api/file-checkpoints.ts";import { ManagedWorktreeMethods } from "./api/managed-worktrees.ts";-export { ChangesEvents, ChangesMethods } from "./api/changes.ts";+export {+ ChangesEvents,+ ChangesMethods,+ type GitSetupStatus,+ GitSetupStatusSchema,+} from "./api/changes.ts";export { FileCheckpointMethods } from "./api/file-checkpoints.ts";export { ManagedWorktreeMethods } from "./api/managed-worktrees.ts";diff --git a/packages/workspaces/src/brain/capability.ts b/packages/workspaces/src/brain/capability.tsindex c093ee5..ba680e6 100644--- a/packages/workspaces/src/brain/capability.ts+++ b/packages/workspaces/src/brain/capability.ts@@ -3,6 +3,7 @@ import { OFFICE_COMPARE_PORT, type OfficeComparePort } from "@pibot/office-contrimport { RpcError, RpcErrorCodes } from "@pibot/workspaces-contract/full";import { registerChangesRpc } from "./changes/changes-rpc.ts";import { ChangesService } from "./changes/changes-service.ts";+import { GitSetup } from "./changes/git-setup.ts";import { createCommitDrafter } from "./changes/write/changes-draft.ts";import { GroupMemberWorktrees } from "./groups/group-member-worktrees.ts";import { registerManagedResourceRpc } from "./managed/managed-resource-rpc.ts";@@ -15,6 +16,7 @@ export function workspacesCapability(): BrainCapability {let closed = false;const pending = new Set<Promise<unknown>>();const changes = new ChangesService(ctx.workspaces.host.local);+ const gitSetup = new GitSetup(ctx.workspaces.host.local);// Absent when the office capability is not installed; the panel then stays binary.changes.office = ctx.ports.get<OfficeComparePort>(OFFICE_COMPARE_PORT);let members: GroupMemberWorktrees;@@ -46,6 +48,7 @@ export function workspacesCapability(): BrainCapability {changes.quiesce();await Promise.allSettled([...pending]);const settled = await Promise.allSettled([+ gitSetup.dispose(),resources?.dispose(),members.dispose(),changes.dispose(),@@ -87,6 +90,12 @@ export function workspacesCapability(): BrainCapability {return operation;});registerChangesRpc(handle, changes);+ handle("changes.gitStatus", (_params, { signal }) =>+ gitSetup.status(AbortSignal.any([signal, changes.signal(15_000)])),+ );+ handle("changes.gitInstall", (_params, { signal }) =>+ gitSetup.install(AbortSignal.any([signal, changes.signal(15_000)])),+ );registerManagedResourceRpc(handle, resources);return {stop: async () => {diff --git a/packages/workspaces/src/brain/changes/git-setup.ts b/packages/workspaces/src/brain/changes/git-setup.tsnew file mode 100644index 0000000..332b0d1--- /dev/null+++ b/packages/workspaces/src/brain/changes/git-setup.ts@@ -0,0 +1,178 @@+import type { WorkspaceLocal as LocalService } from "@pibot/brain/kit";+import {+ findGit,+ type GitInstallPlan,+ gitInstallPlan,+ gitVersion,+ runGitInstaller,+ waitForGit,+} from "@pibot/execution";+import { BotsRepo } from "@pibot/storage";+import type { GitSetupStatus } from "@pibot/workspaces-contract/full";++/** Apple's installer downloads and installs for several minutes; past this the card says so. */+const XCODE_WAIT_MS = 20 * 60_000;+const LINUX_SETTLE_MS = 10_000;++type Failure = NonNullable<GitSetupStatus["reason"]>;++/**+ * Installs Git system-wide when the user clicks 「安装」 on a Git card (maintainers 2026-11-21):+ * macOS and Linux only; Windows ships Git with Pi Bot. One install at a time per brain; every+ * start and end is audited with the command, never the installer's output.+ */+export class GitSetup {+ private running?: Promise<void>;+ private failure?: Failure;+ private readonly lifetime = new AbortController();+ private readonly versions = new Map<string, string | undefined>();++ constructor(private readonly local: LocalService) {}++ private get options() {+ const deps = this.local.deps;+ return { platform: deps.platform, env: deps.env, resourcesDir: deps.resourcesDir };+ }++ private async version(program: string, signal: AbortSignal) {+ if (!this.versions.has(program)) {+ const version = await gitVersion(program, signal);+ // An unanswered version is retried next time rather than remembered as unknown.+ if (version === undefined) return undefined;+ this.versions.set(program, version);+ }+ return this.versions.get(program);+ }++ private describe(plan: GitInstallPlan): Partial<GitSetupStatus> {+ if (plan.kind === "xcode")+ return { installer: "xcode", command: plan.command, manualCommand: plan.manualCommand };+ if (plan.kind === "package")+ return { installer: "package", command: plan.command, manualCommand: plan.manualCommand };+ return plan.kind === "manual" ? { installer: "manual" } : {};+ }++ async status(signal: AbortSignal): Promise<GitSetupStatus> {+ const program = await findGit(this.options);+ if (program) {+ this.failure = undefined;+ const version = await this.version(program, signal);+ return { state: "available", ...(version ? { version } : {}) };+ }+ const plan = await gitInstallPlan(this.local.deps.platform);+ if (plan.kind === "unsupported") return { state: "unsupported" };+ return {+ state: this.running ? "installing" : this.failure ? "failed" : "missing",+ ...this.describe(plan),+ ...(!this.running && this.failure ? { reason: this.failure } : {}),+ };+ }++ /** Starts the installer and answers at once; a click while one runs joins it. */+ async install(signal: AbortSignal): Promise<GitSetupStatus> {+ if (this.running || this.lifetime.signal.aborted) return this.status(signal);+ const current = await this.status(signal);+ if (current.state !== "missing" && current.state !== "failed") return current;+ const plan = await gitInstallPlan(this.local.deps.platform);+ // Re-checked after the awaits above: two clicks in the same tick start one installer.+ if (this.running) return this.status(signal);+ this.failure = undefined;+ const job = this.run(plan).finally(() => {+ if (this.running === job) this.running = undefined;+ });+ this.running = job;+ return this.status(signal);+ }++ private async run(plan: GitInstallPlan) {+ const deps = this.local.deps;+ const signal = this.lifetime.signal;+ const command =+ plan.kind === "package"+ ? plan.elevate+ ? `pkexec ${plan.command}`+ : plan.command+ : plan.kind === "xcode"+ ? plan.command+ : "";+ const started = Date.now();+ this.audit("started", command);+ let reason: Failure | "installed";+ let exitCode: number | null = null;+ try {+ const outcome = await runGitInstaller(plan, {+ platform: deps.platform,+ env: deps.env,+ signal,+ });+ exitCode = outcome.exitCode;+ if (outcome.outcome === "started" || outcome.outcome === "installed") {+ const found = await waitForGit(this.options, {+ signal,+ timeoutMs: plan.kind === "xcode" ? XCODE_WAIT_MS : LINUX_SETTLE_MS,+ intervalMs: plan.kind === "xcode" ? 3000 : 1000,+ });+ reason = found ? "installed" : signal.aborted ? "cancelled" : "timeout";+ } else reason = signal.aborted ? "cancelled" : outcome.outcome;+ } catch (error) {+ // Spawn failures resolve inside runGitInstaller; anything here is a bug worth a warning.+ deps.logger.warn(+ JSON.stringify({+ module: "workspaces",+ event: "git_install_error",+ error: error instanceof Error ? error.name : "unknown",+ }),+ );+ reason = signal.aborted ? "cancelled" : "failed";+ }+ if (reason !== "installed") this.failure = reason;+ this.audit(reason, command, { exitCode, durationMs: Date.now() - started });+ deps.logger.info(+ JSON.stringify({+ module: "workspaces",+ event: "git_install_finished",+ platform: deps.platform,+ outcome: reason,+ exitCode,+ }),+ );+ }++ private audit(+ reasonCode: Failure | "installed" | "started",+ command: string,+ extra: { exitCode?: number | null; durationMs?: number } = {},+ ) {+ const main = new BotsRepo(this.local.deps.db).getMain();+ if (!main) return;+ const platform = this.local.deps.platform;+ const shown = command || "-";+ this.local.approvals.audit.append({+ botId: main.id,+ kind: "git.install",+ summary:+ reasonCode === "started"+ ? `Git install started on ${platform}: ${shown} / 开始安装 Git(${platform}):${shown}`+ : reasonCode === "installed"+ ? `Git installed on ${platform} / Git 已安装(${platform})`+ : `Git install did not finish on ${platform} (${reasonCode}) / Git 没装上(${platform},${reasonCode})`,+ detail: {+ actor: "user",+ toolName: "git_install",+ reasonCode,+ outsideSandbox: true,+ ...(command ? { command } : {}),+ ...(extra.exitCode !== undefined ? { exitCode: extra.exitCode } : {}),+ ...(extra.durationMs !== undefined ? { durationMs: extra.durationMs } : {}),+ },+ });+ }++ /** Stops waiting (an elevated package manager may keep running; it is the system's now). */+ async dispose() {+ this.lifetime.abort();+ await this.running?.catch(() => {+ // run() never rejects; nothing is left to report once the brain stops.+ });+ }+}diff --git a/packages/workspaces/src/ui/changes/PaneSections.tsx b/packages/workspaces/src/ui/changes/PaneSections.tsxindex ee3fae1..051415f 100644--- a/packages/workspaces/src/ui/changes/PaneSections.tsx+++ b/packages/workspaces/src/ui/changes/PaneSections.tsx@@ -1,6 +1,7 @@import { useRpc, useSettings, useWorkspace } from "@pibot/renderer-kit";import { Button } from "@pibot/ui";import type { ReactNode } from "react";+import { GitInstallCard } from "../git/GitInstallCard.tsx";import styles from "./changes.module.css";import { formatCount } from "./diff/FileList.tsx";import { CommitBox } from "./history/CommitBox.tsx";@@ -193,19 +194,29 @@ export function Notices({ model }: { model: ChangesPaneModel }) {</button></Notice>,);- if (git?.state === "none" && git.reason === "git_unavailable" && scope === "turn")+ if (git?.state === "none" && git.reason === "git_unavailable")+ // macOS and Linux offer the system install here; elsewhere the download link stays.items.push(- <Notice key="git" tone="info">- <span>{t("changes.repo.noGitBody")}</span>- <a- className={styles.link}- href="https://git-scm.com/downloads"- target="_blank"- rel="noreferrer"- >- {t("changes.repo.installGit")}- </a>- </Notice>,+ <GitInstallCard+ key="git"+ context="changes"+ onInstalled={() => model.source?.refresh()}+ fallback={+ scope === "turn" && (+ <Notice tone="info">+ <span>{t("changes.repo.noGitBody")}</span>+ <a+ className={styles.link}+ href="https://git-scm.com/downloads"+ target="_blank"+ rel="noreferrer"+ >+ {t("changes.repo.installGit")}+ </a>+ </Notice>+ )+ }+ />,);if (scope === "uncommitted" && git?.state === "repo") {if (git.operation) {@@ -291,12 +302,17 @@ export function Footer({ model }: { model: ChangesPaneModel }) {/>);const notice = model.notice && (- <p- className={model.notice.error ? styles.errorText : styles.okText}- role={model.notice.error ? "alert" : "status"}- >- {t(model.notice.key, { name: model.botName })}- </p>+ <>+ <p+ className={model.notice.error ? styles.errorText : styles.okText}+ role={model.notice.error ? "alert" : "status"}+ >+ {t(model.notice.key, { name: model.botName })}+ </p>+ {model.notice.key === "changes.error.changes_git_unavailable" && (+ <GitInstallCard context="changes" onInstalled={() => model.source?.refresh()} />+ )}+ </>);const toast = model.committed && scope === "uncommitted" && (<div className={styles.toast} role="status">diff --git a/packages/workspaces/src/ui/changes/history/CommitBox.tsx b/packages/workspaces/src/ui/changes/history/CommitBox.tsxindex 89ef898..8f93507 100644--- a/packages/workspaces/src/ui/changes/history/CommitBox.tsx+++ b/packages/workspaces/src/ui/changes/history/CommitBox.tsx@@ -3,6 +3,7 @@ import { useT } from "@pibot/renderer-kit";import { Button } from "@pibot/ui";import type { GitIdentity } from "@pibot/workspaces-contract/full";import { useState } from "react";+import { GitInstallCard } from "../../git/GitInstallCard.tsx";import styles from "../changes.module.css";import { formatCount } from "../diff/FileList.tsx";import { ChangesIcon } from "../icons.tsx";@@ -142,6 +143,7 @@ export function CommitBox({{t(error)}</p>)}+ {error === "changes.error.changes_git_unavailable" && <GitInstallCard context="changes" />}<p className={styles.footNote}>{t("changes.commit.hooks")}{!writesIsolated && ` ${t("changes.commit.notIsolated")}`}diff --git a/packages/workspaces/src/ui/git/GitInstallCard.tsx b/packages/workspaces/src/ui/git/GitInstallCard.tsxnew file mode 100644index 0000000..7f12b16--- /dev/null+++ b/packages/workspaces/src/ui/git/GitInstallCard.tsx@@ -0,0 +1,227 @@+import type { TranslationKey } from "@pibot/i18n";+import { approvalStyles, useRpc, useT } from "@pibot/renderer-kit";+import { Button } from "@pibot/ui";+import type { GitSetupStatus } from "@pibot/workspaces-contract";+import { type ReactNode, useCallback, useEffect, useRef, useState } from "react";+import styles from "./git-install.module.css";++const POLL_MS = 3000;+const MARK = "\u0001";++function BranchIcon() {+ return (+ <svg+ aria-hidden="true"+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ >+ <circle cx="6" cy="5" r="2" />+ <circle cx="6" cy="19" r="2" />+ <circle cx="18" cy="8" r="2" />+ <path d="M6 7v10M18 10c0 4-6 3-12 7" />+ </svg>+ );+}++/** A translated sentence with its {command} shown as code. */+function WithCommand({ text, command }: { text: string; command: string }) {+ const [before, after] = text.split(MARK);+ return (+ <>+ {before}+ <code className={styles.code}>{command}</code>+ {after}+ </>+ );+}++/**+ * 「Pi Bot 需要安装 Git」 (maintainers 2026-11-21), shown only where a feature just needed Git: a+ * group plan whose parallel steps had to take turns ("parallel") and the changes panel or its+ * commit ("changes"). macOS and Linux only; on Windows (Git ships with Pi Bot) the brain answers+ * "unsupported" and `fallback` renders instead. The click on 「安装」 is the confirmation.+ */+export function GitInstallCard({+ context,+ onInstalled,+ fallback = null,+}: {+ context: "parallel" | "changes";+ onInstalled?: () => void;+ fallback?: ReactNode;+}) {+ const t = useT();+ const { peer } = useRpc();+ const [status, setStatus] = useState<GitSetupStatus>();+ const [dismissed, setDismissed] = useState(false);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState(false);+ const watched = useRef(false);+ const announced = useRef(false);+ const installed = useRef(onInstalled);+ installed.current = onInstalled;++ const read = useCallback(+ async (signal?: AbortSignal) => {+ if (!peer) return;+ const next = await peer.call("changes.gitStatus", {}, { timeoutMs: 20_000, signal });+ if (!signal?.aborted) setStatus(next);+ },+ [peer],+ );+ useEffect(() => {+ const abort = new AbortController();+ read(abort.signal).catch(() => {+ // Without an answer the card stays hidden; the feature's own message still explains.+ });+ return () => abort.abort();+ }, [read]);+ const state = status?.state;+ useEffect(() => {+ if (state !== "installing") return;+ watched.current = true;+ const abort = new AbortController();+ const timer = setInterval(() => {+ read(abort.signal).catch(() => {+ // A missed poll is retried on the next tick.+ });+ }, POLL_MS);+ return () => {+ clearInterval(timer);+ abort.abort();+ };+ }, [state, read]);+ useEffect(() => {+ if (state !== "available" || announced.current) return;+ announced.current = true;+ installed.current?.();+ }, [state]);++ const act = async (method: "changes.gitInstall" | "changes.gitStatus") => {+ if (!peer || busy) return;+ setBusy(true);+ setError(false);+ try {+ setStatus(await peer.call(method, {}, { timeoutMs: 20_000 }));+ if (method === "changes.gitInstall") watched.current = true;+ } catch {+ setError(true);+ } finally {+ setBusy(false);+ }+ };++ if (!status) return null;+ if (status.state === "unsupported") return <>{fallback}</>;+ const parallel = context === "parallel";+ if (status.state === "available") {+ // The changes panel only confirms an install it watched; a plan's card keeps its outcome.+ if (!parallel && !watched.current) return null;+ const key: TranslationKey = status.version+ ? parallel+ ? "changes.git.installed"+ : "changes.git.installedPlain"+ : parallel+ ? "changes.git.installedNoVersion"+ : "changes.git.installedPlainNoVersion";+ return (+ <p className={styles.state} data-tone="ok" role="status">+ <span className={styles.dot} aria-hidden="true" />+ {t(key, { version: status.version ?? "" })}+ </p>+ );+ }+ if (status.state === "installing")+ return (+ <p className={styles.state} role="status">+ <span className={styles.dot} aria-hidden="true" />+ {t(parallel ? "changes.git.installing" : "changes.git.installingPlain")}+ {status.installer === "xcode" && (+ <span className={styles.hint}>{t("changes.git.installingMac")}</span>+ )}+ </p>+ );+ if (status.state === "failed")+ return (+ <p className={styles.state} data-tone="danger" role="alert">+ <span className={styles.dot} aria-hidden="true" />+ <span>+ {status.manualCommand ? (+ <WithCommand+ text={t("changes.git.failed", { command: MARK })}+ command={status.manualCommand}+ />+ ) : (+ t("changes.git.failedGeneric")+ )}+ </span>+ <Button+ variant="secondary"+ className={styles.recheck}+ loading={busy}+ onClick={() => void act("changes.gitStatus")}+ >+ {t("changes.git.recheck")}+ </Button>+ </p>+ );+ if (dismissed) return null;+ const what =+ status.installer === "xcode" ? (+ t("changes.git.whatMac")+ ) : status.installer === "package" && status.command ? (+ <WithCommand text={t("changes.git.whatLinux", { command: MARK })} command={status.command} />+ ) : (+ t("changes.git.whatLinuxGeneric")+ );+ return (+ <section+ className={`${approvalStyles.approval} ${styles.card}`}+ data-tone="violet"+ aria-label={t("changes.git.title")}+ >+ <header>+ <span aria-hidden="true">+ <BranchIcon />+ </span>+ <strong>{t("changes.git.title")}</strong>+ </header>+ <dl className={approvalStyles.facts}>+ <div>+ <dt>{t("changes.git.why")}</dt>+ <dd>{t(parallel ? "changes.git.whyParallel" : "changes.git.whyChanges")}</dd>+ </div>+ <div>+ <dt>{t("changes.git.what")}</dt>+ <dd>{what}</dd>+ </div>+ <div>+ <dt>{t("changes.git.where")}</dt>+ <dd>{t("changes.git.whereValue")}</dd>+ </div>+ </dl>+ <p className={approvalStyles.warning}>{t("changes.git.note")}</p>+ <footer>+ {error && (+ <p role="alert" className={approvalStyles.risk}>+ {t("changes.git.error")}+ </p>+ )}+ <div className={approvalStyles.actions}>+ <Button variant="secondary" disabled={busy} onClick={() => setDismissed(true)}>+ {t(parallel ? "changes.git.later" : "changes.git.laterPlain")}+ </Button>+ <Button loading={busy} disabled={!peer} onClick={() => void act("changes.gitInstall")}>+ {t("changes.git.install")}+ </Button>+ </div>+ </footer>+ </section>+ );+}diff --git a/packages/workspaces/src/ui/git/git-install.module.css b/packages/workspaces/src/ui/git/git-install.module.cssnew file mode 100644index 0000000..54f8267--- /dev/null+++ b/packages/workspaces/src/ui/git/git-install.module.css@@ -0,0 +1,50 @@+/* The Git card reuses the shared approval card; only the state line and code chips are its own. */+.card {+ max-width: 640px;+}+.code {+ padding: 1px 6px;+ border-radius: 6px;+ background: var(--tert);+ color: var(--text);+ font-family: var(--font-mono);+ font-size: 12.5px;+ overflow-wrap: anywhere;+}+.state {+ display: inline-flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 8px;+ width: fit-content;+ max-width: 100%;+ box-sizing: border-box;+ margin: 8px 0;+ padding: 6px 14px;+ border-radius: 999px;+ background: var(--card);+ color: var(--text);+ box-shadow: 0 0 0 1px var(--b1);+ font-size: 13px;+ overflow-wrap: anywhere;+}+.dot {+ flex: none;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: var(--prim);+}+.state[data-tone="ok"] .dot {+ background: var(--ok);+}+.state[data-tone="danger"] .dot {+ background: var(--danger);+}+.hint {+ color: var(--text2);+}+.recheck {+ min-height: 26px;+ padding: 2px 12px;+}diff --git a/packages/workspaces/src/ui/index.ts b/packages/workspaces/src/ui/index.tsindex e063f2d..c68570a 100644--- a/packages/workspaces/src/ui/index.ts+++ b/packages/workspaces/src/ui/index.ts@@ -6,4 +6,5 @@ export { TurnCard } from "./changes/history/TurnCard.tsx";export { ChangesIcon } from "./changes/icons.tsx";export type { SourceState } from "./changes/store.ts";export { useChatChanges } from "./changes/use-chat-changes.ts";+export { GitInstallCard } from "./git/GitInstallCard.tsx";export { type WorkspacesUiPorts, WorkspacesUiProvider } from "./shell/ports.tsx";