Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(desktop): bundle macrod and add one-click local agent runtime setup (#8358)

Eric Hayescf039da2dcce
diff --git a/apps/docs/AI/bring-your-own.mdx b/apps/docs/AI/bring-your-own.mdx
index f72d0ca44c..d23748f34e 100644
--- a/apps/docs/AI/bring-your-own.mdx
+++ b/apps/docs/AI/bring-your-own.mdx
@@ -11,12 +11,14 @@ An **agent** combines a name, instructions, a default model, and a runtime.
A **runtime** is the harness that powers it: Macro AI, a built-in coding harness, or an agent running on your own machine, like your very own Claude Code.
-<Info>
-Soon, you will be able to bring your own local coding agents to Macro via the Macro Desktop App. You'll be able to @claude and this will route to a Claude Code running on your own computer automatically. In the meantime, you can use `macrod`, a CLI based tool to bring your local agents to Macro.
-</Info>
-
Manage both in **Settings → General → Agents**. Connect your machine in **Runtimes**, then create an agent that uses it in **Agents**.
+## On the Macro desktop app
+
+The desktop app bundles `macrod`, so there is nothing to download. Open **Settings → General → Agents → Runtimes** and use the **This computer** card: **Set up** detects the coding agents installed on your machine, you pick one and a workspace folder, and **Start running agents here** configures, pairs, and starts the runtime automatically — no terminal and no pairing code. Keep the app open while agents run.
+
+The manual `macrod` steps below are for machines without the desktop app (servers, a second computer), and both kinds of runtime can be paired to the same account.
+
## Macro daemon
Use your local coding agent from Macro. `macrod` runs on your computer, connects your agent to Macro, and keeps its sessions available from your workspace.
diff --git a/apps/web/src/features/agents-view/core/roster.test.ts b/apps/web/src/features/agents-view/core/roster.test.ts
index 74b7c92b86..8a0ece3a9e 100644
--- a/apps/web/src/features/agents-view/core/roster.test.ts
+++ b/apps/web/src/features/agents-view/core/roster.test.ts
@@ -100,6 +100,7 @@ describe('buildAgentRoster', () => {
connected: false,
});
expect(saved[2]?.unavailableReason).toBe('Its runtime is disconnected');
+ expect(saved[2]?.connectLabel).toBe('Reconnect runtime');
expect(saved[3]?.runtime.label).toBe('Disconnected runtime');
});
diff --git a/apps/web/src/features/agents-view/core/roster.ts b/apps/web/src/features/agents-view/core/roster.ts
index 2ca792ed14..1da4feb786 100644
--- a/apps/web/src/features/agents-view/core/roster.ts
+++ b/apps/web/src/features/agents-view/core/roster.ts
@@ -158,7 +158,9 @@ function persistedAgent(
connectLabel:
agent.harness === 'cursor' && input.cursorNeedsConnection
? 'Connect Cursor'
- : undefined,
+ : agent.harness === 'macrod' && !connected
+ ? 'Reconnect runtime'
+ : undefined,
unavailableReason:
agent.harness === 'macrod' && !connected
? 'Its runtime is disconnected'
diff --git a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx b/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
index 7d20b050ad..e989e1f829 100644
--- a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
+++ b/apps/web/src/features/agents-view/views/NewChatPage.test.tsx
@@ -706,7 +706,7 @@ describe('agent-led new conversation', () => {
});
});
- it('keeps a disconnected paired agent visible with its availability reason', () => {
+ it('keeps a disconnected paired agent visible and offers to reconnect it', () => {
page(
true,
[
@@ -723,8 +723,11 @@ describe('agent-led new conversation', () => {
);
openAgents();
const row = screen.getByRole('menuitem', { name: /Laptop agent/ });
- expect(row.getAttribute('aria-disabled')).toBe('true');
- expect(row.textContent).toContain('Its runtime is disconnected');
+ // The row stays clickable: selecting it opens Settings → Runtimes, where
+ // the runtime can be restarted (one click on desktop) or re-paired.
+ expect(row.getAttribute('aria-disabled')).not.toBe('true');
+ expect(row.getAttribute('title')).toBe('Its runtime is disconnected');
+ expect(row.textContent).toContain('Reconnect runtime');
});
it.each([false, true])(
@@ -752,13 +755,14 @@ describe('agent-led new conversation', () => {
}).filter((agent) => agent.kind === 'coder');
const onCreate = vi.fn();
const onSelect = vi.fn();
+ const onConnect = vi.fn();
render(() => (
<AgentPicker
agents={roster}
selected={roster[0]}
loading={false}
onSelect={onSelect}
- onConnect={vi.fn()}
+ onConnect={onConnect}
onCreate={onCreate}
/>
));
@@ -774,7 +778,9 @@ describe('agent-led new conversation', () => {
expect(saved.textContent).toContain('Reviewer');
expect(saved.textContent).toContain('Laptop · Sonnet 5.5');
expect(offline.textContent).toContain('Offline agent');
- expect(offline.textContent).toContain('Its runtime is disconnected');
+ // The disconnected row stays clickable: it offers to reconnect the
+ // runtime (opens Settings → Runtimes) and keeps the reason as a tooltip.
+ expect(offline.textContent).toContain('Reconnect runtime');
expect(
within(picker).queryByText('Connect the runtime to load models.')
).toBeNull();
@@ -782,13 +788,26 @@ describe('agent-led new conversation', () => {
const unavailable = within(offline).getByRole(
touch ? 'button' : 'menuitem'
);
+ // The desktop row keeps the reason as a tooltip; the drawer row has no
+ // title attribute.
+ if (!touch) {
+ expect(unavailable.getAttribute('title')).toBe(
+ 'Its runtime is disconnected'
+ );
+ }
expect(
touch
? unavailable.hasAttribute('disabled')
: unavailable.getAttribute('aria-disabled') === 'true'
- ).toBe(true);
- fireEvent.click(unavailable);
- expect(onSelect).not.toHaveBeenCalled();
+ ).toBe(false);
+ if (touch) {
+ fireEvent.click(unavailable);
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onConnect).toHaveBeenCalledOnce();
+ // Connecting closes the drawer; reopen it for the create assertion.
+ fireEvent.click(screen.getByRole('button', { name: 'Agent' }));
+ await screen.findByRole('dialog');
+ }
const create = within(picker).getByRole(touch ? 'button' : 'menuitem', {
name: 'Create agent',
});
diff --git a/apps/web/src/features/agents-view/views/NewChatPage.tsx b/apps/web/src/features/agents-view/views/NewChatPage.tsx
index 5e830b5b1d..55d52b9284 100644
--- a/apps/web/src/features/agents-view/views/NewChatPage.tsx
+++ b/apps/web/src/features/agents-view/views/NewChatPage.tsx
@@ -222,7 +222,11 @@ export function NewChatPage(props: {
};
const connect = (agent: RosterAgent) => {
- if (agent.harness === 'cursor') openSettings('Harness');
+ // Both land on Settings → Runtimes: Cursor to save an API key, macrod to
+ // restart the local runtime (one click on desktop) or re-pair it.
+ if (agent.harness === 'cursor' || agent.harness === 'macrod') {
+ openSettings('Harness');
+ }
};
const attachmentTracker = createMemo(() => {
diff --git a/apps/web/src/features/routines/views/routine-execution-picker.test.tsx b/apps/web/src/features/routines/views/routine-execution-picker.test.tsx
index 642eba2483..7c007bea17 100644
--- a/apps/web/src/features/routines/views/routine-execution-picker.test.tsx
+++ b/apps/web/src/features/routines/views/routine-execution-picker.test.tsx
@@ -366,14 +366,18 @@ describe('routine execution picker', () => {
'Its runtime is disconnected'
);
let trigger = openPicker();
- expect(
- screen
- .getByRole('menuitem', { name: /Local worker/ })
- .getAttribute('aria-disabled')
- ).toBe('true');
+ // A disconnected macrod agent stays clickable: selecting it is the
+ // reconnect path (opens Settings → Runtimes) rather than a dead row.
+ const reconnect = screen.getByRole('menuitem', { name: /Local worker/ });
+ expect(reconnect.getAttribute('aria-disabled')).not.toBe('true');
+ expect(reconnect.textContent).toContain('Reconnect runtime');
+ fireEvent.keyDown(reconnect, { key: 'Enter' });
+ expect(onConnect.mock.calls[0][0].harness).toBe('macrod');
+ await expectClosed(trigger);
+ trigger = openPicker();
const connect = screen.getByRole('menuitem', { name: /Connect Cursor/ });
fireEvent.keyDown(connect, { key: 'Enter' });
- expect(onConnect.mock.calls[0][0].harness).toBe('cursor');
+ expect(onConnect.mock.calls[1][0].harness).toBe('cursor');
await expectClosed(trigger);
trigger = openPicker();
fireEvent.keyDown(screen.getByRole('menuitem', { name: 'Create agent' }), {
diff --git a/apps/web/src/features/settings/Harness.tsx b/apps/web/src/features/settings/Harness.tsx
index a0e666ebe3..f1ad95796d 100644
--- a/apps/web/src/features/settings/Harness.tsx
+++ b/apps/web/src/features/settings/Harness.tsx
@@ -23,6 +23,7 @@ import { createSignal, For, onMount, Show } from 'solid-js';
import { ClaudeConnection } from '../claude-connection/claude-connection';
import { CodexHarness } from './codex/views/CodexHarness';
import { CursorDefaultModel } from './components/cursor-default-model';
+import { LocalRuntimeCard } from './components/local-runtime-card';
import {
CURSOR_KEY_FORMAT_ERROR,
CURSOR_KEY_PLACEHOLDER,
@@ -143,6 +144,7 @@ export function Harness(props: { onBack?: () => void } = {}) {
</Button>
}
>
+ <LocalRuntimeCard />
<div>
<h2 class="mb-3 px-6 text-sm font-semibold text-ink">
Built-in runtimes
diff --git a/apps/web/src/features/settings/components/local-runtime-card.tsx b/apps/web/src/features/settings/components/local-runtime-card.tsx
new file mode 100644
index 0000000000..f2cccdddfb
--- /dev/null
+++ b/apps/web/src/features/settings/components/local-runtime-card.tsx
@@ -0,0 +1,501 @@
+import { toast } from '@core/component/Toast/Toast';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { isDesktopPlatform } from '@core/util/platform';
+import {
+ type MacrodDetectedAgent,
+ type MacrodStatus as MacrodSnapshot,
+ type MacrodSupport,
+ macrodDetectAgents,
+ macrodInspect,
+ macrodStart,
+ macrodStatus,
+ macrodStop,
+ macrodSupport,
+ onMacrodStatus,
+} from '@macro/tauri/macrod';
+import LaptopIcon from '@phosphor/laptop.svg';
+import SpinnerIcon from '@phosphor/spinner-gap.svg';
+import { useApproveHarnessPairingMutation } from '@queries/harnesses/harnesses';
+import type { UnlistenFn } from '@tauri-apps/api/event';
+import { Button } from '@ui';
+import {
+ createSignal,
+ Match,
+ onCleanup,
+ onMount,
+ Show,
+ Switch,
+} from 'solid-js';
+import { HarnessIcon, StatusDot } from '../integration-ui';
+import { SettingsCard } from '../primitives';
+import { SettingsSelect } from './settings-select';
+
+function errorMessage(error: unknown, fallback: string): string {
+ if (typeof error === 'string' && error.length > 0) return error;
+ if (error instanceof Error && error.message) return error.message;
+ return fallback;
+}
+
+/**
+ * One-click local runtime on the desktop app: the bundled macrod daemon is
+ * configured, paired, and supervised without the user touching a terminal.
+ * The card detects which coding agents are installed on this computer, and
+ * approving the pairing happens automatically — the daemon reports its code
+ * over the sidecar channel and this card approves it with the signed-in
+ * session, so no code is ever typed.
+ */
+export function LocalRuntimeCard() {
+ // Everything here talks to the Tauri main process; on other platforms the
+ // card renders nothing and calls nothing.
+ if (!isDesktopPlatform()) return null;
+
+ const approvePairing = useApproveHarnessPairingMutation();
+ const [support, setSupport] = createSignal<MacrodSupport>();
+ const [snapshot, setSnapshot] = createSignal<MacrodSnapshot>();
+ /** Whether a paired config already exists on disk (daemon may be stopped). */
+ const [paired, setPaired] = createSignal(false);
+ const [setupOpen, setSetupOpen] = createSignal(false);
+ const [agents, setAgents] = createSignal<MacrodDetectedAgent[]>();
+ const [scanning, setScanning] = createSignal(false);
+ const [selectedAgent, setSelectedAgent] = createSignal<string>();
+ const [workspace, setWorkspace] = createSignal('');
+ const [fullAccess, setFullAccess] = createSignal(false);
+ const [busy, setBusy] = createSignal(false);
+ const [approveFailed, setApproveFailed] = createSignal(false);
+
+ // One approval attempt per pairing code; a failed attempt surfaces a Retry
+ // affordance instead of hammering the endpoint from the status stream.
+ const attemptedCodes = new Set<string>();
+
+ const approveCode = (code: string) => {
+ attemptedCodes.add(code);
+ setApproveFailed(false);
+ approvePairing.mutate(
+ { code, allowPermissionBypass: fullAccess() },
+ {
+ onError: () => setApproveFailed(true),
+ }
+ );
+ };
+
+ const handleStatus = (next: MacrodSnapshot) => {
+ setSnapshot(next);
+ if (next.phase === 'running') setPaired(true);
+ if (
+ next.phase === 'pairing' &&
+ next.pairingCode &&
+ !attemptedCodes.has(next.pairingCode)
+ ) {
+ approveCode(next.pairingCode);
+ }
+ };
+
+ onMount(() => {
+ let disposed = false;
+ let unlisten: UnlistenFn | undefined;
+ const probe = async () => {
+ try {
+ const [supportInfo, current] = await Promise.all([
+ macrodSupport(),
+ macrodStatus(),
+ ]);
+ if (disposed) return;
+ setSupport(supportInfo);
+ if (!workspace() && supportInfo.defaultWorkspace) {
+ setWorkspace(supportInfo.defaultWorkspace);
+ }
+ handleStatus(current);
+ if (!supportInfo.supported) return;
+ unlisten = await onMacrodStatus(handleStatus);
+ if (disposed) {
+ fireAndForget(unlisten(), 'local-runtime-card');
+ return;
+ }
+ const inspection = await macrodInspect();
+ if (!disposed && inspection.paired) setPaired(true);
+ } catch (error) {
+ console.error('could not probe the bundled macrod daemon', error);
+ }
+ };
+ fireAndForget(probe(), 'local-runtime-card');
+ onCleanup(() => {
+ disposed = true;
+ const dispose = unlisten;
+ if (dispose) fireAndForget(dispose(), 'local-runtime-card');
+ });
+ });
+
+ const scanAgents = async () => {
+ setScanning(true);
+ try {
+ const found = await macrodDetectAgents();
+ setAgents(found);
+ if (found.length > 0 && !found.some((a) => a.id === selectedAgent())) {
+ setSelectedAgent(found[0].id);
+ }
+ } catch (error) {
+ setAgents([]);
+ toast.failure(
+ errorMessage(error, 'Could not scan this computer for agents')
+ );
+ } finally {
+ setScanning(false);
+ }
+ };
+
+ const openSetup = () => {
+ setSetupOpen(true);
+ // scanAgents reports its own failures through the toast.
+ fireAndForget(scanAgents(), 'local-runtime-card');
+ };
+
+ const startWithSetup = async () => {
+ const agent = selectedAgent();
+ if (!agent || busy()) return;
+ setBusy(true);
+ try {
+ await macrodStart({
+ agent,
+ workspace: workspace().trim() || undefined,
+ scope: 'private',
+ allowPermissionBypass: fullAccess(),
+ });
+ setSetupOpen(false);
+ } catch (error) {
+ toast.failure(errorMessage(error, 'Could not start the local runtime'));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const startExisting = async () => {
+ if (busy()) return;
+ setBusy(true);
+ try {
+ await macrodStart({});
+ } catch (error) {
+ toast.failure(errorMessage(error, 'Could not start the local runtime'));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const stop = async () => {
+ if (busy()) return;
+ setBusy(true);
+ try {
+ await macrodStop();
+ } catch (error) {
+ toast.failure(errorMessage(error, 'Could not stop the local runtime'));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const phase = () => snapshot()?.phase ?? 'stopped';
+ const working = () =>
+ phase() === 'starting' ||
+ phase() === 'installing-adapter' ||
+ phase() === 'pairing';
+
+ return (
+ <Show when={support()?.supported}>
+ <div>
+ <h2 class="mb-3 px-6 text-sm font-semibold text-ink">This computer</h2>
+ <SettingsCard>
+ <section class="flex gap-4 px-6 py-5">
+ <HarnessIcon>
+ <LaptopIcon />
+ </HarnessIcon>
+ <div class="min-w-0 flex-1">
+ <div class="flex min-h-5 items-center justify-between gap-3">
+ <div class="flex min-w-0 items-center gap-2">
+ <h2 class="min-w-0 text-sm/5 font-medium text-ink">
+ Run agents on this computer
+ </h2>
+ <StatusDot
+ state={
+ phase() === 'running'
+ ? 'connected'
+ : phase() === 'error'
+ ? 'attention'
+ : 'disconnected'
+ }
+ label={
+ phase() === 'running'
+ ? 'Running'
+ : phase() === 'error'
+ ? 'Error'
+ : 'Not running'
+ }
+ />
+ </div>
+ <Show when={phase() === 'running'}>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={busy()}
+ onClick={() => fireAndForget(stop(), 'local-runtime-card')}
+ >
+ Stop
+ </Button>
+ </Show>
+ </div>
+ <p class="mt-1 text-sm text-ink-muted">
+ Macro runs agents you already have installed — Claude Code,
+ Codex, and more — right here on your machine, using your own
+ subscriptions and your local files.
+ </p>
+
+ <Switch>
+ <Match when={working()}>
+ <div class="mt-4 flex items-center gap-2 text-sm text-ink-muted">
+ <SpinnerIcon class="size-4 animate-spin" />
+ <Switch>
+ <Match when={phase() === 'installing-adapter'}>
+ Installing the agent adapter…
+ </Match>
+ <Match when={phase() === 'pairing'}>
+ <Show
+ when={!approveFailed()}
+ fallback={
+ <span class="flex items-center gap-2">
+ Could not connect this computer.
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ const code = snapshot()?.pairingCode;
+ if (code) approveCode(code);
+ }}
+ >
+ Retry
+ </Button>
+ </span>
+ }
+ >
+ Connecting this computer to your account…
+ </Show>
+ </Match>
+ <Match when>Starting…</Match>
+ </Switch>
+ </div>
+ </Match>
+
+ <Match when={phase() === 'running'}>
+ <p class="mt-4 text-sm text-ink-muted">
+ <span class="font-medium text-ink">
+ {snapshot()?.agentName ?? 'Your agent'}
+ </span>{' '}
+ is ready
+ <Show when={snapshot()?.workspace}>
+ {(dir) => (
+ <>
+ {' '}
+ in <span class="font-mono text-xs">{dir()}</span>
+ </>
+ )}
+ </Show>
+ . Keep the app open; create an agent below to start using
+ it.
+ </p>
+ </Match>
+
+ <Match when={phase() === 'error'}>
+ <div class="mt-4 flex flex-wrap items-center gap-3">
+ <p class="text-sm text-negative">
+ {snapshot()?.lastError ?? 'The local runtime stopped.'}
+ </p>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={busy()}
+ onClick={() =>
+ paired()
+ ? fireAndForget(startExisting(), 'local-runtime-card')
+ : openSetup()
+ }
+ >
+ Try again
+ </Button>
+ </div>
+ </Match>
+
+ <Match when={setupOpen()}>
+ <div class="mt-4 flex flex-col gap-4">
+ <Show
+ when={!scanning()}
+ fallback={
+ <p class="flex items-center gap-2 text-sm text-ink-muted">
+ <SpinnerIcon class="size-4 animate-spin" />
+ Looking for agents installed on this computer…
+ </p>
+ }
+ >
+ <Show
+ when={(agents()?.length ?? 0) > 0}
+ fallback={
+ <div class="flex flex-col gap-2">
+ <p class="text-sm text-ink-muted">
+ No supported agents were found on this computer.
+ Install Claude Code, Codex, OpenCode, or OpenClaw,
+ then scan again.
+ </p>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ class="w-fit"
+ onClick={() =>
+ fireAndForget(
+ scanAgents(),
+ 'local-runtime-card'
+ )
+ }
+ >
+ Scan again
+ </Button>
+ </div>
+ }
+ >
+ <div class="flex w-full max-w-72 flex-col gap-1.5">
+ <span class="text-xs font-medium text-ink">
+ Agent found on this computer
+ </span>
+ <SettingsSelect
+ label="Agent"
+ options={(agents() ?? []).map((agent) => ({
+ id: agent.id,
+ name: agent.name,
+ }))}
+ value={selectedAgent()}
+ onChange={setSelectedAgent}
+ />
+ <Show
+ when={
+ agents()?.find((a) => a.id === selectedAgent())
+ ?.needs_install
+ }
+ fallback={
+ <p class="text-xs text-ink-extra-muted">
+ Sessions run with your existing login and
+ subscription.
+ </p>
+ }
+ >
+ <p class="text-xs text-ink-extra-muted">
+ A small connector is downloaded on first start;
+ sessions run with your existing login and
+ subscription.
+ </p>
+ </Show>
+ </div>
+ <div class="flex w-full max-w-72 flex-col gap-1.5">
+ <label
+ for="local-runtime-workspace"
+ class="text-xs font-medium text-ink"
+ >
+ Workspace folder
+ </label>
+ <input
+ id="local-runtime-workspace"
+ type="text"
+ spellcheck={false}
+ class="settings-input min-w-0"
+ value={workspace()}
+ onInput={(event) =>
+ setWorkspace(event.currentTarget.value)
+ }
+ />
+ <p class="text-xs text-ink-extra-muted">
+ Where sessions run. Created if it doesn't exist.
+ </p>
+ </div>
+ <label class="flex w-fit items-start gap-2 text-sm text-ink">
+ <input
+ type="checkbox"
+ class="mt-0.5"
+ checked={fullAccess()}
+ onChange={(event) =>
+ setFullAccess(event.currentTarget.checked)
+ }
+ />
+ <span>
+ Full access
+ <span class="block text-xs text-ink-extra-muted">
+ Let agents run commands and edit files without
+ asking each time.
+ </span>
+ </span>
+ </label>
+ <div class="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="cta"
+ size="sm"
+ disabled={busy() || !selectedAgent()}
+ onClick={() =>
+ fireAndForget(
+ startWithSetup(),
+ 'local-runtime-card'
+ )
+ }
+ >
+ {busy() ? 'Starting…' : 'Start running agents here'}
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setSetupOpen(false)}
+ >
+ Cancel
+ </Button>
+ </div>
+ </Show>
+ </Show>
+ </div>
+ </Match>
+
+ <Match when={paired()}>
+ <div class="mt-4 flex flex-wrap items-center gap-3">
+ <p class="text-sm text-ink-muted">
+ This computer is set up but not running.
+ </p>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={busy()}
+ onClick={() =>
+ fireAndForget(startExisting(), 'local-runtime-card')
+ }
+ >
+ {busy() ? 'Starting…' : 'Start'}
+ </Button>
+ </div>
+ </Match>
+
+ <Match when>
+ <div class="mt-4">
+ <Button
+ type="button"
+ variant="cta"
+ size="sm"
+ onClick={openSetup}
+ >
+ Set up
+ </Button>
+ </div>
+ </Match>
+ </Switch>
+ </div>
+ </section>
+ </SettingsCard>
+ </div>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/settings/components/runtime-setup-steps.tsx b/apps/web/src/features/settings/components/runtime-setup-steps.tsx
index b3ce35fe50..3d55420943 100644
--- a/apps/web/src/features/settings/components/runtime-setup-steps.tsx
+++ b/apps/web/src/features/settings/components/runtime-setup-steps.tsx
@@ -1,6 +1,7 @@
+import { isDesktopPlatform } from '@core/util/platform';
import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';
import { cn } from '@ui';
-import type { JSX } from 'solid-js';
+import { type JSX, Show } from 'solid-js';
/** One numbered step in a connection guide; steps share a connecting rail. */
export function SetupStep(props: {
@@ -57,37 +58,47 @@ export function SetupField(props: { class?: string; children: JSX.Element }) {
/** Installation instructions surrounding the live pairing-code form. */
export function RuntimeSetupSteps(props: { children: JSX.Element }) {
return (
- <ol aria-label="Runtime setup steps" class="list-none">
- <SetupStep number={1} title="Install macrod">
- <p>Download the macrod archive for your computer, then extract it.</p>
- <SetupLink href="https://github.com/macro-inc/macro/releases">
- Download macrod
- </SetupLink>
- </SetupStep>
- <SetupStep number={2} title="Run macrod">
- <p>Open a terminal in the extracted folder and run:</p>
- <div class="rounded-lg border border-edge-muted bg-ink/[0.025] px-3 py-2 font-mono text-sm text-ink">
- <span
- aria-hidden="true"
- class="mr-2 select-none text-ink-extra-muted"
- >
- $
- </span>
- <code>./macrod</code>
- </div>
- <p>
- Choose your agent, workspace, and access in Quickstart, then select{' '}
- <span class="font-medium text-ink">Create and pair</span>. Keep macrod
- running.
- </p>
- </SetupStep>
- <SetupStep number={3} title="Enter your pairing code">
- <p>
- Enter the device code from your terminal to review and connect this
- runtime.
+ <>
+ <Show when={isDesktopPlatform()}>
+ <p class="mb-6 rounded-lg border border-edge-muted bg-ink/[0.025] px-3 py-2 text-sm text-ink-muted">
+ Setting up this computer? The desktop app bundles the runtime — use
+ the <span class="font-medium text-ink">This computer</span> card on
+ the Runtimes page instead; no download or pairing code needed. The
+ steps below connect a different machine.
</p>
- {props.children}
- </SetupStep>
- </ol>
+ </Show>
+ <ol aria-label="Runtime setup steps" class="list-none">
+ <SetupStep number={1} title="Install macrod">
+ <p>Download the macrod archive for your computer, then extract it.</p>
+ <SetupLink href="https://github.com/macro-inc/macro/releases">
+ Download macrod
+ </SetupLink>
+ </SetupStep>
+ <SetupStep number={2} title="Run macrod">
+ <p>Open a terminal in the extracted folder and run:</p>
+ <div class="rounded-lg border border-edge-muted bg-ink/[0.025] px-3 py-2 font-mono text-sm text-ink">
+ <span
+ aria-hidden="true"
+ class="mr-2 select-none text-ink-extra-muted"
+ >
+ $
+ </span>
+ <code>./macrod</code>
+ </div>
+ <p>
+ Choose your agent, workspace, and access in Quickstart, then select{' '}
+ <span class="font-medium text-ink">Create and pair</span>. Keep
+ macrod running.
+ </p>
+ </SetupStep>
+ <SetupStep number={3} title="Enter your pairing code">
+ <p>
+ Enter the device code from your terminal to review and connect this
+ runtime.
+ </p>
+ {props.children}
+ </SetupStep>
+ </ol>
+ </>
);
}
diff --git a/apps/web/src/features/settings/core/settings-search.ts b/apps/web/src/features/settings/core/settings-search.ts
index a0dd377e1c..1be422c0ec 100644
--- a/apps/web/src/features/settings/core/settings-search.ts
+++ b/apps/web/src/features/settings/core/settings-search.ts
@@ -95,6 +95,12 @@ const SETTINGS: Setting[] = [
title: 'Agent runtimes and credentials',
keywords: 'cursor harness runtime api key provider pairing daemon',
},
+ {
+ tab: 'Harness',
+ title: 'Run agents on this computer',
+ keywords:
+ 'local runtime macrod this computer machine claude code codex desktop daemon',
+ },
{
tab: 'Account',
title: 'Profile picture',
diff --git a/apps/web/src/lib/core/util/platform.ts b/apps/web/src/lib/core/util/platform.ts
index 3fcdb731f0..b3532ddc27 100644
--- a/apps/web/src/lib/core/util/platform.ts
+++ b/apps/web/src/lib/core/util/platform.ts
@@ -33,7 +33,8 @@ function isMobilePlatform(platform: MacroPlatform = getPlatform()): boolean {
return platform === 'ios' || platform === 'android';
}
-function _isDesktopPlatform(): boolean {
+/** Whether this is the desktop (Tauri) app on macOS/Windows/Linux. */
+export function isDesktopPlatform(): boolean {
return isPlatform('desktop');
}
diff --git a/apps/web/src/lib/tauri/macrod.ts b/apps/web/src/lib/tauri/macrod.ts
new file mode 100644
index 0000000000..d27b2d40e4
--- /dev/null
+++ b/apps/web/src/lib/tauri/macrod.ts
@@ -0,0 +1,104 @@
+import { invoke } from '@tauri-apps/api/core';
+import { listen, type UnlistenFn } from '@tauri-apps/api/event';
+
+/**
+ * Bridge to the bundled macrod daemon (the local agent runtime) supervised by
+ * the desktop app's main process. Desktop only: callers gate on
+ * `isDesktopPlatform()` before touching anything here.
+ */
+
+export type MacrodPhase =
+ | 'stopped'
+ | 'starting'
+ | 'installing-adapter'
+ | 'pairing'
+ | 'running'
+ | 'error';
+
+/** The daemon snapshot the main process folds service events into. */
+export type MacrodStatus = {
+ phase: MacrodPhase;
+ agentId: string | null;
+ agentName: string | null;
+ workspace: string | null;
+ /** Open pairing code awaiting approval, `XXXX-XXXX`. */
+ pairingCode: string | null;
+ pairingExpiresAt: string | null;
+ harnessId: string | null;
+ lastError: string | null;
+};
+
+export type MacrodSupport = {
+ /** Whether this build bundles the daemon on this platform. */
+ supported: boolean;
+ /** Suggested workspace directory for a first-time setup. */
+ defaultWorkspace: string | null;
+};
+
+/** One installed agent, as reported by `macrod detect-agents`. */
+export type MacrodDetectedAgent = {
+ /** Stable preset id accepted by {@link macrodStart}, e.g. `claude-code`. */
+ id: string;
+ name: string;
+ note: string | null;
+ /** Whether selecting this agent downloads an ACP adapter first. */
+ needs_install: boolean;
+};
+
+/** The service config's state, as reported by `macrod inspect`. */
+export type MacrodInspection = {
+ config_path: string;
+ exists: boolean;
+ paired: boolean;
+ error?: string;
+ harness_id?: string;
+ agent_id?: string;
+ agent_name?: string;
+ workspace?: string;
+ web_url?: string;
+};
+
+export type MacrodStartOptions = {
+ agent?: string;
+ workspace?: string;
+ scope?: 'private' | 'team';
+ allowPermissionBypass?: boolean;
+};
+
+export function macrodSupport(): Promise<MacrodSupport> {
+ return invoke<MacrodSupport>('macrod_support');
+}
+
+export async function macrodDetectAgents(): Promise<MacrodDetectedAgent[]> {
+ const result = await invoke<{ agents: MacrodDetectedAgent[] }>(
+ 'macrod_detect_agents'
+ );
+ return result.agents;
+}
+
+export function macrodInspect(): Promise<MacrodInspection> {
+ return invoke<MacrodInspection>('macrod_inspect');
+}
+
+export function macrodStart(
+ options: MacrodStartOptions
+): Promise<MacrodStatus> {
+ return invoke<MacrodStatus>('macrod_start', { options });
+}
+
+export function macrodStop(): Promise<MacrodStatus> {
+ return invoke<MacrodStatus>('macrod_stop');
+}
+
+export function macrodStatus(): Promise<MacrodStatus> {
+ return invoke<MacrodStatus>('macrod_status');
+}
+
+/** Subscribe to daemon snapshot changes; resolves to the unlisten function. */
+export function onMacrodStatus(
+ callback: (status: MacrodStatus) => void
+): Promise<UnlistenFn> {
+ return listen<MacrodStatus>('macrod-status', (event) =>
+ callback(event.payload)
+ );
+}
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index 8b1a3ee3aa..cfeedd8cdc 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -41,6 +41,7 @@ mod linux_notification;
mod logging;
#[cfg(target_os = "macos")]
mod macos_notification_permission;
+mod macrod;
mod share_target;
mod staged_upload;
#[cfg(desktop)]
@@ -335,6 +336,7 @@ pub fn run() {
.manage(DeepLinkDelivery::default())
.manage(graphql_cache_plugin::CacheState::default())
.manage(IsIpad(is_ipad_device))
+ .manage(macrod::MacrodState::default())
.invoke_handler(tauri::generate_handler![
desktop_update::get_native_update_status,
desktop_update::restart_native_update,
@@ -388,6 +390,12 @@ pub fn run() {
read_shared_file_text,
flush_launch_deep_link,
staged_upload::upload_staged_file_to_presigned_url,
+ macrod::macrod_support,
+ macrod::macrod_detect_agents,
+ macrod::macrod_inspect,
+ macrod::macrod_start,
+ macrod::macrod_stop,
+ macrod::macrod_status,
])
.setup(move |app| {
#[cfg(desktop)]
@@ -412,6 +420,7 @@ pub fn run() {
app.chain(attach_deep_link_handler);
cleanup_stale_staged_files(&app.handle());
+ macrod::autostart(&app.handle());
Ok(())
})
@@ -480,6 +489,11 @@ pub fn run() {
desktop_update::on_exit_requested(app_handle, api)
}
RunEvent::Exit => {
+ if let Some(state) = app_handle.try_state::<macrod::MacrodState>() {
+ // The daemon also exits on its own when its stdin pipe
+ // closes with this process; the kill is the fast path.
+ macrod::kill_now(&state);
+ }
if let Some(state) = app_handle.try_state::<graphql_cache_plugin::CacheState>() {
state
.shutdown()
diff --git a/apps/web/tauri/src-tauri/src/macrod.rs b/apps/web/tauri/src-tauri/src/macrod.rs
new file mode 100644
index 0000000000..f91bbfa57d
--- /dev/null
+++ b/apps/web/tauri/src-tauri/src/macrod.rs
@@ -0,0 +1,536 @@
+//! Management of the bundled macrod daemon: the local agent runtime that
+//! lets users run coding agents on this machine.
+//!
+//! The desktop app ships the `macrod` binary next to its own executable and
+//! supervises it as a child process in `macrod service` mode. That mode
+//! reports state changes as one JSON object per line on stdout; this module
+//! folds those lines into a [`MacrodStatus`] snapshot, re-emits every change
+//! to the webview as a `macrod-status` event, and exposes commands to detect
+//! installed agents, start or stop the daemon, and read the snapshot.
+//!
+//! GUI apps on macOS inherit launchd's minimal `PATH`, where user-installed
+//! CLIs (`claude`, `codex`, `npm`) are invisible. Every macrod invocation runs
+//! with the user's login-shell `PATH` so detection matches what a terminal
+//! would see.
+
+use std::path::PathBuf;
+use std::process::Stdio;
+use std::sync::{Arc, Mutex, OnceLock};
+
+use serde::{Deserialize, Serialize};
+use tauri::{AppHandle, Emitter, Manager};
+use tokio::io::AsyncBufReadExt as _;
+
+/// The webview event carrying each [`MacrodStatus`] change.
+const STATUS_EVENT: &str = "macrod-status";
+
+/// Where the daemon lifecycle currently stands.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "kebab-case")]
+pub(crate) enum MacrodPhase {
+ Stopped,
+ Starting,
+ InstallingAdapter,
+ Pairing,
+ Running,
+ Error,
+}
+
+impl Default for MacrodPhase {
+ fn default() -> Self {
+ Self::Stopped
+ }
+}
+
+/// The daemon state snapshot the frontend renders from.
+#[derive(Debug, Clone, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct MacrodStatus {
+ pub(crate) phase: MacrodPhase,
+ /// Agent preset id from the service config, e.g. `claude-code`.
+ pub(crate) agent_id: Option<String>,
+ /// Human-readable agent name from the service config.
+ pub(crate) agent_name: Option<String>,
+ /// Workspace directory sessions run in.
+ pub(crate) workspace: Option<String>,
+ /// Open pairing code awaiting approval, `XXXX-XXXX`.
+ pub(crate) pairing_code: Option<String>,
+ /// When the open pairing expires (RFC 3339).
+ pub(crate) pairing_expires_at: Option<String>,
+ /// The registered harness once paired.
+ pub(crate) harness_id: Option<String>,
+ /// The last fatal error, kept until the next start.
+ pub(crate) last_error: Option<String>,
+}
+
+impl MacrodStatus {
+ /// Fold one service event line into this snapshot.
+ fn apply(&mut self, event: &serde_json::Value) {
+ let text = |key: &str| {
+ event
+ .get(key)
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_owned)
+ };
+ match event.get("event").and_then(serde_json::Value::as_str) {
+ Some("config") => {
+ self.agent_id = text("agent_id");
+ self.agent_name = text("agent_name");
+ self.workspace = text("workspace");
+ }
+ Some("installing_adapter") => self.phase = MacrodPhase::InstallingAdapter,
+ Some("adapter_installed") => self.phase = MacrodPhase::Starting,
+ Some("pairing") => {
+ self.phase = MacrodPhase::Pairing;
+ self.pairing_code = text("code");
+ self.pairing_expires_at = text("expires_at");
+ }
+ Some("paired") => {
+ self.pairing_code = None;
+ self.pairing_expires_at = None;
+ self.harness_id = text("harness_id");
+ }
+ Some("running") => {
+ self.phase = MacrodPhase::Running;
+ self.harness_id = text("harness_id");
+ }
+ Some("fatal") => {
+ self.phase = MacrodPhase::Error;
+ self.last_error = text("message");
+ }
+ _ => {}
+ }
+ }
+}
+
+/// The supervised daemon, managed as Tauri state.
+#[derive(Default)]
+pub(crate) struct MacrodState {
+ inner: Arc<Mutex<Inner>>,
+}
+
+#[derive(Default)]
+struct Inner {
+ /// The live child; `None` once it exited or was stopped.
+ child: Option<tokio::process::Child>,
+ status: MacrodStatus,
+ /// Increments per start so a stale reader task cannot clobber a newer run.
+ generation: u64,
+}
+
+fn emit_status(app: &AppHandle, status: &MacrodStatus) {
+ if let Err(error) = app.emit(STATUS_EVENT, status) {
+ tracing::warn!(?error, "failed to emit macrod status");
+ }
+}
+
+/// The user's login-shell `PATH`, resolved once. `None` when it cannot be
+/// read (non-unix, odd shells); callers fall back to the process `PATH`.
+fn login_shell_path() -> Option<&'static str> {
+ static RESOLVED: OnceLock<Option<String>> = OnceLock::new();
+ RESOLVED
+ .get_or_init(|| {
+ #[cfg(unix)]
+ {
+ let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_owned());
+ // `env` output is shell-agnostic (fish would join "$PATH" with
+ // spaces); take the last PATH= line in case a login banner
+ // happens to contain one.
+ let output = std::process::Command::new(&shell)
+ .args(["-l", "-c", "env"])
+ .stdin(Stdio::null())
+ .output()
+ .ok()?;
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ stdout
+ .lines()
+ .rev()
+ .find_map(|line| line.strip_prefix("PATH="))
+ .map(str::to_owned)
+ .filter(|path| !path.is_empty())
+ }
+ #[cfg(not(unix))]
+ {
+ None
+ }
+ })
+ .as_deref()
+}
+
+/// The `PATH` macrod runs with: login shell first, then this process's own,
+/// then well-known install locations, deduplicated in order.
+fn macrod_path_env() -> String {
+ let mut directories: Vec<String> = Vec::new();
+ let mut push = |value: &str| {
+ for directory in std::env::split_paths(value) {
+ let directory = directory.to_string_lossy().into_owned();
+ if !directory.is_empty() && !directories.contains(&directory) {
+ directories.push(directory);
+ }
+ }
+ };
+ if let Some(path) = login_shell_path() {
+ push(path);
+ }
+ if let Ok(path) = std::env::var("PATH") {
+ push(&path);
+ }
+ if let Ok(home) = std::env::var("HOME") {
+ for suffix in [".local/bin", ".bun/bin", ".volta/bin", ".cargo/bin"] {
+ push(&format!("{home}/{suffix}"));
+ }
+ }
+ for directory in ["/opt/homebrew/bin", "/usr/local/bin"] {
+ push(directory);
+ }
+ directories.join(if cfg!(windows) { ";" } else { ":" })
+}
+
+/// Locate the macrod binary: an explicit override, the bundled copy next to
+/// this executable, the resource directory, then the development `PATH`.
+fn macrod_binary(app: &AppHandle) -> Option<PathBuf> {
+ let name = if cfg!(windows) { "macrod.exe" } else { "macrod" };
+ if let Ok(path) = std::env::var("MACROD_PATH") {
+ let path = PathBuf::from(path);
+ if path.is_file() {
+ return Some(path);
+ }
+ }
+ if let Some(path) = std::env::current_exe()
+ .ok()
+ .and_then(|exe| Some(exe.parent()?.join(name)))
+ .filter(|path| path.is_file())
+ {
+ return Some(path);
+ }
+ if let Some(path) = app
+ .path()
+ .resource_dir()
+ .ok()
+ .map(|resources| resources.join(name))
+ .filter(|path| path.is_file())
+ {
+ return Some(path);
+ }
+ std::env::split_paths(&macrod_path_env())
+ .map(|directory| directory.join(name))
+ .find(|path| path.is_file())
+}
+
+fn macrod_command(app: &AppHandle) -> Result<tokio::process::Command, String> {
+ let binary = macrod_binary(app).ok_or_else(|| "macrod is not bundled with this build".to_owned())?;
+ let mut command = tokio::process::Command::new(binary);
+ command.env("PATH", macrod_path_env());
+ if crate::AppEnvironment::current() == crate::AppEnvironment::Development {
+ // A config created by this daemon must target the dev deployment,
+ // like the webview it pairs with.
+ command.env("DEV_MODE", "1");
+ }
+ #[cfg(windows)]
+ {
+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+ command.creation_flags(CREATE_NO_WINDOW);
+ }
+ Ok(command)
+}
+
+/// Run a one-shot macrod query and parse its stdout as JSON.
+async fn macrod_query(app: &AppHandle, args: &[&str]) -> Result<serde_json::Value, String> {
+ let output = macrod_command(app)?
+ .args(args)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true)
+ .output()
+ .await
+ .map_err(|error| format!("could not run macrod: {error}"))?;
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(format!(
+ "macrod {} failed: {}",
+ args.join(" "),
+ stderr.trim().lines().last().unwrap_or("no output")
+ ));
+ }
+ serde_json::from_slice(&output.stdout)
+ .map_err(|error| format!("macrod {} returned invalid JSON: {error}", args.join(" ")))
+}
+
+/// Whether this build can run a local agent runtime, and the daemon facts the
+/// setup flow pre-fills from.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct MacrodSupport {
+ /// Whether the bundled daemon exists on this platform and build.
+ supported: bool,
+ /// Suggested workspace directory for a first-time setup.
+ default_workspace: Option<String>,
+}
+
+#[tauri::command]
+pub(crate) fn macrod_support(app: AppHandle) -> MacrodSupport {
+ let supported = cfg!(desktop) && macrod_binary(&app).is_some();
+ let default_workspace = app
+ .path()
+ .home_dir()
+ .ok()
+ .map(|home| home.join("Macro").to_string_lossy().into_owned());
+ MacrodSupport {
+ supported,
+ default_workspace,
+ }
+}
+
+/// The ACP agents installed on this machine, from `macrod detect-agents`.
+#[tauri::command]
+pub(crate) async fn macrod_detect_agents(app: AppHandle) -> Result<serde_json::Value, String> {
+ macrod_query(&app, &["detect-agents"]).await
+}
+
+/// The service config's state, from `macrod inspect`.
+#[tauri::command]
+pub(crate) async fn macrod_inspect(app: AppHandle) -> Result<serde_json::Value, String> {
+ macrod_query(&app, &["inspect"]).await
+}
+
+/// Setup choices for a first-time (or re-) configuration. All optional: a
+/// plain restart of an already configured daemon passes none of them.
+#[derive(Debug, Clone, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct MacrodStartOptions {
+ agent: Option<String>,
+ workspace: Option<String>,
+ scope: Option<String>,
+ allow_permission_bypass: Option<bool>,
+}
+
+/// Start (or restart) the supervised daemon and remember to auto-start it on
+/// the next app launch.
+#[tauri::command]
+pub(crate) async fn macrod_start(
+ app: AppHandle,
+ state: tauri::State<'_, MacrodState>,
+ options: MacrodStartOptions,
+) -> Result<MacrodStatus, String> {
+ stop_child(&app, &state.inner).await;
+
+ let mut command = macrod_command(&app)?;
+ command.arg("service");
+ if let Some(agent) = &options.agent {
+ command.args(["--agent", agent]);
+ }
+ if let Some(workspace) = &options.workspace {
+ command.args(["--workspace", workspace]);
+ }
+ if let Some(scope) = &options.scope {
+ command.args(["--scope", scope]);
+ }
+ if let Some(allowed) = options.allow_permission_bypass {
+ command.args(["--allow-permission-bypass", if allowed { "true" } else { "false" }]);
+ }
+ let mut child = command
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true)
+ .spawn()
+ .map_err(|error| format!("could not start macrod: {error}"))?;
+
+ let stdout = child
+ .stdout
+ .take()
+ .ok_or_else(|| "macrod started without stdout".to_owned())?;
+ let stderr = child.stderr.take();
+
+ let status = {
+ let mut inner = state.inner.lock().expect("macrod state lock");
+ inner.child = Some(child);
+ inner.generation += 1;
+ inner.status = MacrodStatus {
+ phase: MacrodPhase::Starting,
+ ..MacrodStatus::default()
+ };
+ tauri::async_runtime::spawn(read_events(
+ app.clone(),
+ state.inner.clone(),
+ inner.generation,
+ stdout,
+ ));
+ inner.status.clone()
+ };
+ if let Some(stderr) = stderr {
+ tauri::async_runtime::spawn(async move {
+ let mut lines = tokio::io::BufReader::new(stderr).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ tracing::debug!(target: "macrod", "{line}");
+ }
+ });
+ }
+ set_autostart(&app, true);
+ emit_status(&app, &status);
+ Ok(status)
+}
+
+/// Fold the service's stdout into the snapshot until it closes.
+async fn read_events(
+ app: AppHandle,
+ inner: Arc<Mutex<Inner>>,
+ generation: u64,
+ stdout: tokio::process::ChildStdout,
+) {
+ let mut lines = tokio::io::BufReader::new(stdout).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ let Ok(event) = serde_json::from_str::<serde_json::Value>(&line) else {
+ tracing::warn!(target: "macrod", "unparseable service event: {line}");
+ continue;
+ };
+ let status = {
+ let mut inner = inner.lock().expect("macrod state lock");
+ if inner.generation != generation {
+ return;
+ }
+ inner.status.apply(&event);
+ inner.status.clone()
+ };
+ emit_status(&app, &status);
+ }
+ // stdout closed: the daemon exited. Keep an error phase so the user sees
+ // why; otherwise show it as stopped.
+ let status = {
+ let mut inner = inner.lock().expect("macrod state lock");
+ if inner.generation != generation {
+ return;
+ }
+ inner.child = None;
+ if inner.status.phase != MacrodPhase::Error {
+ inner.status.phase = MacrodPhase::Stopped;
+ }
+ inner.status.clone()
+ };
+ emit_status(&app, &status);
+}
+
+/// Stop the supervised daemon and stop auto-starting it.
+#[tauri::command]
+pub(crate) async fn macrod_stop(
+ app: AppHandle,
+ state: tauri::State<'_, MacrodState>,
+) -> Result<MacrodStatus, String> {
+ set_autostart(&app, false);
+ stop_child(&app, &state.inner).await;
+ let status = {
+ let mut inner = state.inner.lock().expect("macrod state lock");
+ inner.status = MacrodStatus::default();
+ inner.status.clone()
+ };
+ emit_status(&app, &status);
+ Ok(status)
+}
+
+/// The current snapshot, for a webview that (re)mounted after events fired.
+#[tauri::command]
+pub(crate) fn macrod_status(state: tauri::State<'_, MacrodState>) -> MacrodStatus {
+ state.inner.lock().expect("macrod state lock").status.clone()
+}
+
+/// Kill the child synchronously; the app is exiting and cannot await.
+pub(crate) fn kill_now(state: &MacrodState) {
+ let child = {
+ let mut inner = state.inner.lock().expect("macrod state lock");
+ inner.generation += 1;
+ inner.child.take()
+ };
+ if let Some(mut child) = child {
+ let _ = child.start_kill();
+ }
+}
+
+/// Kill the child, invalidating any reader still attached to it.
+async fn stop_child(_app: &AppHandle, inner: &Arc<Mutex<Inner>>) {
+ let child = {
+ let mut inner = inner.lock().expect("macrod state lock");
+ inner.generation += 1;
+ inner.child.take()
+ };
+ if let Some(mut child) = child {
+ // Closing stdin asks the service to shut down on its own; the kill is
+ // the backstop for a wedged process.
+ child.stdin.take();
+ match tokio::time::timeout(std::time::Duration::from_secs(3), child.wait()).await {
+ Ok(_) => {}
+ Err(_) => {
+ let _ = child.start_kill();
+ let _ = child.wait().await;
+ }
+ }
+ }
+}
+
+/// Where the auto-start marker lives: a tiny JSON file in the app's config
+/// directory, read before the webview exists.
+fn autostart_marker(app: &AppHandle) -> Option<PathBuf> {
+ app.path()
+ .app_config_dir()
+ .ok()
+ .map(|directory| directory.join("macrod.json"))
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+struct AutostartMarker {
+ autostart: bool,
+}
+
+fn set_autostart(app: &AppHandle, autostart: bool) {
+ let Some(path) = autostart_marker(app) else {
+ return;
+ };
+ if let Some(parent) = path.parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+ let marker = AutostartMarker { autostart };
+ if let Err(error) = std::fs::write(
+ &path,
+ serde_json::to_vec(&marker).expect("marker is plain data"),
+ ) {
+ tracing::warn!(?error, "failed to persist macrod autostart marker");
+ }
+}
+
+fn autostart_enabled(app: &AppHandle) -> bool {
+ autostart_marker(app)
+ .and_then(|path| std::fs::read(path).ok())
+ .and_then(|raw| serde_json::from_slice::<AutostartMarker>(&raw).ok())
+ .is_some_and(|marker| marker.autostart)
+}
+
+/// At app launch: resume the daemon when the user enabled it and a paired
+/// config exists, so agents are reachable without opening settings.
+pub(crate) fn autostart(app: &AppHandle) {
+ if !cfg!(desktop) {
+ return;
+ }
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ if !autostart_enabled(&app) || macrod_binary(&app).is_none() {
+ return;
+ }
+ let paired = match macrod_query(&app, &["inspect"]).await {
+ Ok(inspection) => inspection
+ .get("paired")
+ .and_then(serde_json::Value::as_bool)
+ .unwrap_or(false),
+ Err(error) => {
+ tracing::warn!(target: "macrod", "autostart inspect failed: {error}");
+ false
+ }
+ };
+ if !paired {
+ return;
+ }
+ let state = app.state::<MacrodState>();
+ if let Err(error) = macrod_start(app.clone(), state, MacrodStartOptions::default()).await {
+ tracing::warn!(target: "macrod", "autostart failed: {error}");
+ }
+ });
+}
diff --git a/apps/web/tauri/src-tauri/tauri.android.conf.json b/apps/web/tauri/src-tauri/tauri.android.conf.json
index 77f62ead47..8617cd1127 100644
--- a/apps/web/tauri/src-tauri/tauri.android.conf.json
+++ b/apps/web/tauri/src-tauri/tauri.android.conf.json
@@ -2,7 +2,7 @@
"version": "2.5.0",
"bundle": {
"android": {
- "versionCode": 8
+ "versionCode": 9
}
},
"$schema": "https://schema.tauri.app/config/2",
diff --git a/crates/coding_agent_worker/src/main.rs b/crates/coding_agent_worker/src/main.rs
index 779d8176c8..cb6d025722 100644
--- a/crates/coding_agent_worker/src/main.rs
+++ b/crates/coding_agent_worker/src/main.rs
@@ -24,6 +24,7 @@ mod herdr;
mod outbound;
mod repository;
mod runtime;
+mod service;
mod trigger;
mod tui;
@@ -85,6 +86,38 @@ enum Command {
#[arg(last = true)]
agent_args: Vec<String>,
},
+ /// Run headless, managed by an embedding app such as the Macro desktop
+ /// app: no terminal panel, state changes as JSON lines on stdout, and
+ /// shutdown on SIGTERM, Ctrl-C, or stdin closing.
+ Service {
+ /// Config file; defaults to `~/.macrod/macrod.toml`, created when the
+ /// setup flags are given.
+ #[arg(long)]
+ config: Option<std::path::PathBuf>,
+ /// Agent preset id from `detect-agents`, e.g. `claude-code`.
+ #[arg(long)]
+ agent: Option<String>,
+ /// Absolute directory sessions run in; created when missing.
+ #[arg(long)]
+ workspace: Option<std::path::PathBuf>,
+ /// Requested display name for the next pairing.
+ #[arg(long)]
+ name: Option<String>,
+ /// Requested ownership for the next pairing.
+ #[arg(long, value_enum)]
+ scope: Option<service::ServiceScope>,
+ /// Whether the next pairing may enable permission bypass.
+ #[arg(long)]
+ allow_permission_bypass: Option<bool>,
+ },
+ /// List the ACP agents installed on this machine as JSON.
+ DetectAgents,
+ /// Report the service config's state as JSON without running anything.
+ Inspect {
+ /// Config file; defaults to `~/.macrod/macrod.toml`.
+ #[arg(long)]
+ config: Option<std::path::PathBuf>,
+ },
}
#[tokio::main]
@@ -104,8 +137,54 @@ async fn main() -> ExitCode {
}
};
}
- #[cfg(unix)]
match args.command {
+ Some(Command::Service {
+ config,
+ agent,
+ workspace,
+ name,
+ scope,
+ allow_permission_bypass,
+ }) => {
+ // stdout is the event protocol: logs go to stderr, like herdr-acp.
+ tracing_subscriber::fmt()
+ .with_writer(std::io::stderr)
+ .init();
+ return match service::run(service::ServiceOptions {
+ config,
+ agent,
+ workspace,
+ name,
+ scope,
+ allow_permission_bypass,
+ })
+ .await
+ {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(error) => {
+ service::emit_fatal(&format!("{error}"));
+ eprintln!("macrod service: {error:?}");
+ ExitCode::FAILURE
+ }
+ };
+ }
+ Some(Command::DetectAgents) => {
+ println!("{}", service::detect_agents_json());
+ return ExitCode::SUCCESS;
+ }
+ Some(Command::Inspect { config }) => {
+ return match service::inspect_json(config) {
+ Ok(inspection) => {
+ println!("{inspection}");
+ ExitCode::SUCCESS
+ }
+ Err(error) => {
+ eprintln!("macrod inspect: {error:?}");
+ ExitCode::FAILURE
+ }
+ };
+ }
+ #[cfg(unix)]
Some(Command::HerdrPane { socket, session }) => {
return match tui::run_herdr_pane(&socket, &session).await {
Ok(()) => ExitCode::SUCCESS,
@@ -115,6 +194,7 @@ async fn main() -> ExitCode {
}
};
}
+ #[cfg(unix)]
Some(Command::HerdrAcp {
state_dir,
model,
diff --git a/crates/coding_agent_worker/src/service.rs b/crates/coding_agent_worker/src/service.rs
new file mode 100644
index 0000000000..6e47aa7a58
--- /dev/null
+++ b/crates/coding_agent_worker/src/service.rs
@@ -0,0 +1,468 @@
+//! Headless mode for embedders: the serving core without the terminal panel.
+//!
+//! The Macro desktop app bundles macrod and manages it as a child process.
+//! `macrod service` is the contract between them: setup flags configure
+//! `macrod.toml` without a TUI, state changes stream to stdout as one JSON
+//! object per line, and the process shuts down on SIGTERM, Ctrl-C, or stdin
+//! closing (the embedder exited). `macrod detect-agents` and `macrod inspect`
+//! are the matching one-shot queries.
+
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use rootcause::prelude::ResultExt as _;
+use serde::Serialize;
+use tokio::io::AsyncReadExt as _;
+
+use crate::config::{Config, HarnessCredentials, IdentityScope};
+use crate::daemon::Daemon;
+use crate::outbound::pairing::{ClaimStatus, PairingClient};
+use crate::tui::agent_catalog::{self, DetectedAgent, PathCommands};
+use crate::tui::config_form::{ConfigForm, Setting};
+
+mod environment {
+ macro_env_var::maybe_env_var! {
+ pub struct Home;
+ }
+}
+
+#[cfg(test)]
+mod test;
+
+/// How often the serving core's liveness is re-checked once running.
+const DAEMON_WATCH: Duration = Duration::from_secs(5);
+
+/// The ownership scope a service setup asks for.
+#[derive(Debug, Clone, Copy, clap::ValueEnum)]
+pub enum ServiceScope {
+ /// Only the approving user can run agents on this harness.
+ Private,
+ /// Any of the approving user's teammates can bind agents to it.
+ Team,
+}
+
+impl From<ServiceScope> for IdentityScope {
+ fn from(scope: ServiceScope) -> Self {
+ match scope {
+ ServiceScope::Private => IdentityScope::Private,
+ ServiceScope::Team => IdentityScope::Team,
+ }
+ }
+}
+
+/// Everything `macrod service` accepts.
+pub struct ServiceOptions {
+ /// Config file; absent uses [`default_config_path`].
+ pub config: Option<PathBuf>,
+ /// Agent preset id from `detect-agents` to configure.
+ pub agent: Option<String>,
+ /// Workspace directory sessions run in; created when missing.
+ pub workspace: Option<PathBuf>,
+ /// Requested display name for the next pairing.
+ pub name: Option<String>,
+ /// Requested ownership for the next pairing.
+ pub scope: Option<ServiceScope>,
+ /// Whether the next pairing may enable permission bypass.
+ pub allow_permission_bypass: Option<bool>,
+}
+
+impl ServiceOptions {
+ /// Whether any setup flag was passed, i.e. the config should be (re)written.
+ fn wants_setup(&self) -> bool {
+ self.agent.is_some()
+ || self.workspace.is_some()
+ || self.name.is_some()
+ || self.scope.is_some()
+ || self.allow_permission_bypass.is_some()
+ }
+}
+
+/// Where the service keeps its config when the embedder names none: the same
+/// `~/.macrod` directory that holds adapter installs. Deliberately not the
+/// TUI's `./macrod.toml`, so a desktop-managed daemon and a manually run one
+/// stay separate harnesses.
+pub fn default_config_path() -> Option<PathBuf> {
+ environment::Home::new()
+ .and_then(|home| home.value().map(PathBuf::from))
+ .map(|home| home.join(".macrod").join("macrod.toml"))
+}
+
+/// One state change, written to stdout as a single JSON line.
+#[derive(Debug, Serialize)]
+#[serde(tag = "event", rename_all = "snake_case")]
+enum Event {
+ /// The config loaded; emitted once at startup and after a setup rewrite.
+ Config {
+ path: String,
+ agent_id: Option<&'static str>,
+ agent_name: Option<&'static str>,
+ workspace: String,
+ paired: bool,
+ web_url: String,
+ },
+ /// A chosen agent's npm ACP adapter is installing.
+ InstallingAdapter { package: &'static str },
+ /// The adapter install finished.
+ AdapterInstalled { package: &'static str },
+ /// A pairing is open and waiting for web approval.
+ Pairing {
+ code: String,
+ url: String,
+ expires_at: chrono::DateTime<chrono::Utc>,
+ },
+ /// The pairing was approved and the credential persisted.
+ Paired { harness_id: String },
+ /// The serving core is up on the stored credential.
+ Running { harness_id: String },
+ /// The service is exiting on an error; the message is user-facing.
+ Fatal { message: String },
+}
+
+fn emit(event: &Event) {
+ use std::io::Write as _;
+
+ let line = serde_json::to_string(event).expect("service events are plain data");
+ let mut stdout = std::io::stdout().lock();
+ let _ = writeln!(stdout, "{line}");
+ let _ = stdout.flush();
+}
+
+/// Report a fatal error as the last event before a non-zero exit.
+pub fn emit_fatal(message: &str) {
+ emit(&Event::Fatal {
+ message: fatal_root_message(message),
+ });
+}
+
+/// Reports render as decorated multi-line trees; an embedder shows one plain
+/// sentence, so keep the root message alone.
+fn fatal_root_message(message: &str) -> String {
+ message
+ .lines()
+ .map(|line| line.trim().trim_start_matches('●').trim())
+ .find(|line| !line.is_empty() && !line.starts_with('╰'))
+ .unwrap_or(message)
+ .to_owned()
+}
+
+/// Run headless until SIGTERM, Ctrl-C, or stdin closes.
+pub async fn run(options: ServiceOptions) -> rootcause::Result<()> {
+ let shutdown = shutdown_requested();
+ tokio::pin!(shutdown);
+
+ let daemon = tokio::select! {
+ daemon = start(&options) => daemon?,
+ () = &mut shutdown => return Ok(()),
+ };
+
+ loop {
+ tokio::select! {
+ () = &mut shutdown => break,
+ () = tokio::time::sleep(DAEMON_WATCH) => {
+ if !daemon.is_running() {
+ daemon.stop().await;
+ rootcause::bail!("the serving core stopped unexpectedly");
+ }
+ }
+ }
+ }
+ daemon.stop().await;
+ Ok(())
+}
+
+/// Configure, install, pair, and start the serving core.
+async fn start(options: &ServiceOptions) -> rootcause::Result<Daemon> {
+ let path = config_path(options)?;
+ if !path.exists() && !options.wants_setup() {
+ rootcause::bail!(
+ "no config at {}; pass --agent and --workspace to create one",
+ path.display()
+ );
+ }
+ if options.wants_setup() {
+ let agent = options.agent.as_deref().map(installed_agent).transpose()?;
+ configure(&path, options, agent)?;
+ }
+
+ let config = Config::load(&path)?;
+ let commands = PathCommands::discover();
+ let agent = agent_catalog::detected_for(&config.harness, &commands);
+ emit(&Event::Config {
+ path: path.display().to_string(),
+ agent_id: agent.as_ref().map(|agent| agent.kind.id()),
+ agent_name: agent.as_ref().map(|agent| agent.name),
+ workspace: config.workspace.path.display().to_string(),
+ paired: config
+ .credentials
+ .as_ref()
+ .is_some_and(HarnessCredentials::is_valid),
+ web_url: config.macro_api.web_url.clone(),
+ });
+
+ if let Some(install) = agent.as_ref().and_then(DetectedAgent::pending_install) {
+ emit(&Event::InstallingAdapter {
+ package: install.package,
+ });
+ install
+ .run()
+ .await
+ .map_err(|message| rootcause::report!("{message}"))?;
+ emit(&Event::AdapterInstalled {
+ package: install.package,
+ });
+ }
+
+ let credentials = match config
+ .credentials
+ .clone()
+ .filter(HarnessCredentials::is_valid)
+ {
+ Some(credentials) => credentials,
+ None => pair(&path, &config).await?,
+ };
+ // Pairing persisted into the file; serve what is actually on disk.
+ let config = Config::load(&path)?;
+ let harness_id = credentials.harness_id.to_string();
+ let daemon = Daemon::start(config, credentials, &path).await?;
+ emit(&Event::Running { harness_id });
+ Ok(daemon)
+}
+
+/// Open one pairing and poll it to a claimed credential.
+///
+/// One code per invocation on purpose: an expired or consumed pairing ends the
+/// process, and the embedder decides whether to start over.
+async fn pair(path: &Path, config: &Config) -> rootcause::Result<HarnessCredentials> {
+ let client = PairingClient::new(config);
+ let created = client.start(config).await?;
+ emit(&Event::Pairing {
+ code: created.code.clone(),
+ url: config.macro_api.pairing_approval_url(&created.code),
+ expires_at: created.expires_at,
+ });
+ let interval = Duration::from_secs(created.poll_interval_seconds.max(1));
+ loop {
+ tokio::time::sleep(interval).await;
+ if created.expires_at <= chrono::Utc::now() {
+ rootcause::bail!("the pairing code expired before it was approved");
+ }
+ match client
+ .claim(created.pairing_id, &created.device_secret)
+ .await?
+ {
+ ClaimStatus::Pending => {}
+ ClaimStatus::Claimed(credentials) => {
+ ConfigForm::load(path)?.persist_credentials(&credentials)?;
+ emit(&Event::Paired {
+ harness_id: credentials.harness_id.to_string(),
+ });
+ return Ok(credentials);
+ }
+ ClaimStatus::Gone(reason) => rootcause::bail!("{reason}"),
+ }
+ }
+}
+
+fn config_path(options: &ServiceOptions) -> rootcause::Result<PathBuf> {
+ options
+ .config
+ .clone()
+ .or_else(default_config_path)
+ .ok_or_else(|| rootcause::report!("no config path: pass --config or set HOME"))
+}
+
+/// Create or edit the config from setup flags, comment-preservingly.
+/// `agent` is the resolved launch for `options.agent`, when one was named.
+fn configure(
+ path: &Path,
+ options: &ServiceOptions,
+ agent: Option<DetectedAgent>,
+) -> rootcause::Result<()> {
+ if let Some(workspace) = &options.workspace {
+ std::fs::create_dir_all(workspace).context(format!(
+ "could not create the workspace at {}",
+ workspace.display()
+ ))?;
+ }
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).context(format!(
+ "could not create the config directory at {}",
+ parent.display()
+ ))?;
+ }
+
+ let mut form = if path.exists() {
+ let mut form = ConfigForm::load(path)?;
+ if let Some(agent) = &agent {
+ form.apply_agent(agent);
+ }
+ if let Some(workspace) = &options.workspace {
+ form.apply_text(Setting::Workspace, &workspace.to_string_lossy())
+ .map_err(|message| rootcause::report!("{message}"))?;
+ }
+ form
+ } else {
+ let agent = agent
+ .as_ref()
+ .ok_or_else(|| rootcause::report!("creating a config needs --agent"))?;
+ let workspace = options
+ .workspace
+ .as_deref()
+ .ok_or_else(|| rootcause::report!("creating a config needs --workspace"))?;
+ ConfigForm::create(path, agent, workspace)?;
+ ConfigForm::load(path)?
+ };
+
+ if let Some(name) = &options.name {
+ form.apply_text(Setting::Name, name)
+ .map_err(|message| rootcause::report!("{message}"))?;
+ }
+ if let Some(scope) = options.scope {
+ form.set_scope(scope.into());
+ }
+ if let Some(allowed) = options.allow_permission_bypass {
+ form.set_permission_bypass(allowed);
+ }
+ form.save()
+}
+
+fn installed_agent(id: &str) -> rootcause::Result<DetectedAgent> {
+ let commands = PathCommands::discover();
+ agent_catalog::discover(&commands)
+ .into_iter()
+ .find(|agent| agent.kind.id() == id)
+ .ok_or_else(|| {
+ rootcause::report!(
+ "agent `{id}` is not installed on this machine; run `macrod detect-agents`"
+ )
+ })
+}
+
+/// Resolve when the embedder or operator asks the service to stop: SIGTERM,
+/// Ctrl-C, or stdin reaching EOF (the embedding process exited).
+async fn shutdown_requested() {
+ let stdin_eof = async {
+ let mut stdin = tokio::io::stdin();
+ let mut buffer = [0u8; 256];
+ loop {
+ match stdin.read(&mut buffer).await {
+ Ok(0) | Err(_) => break,
+ Ok(_) => {}
+ }
+ }
+ };
+ #[cfg(unix)]
+ {
+ let mut terminate =
+ tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
+ .expect("installing a SIGTERM handler never fails");
+ tokio::select! {
+ _ = tokio::signal::ctrl_c() => {}
+ _ = terminate.recv() => {}
+ () = stdin_eof => {}
+ }
+ }
+ #[cfg(not(unix))]
+ tokio::select! {
+ _ = tokio::signal::ctrl_c() => {}
+ () = stdin_eof => {}
+ }
+}
+
+/// The `detect-agents` answer: installed agents in product-preference order.
+#[derive(Debug, Serialize)]
+struct DetectedAgents {
+ agents: Vec<DetectedAgentReport>,
+}
+
+/// One installed agent, as reported to an embedder.
+#[derive(Debug, Serialize)]
+struct DetectedAgentReport {
+ /// Stable preset id, accepted by `service --agent`.
+ id: &'static str,
+ /// Human-readable name.
+ name: &'static str,
+ /// Short explanation for adapter-backed launchers.
+ note: Option<&'static str>,
+ /// Whether selecting this agent still downloads an ACP adapter first.
+ needs_install: bool,
+}
+
+/// The ACP agents installed on this machine, as a JSON document.
+pub fn detect_agents_json() -> String {
+ let commands = PathCommands::discover();
+ let agents = agent_catalog::discover(&commands)
+ .into_iter()
+ .map(|agent| DetectedAgentReport {
+ id: agent.kind.id(),
+ name: agent.name,
+ note: agent.note,
+ needs_install: agent.pending_install().is_some(),
+ })
+ .collect();
+ serde_json::to_string(&DetectedAgents { agents }).expect("agent reports are plain data")
+}
+
+/// The `inspect` answer: the service config's state, without running anything.
+#[derive(Debug, Serialize)]
+struct Inspection {
+ config_path: String,
+ exists: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ error: Option<String>,
+ paired: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ harness_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ agent_id: Option<&'static str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ agent_name: Option<&'static str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ workspace: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ web_url: Option<String>,
+}
+
+/// Inspect the config at `path` (or the default location) as a JSON document.
+pub fn inspect_json(config: Option<PathBuf>) -> rootcause::Result<String> {
+ let path = config_path(&ServiceOptions {
+ config,
+ agent: None,
+ workspace: None,
+ name: None,
+ scope: None,
+ allow_permission_bypass: None,
+ })?;
+ let mut inspection = Inspection {
+ config_path: path.display().to_string(),
+ exists: path.exists(),
+ error: None,
+ paired: false,
+ harness_id: None,
+ agent_id: None,
+ agent_name: None,
+ workspace: None,
+ web_url: None,
+ };
+ if inspection.exists {
+ match Config::load(&path) {
+ Ok(config) => {
+ let commands = PathCommands::discover();
+ let agent = agent_catalog::detected_for(&config.harness, &commands);
+ let credentials = config
+ .credentials
+ .as_ref()
+ .filter(|credentials| credentials.is_valid());
+ inspection.paired = credentials.is_some();
+ inspection.harness_id =
+ credentials.map(|credentials| credentials.harness_id.to_string());
+ inspection.agent_id = agent.as_ref().map(|agent| agent.kind.id());
+ inspection.agent_name = agent.as_ref().map(|agent| agent.name);
+ inspection.workspace = Some(config.workspace.path.display().to_string());
+ inspection.web_url = Some(config.macro_api.web_url.clone());
+ }
+ Err(error) => inspection.error = Some(format!("{error}")),
+ }
+ }
+ Ok(serde_json::to_string(&inspection).expect("inspections are plain data"))
+}
diff --git a/crates/coding_agent_worker/src/service/test.rs b/crates/coding_agent_worker/src/service/test.rs
new file mode 100644
index 0000000000..02bd63a8e9
--- /dev/null
+++ b/crates/coding_agent_worker/src/service/test.rs
@@ -0,0 +1,107 @@
+use super::*;
+use crate::config::HarnessScope;
+use harness_id::HarnessId;
+
+fn setup_options(workspace: &Path) -> ServiceOptions {
+ ServiceOptions {
+ config: None,
+ agent: Some("custom".to_owned()),
+ workspace: Some(workspace.to_owned()),
+ name: Some("Desk".to_owned()),
+ scope: Some(ServiceScope::Team),
+ allow_permission_bypass: Some(true),
+ }
+}
+
+#[test]
+fn creates_a_config_from_setup_flags() {
+ let directory = tempfile::tempdir().expect("temp dir");
+ // Neither the config directory nor the workspace exist yet; setup
+ // creates both.
+ let path = directory.path().join("state").join("macrod.toml");
+ let workspace = directory.path().join("workspace");
+ let agent = agent_catalog::custom("hermes acp").expect("custom agent");
+
+ configure(&path, &setup_options(&workspace), Some(agent)).expect("configure");
+
+ let config = Config::load(&path).expect("load created config");
+ assert_eq!(config.harness.command, "hermes");
+ assert_eq!(config.harness.args, ["acp"]);
+ assert_eq!(config.workspace.path, workspace);
+ assert!(workspace.is_dir());
+ assert_eq!(config.identity.name.as_deref(), Some("Desk"));
+ assert_eq!(config.identity.scope, IdentityScope::Team);
+ assert!(config.identity.allow_permission_bypass);
+ assert!(config.credentials.is_none());
+}
+
+#[test]
+fn reconfigures_without_dropping_credentials() {
+ let directory = tempfile::tempdir().expect("temp dir");
+ let path = directory.path().join("macrod.toml");
+ let workspace = directory.path().join("workspace");
+ let agent = agent_catalog::custom("hermes acp").expect("custom agent");
+ configure(&path, &setup_options(&workspace), Some(agent)).expect("configure");
+
+ let credentials = HarnessCredentials {
+ harness_id: HarnessId::TEST_A,
+ token: "mhns_test_secret".to_owned(),
+ scope: HarnessScope::User,
+ };
+ ConfigForm::load(&path)
+ .expect("load form")
+ .persist_credentials(&credentials)
+ .expect("persist credentials");
+
+ let moved = directory.path().join("elsewhere");
+ configure(
+ &path,
+ &ServiceOptions {
+ config: None,
+ agent: None,
+ workspace: Some(moved.clone()),
+ name: None,
+ scope: Some(ServiceScope::Private),
+ allow_permission_bypass: None,
+ },
+ None,
+ )
+ .expect("reconfigure");
+
+ let config = Config::load(&path).expect("load edited config");
+ assert_eq!(config.credentials, Some(credentials));
+ assert_eq!(config.workspace.path, moved);
+ assert_eq!(config.identity.scope, IdentityScope::Private);
+ // Untouched settings survive the edit.
+ assert_eq!(config.identity.name.as_deref(), Some("Desk"));
+ assert!(config.identity.allow_permission_bypass);
+}
+
+#[test]
+fn creating_a_config_requires_an_agent() {
+ let directory = tempfile::tempdir().expect("temp dir");
+ let path = directory.path().join("macrod.toml");
+ let error = configure(
+ &path,
+ &ServiceOptions {
+ config: None,
+ agent: None,
+ workspace: Some(directory.path().to_owned()),
+ name: None,
+ scope: None,
+ allow_permission_bypass: None,
+ },
+ None,
+ )
+ .expect_err("creation without an agent must fail");
+ assert!(format!("{error}").contains("--agent"));
+}
+
+#[test]
+fn fatal_root_message_keeps_the_root_line() {
+ assert_eq!(
+ fatal_root_message("\n ● the pairing code expired\n ╰ crates/x.rs:1\n"),
+ "the pairing code expired"
+ );
+ assert_eq!(fatal_root_message("plain failure"), "plain failure");
+}
diff --git a/crates/coding_agent_worker/src/tui.rs b/crates/coding_agent_worker/src/tui.rs
index 172806c864..8c8a317e4d 100644
--- a/crates/coding_agent_worker/src/tui.rs
+++ b/crates/coding_agent_worker/src/tui.rs
@@ -6,10 +6,12 @@
//! own logs - and drives its lifecycle: edit `macrod.toml`, pair (or re-pair,
//! restarting the core on the new credential), and retire the harness.
-mod agent_catalog;
+// `service` reuses agent discovery and the comment-preserving config editor;
+// they live here because the TUI grew them first.
+pub(crate) mod agent_catalog;
mod api;
mod app;
-mod config_form;
+pub(crate) mod config_form;
#[cfg(unix)]
mod herdr_pane;
mod input;
diff --git a/crates/coding_agent_worker/src/tui/agent_catalog.rs b/crates/coding_agent_worker/src/tui/agent_catalog.rs
index 3163f0a243..faf92ba8f1 100644
--- a/crates/coding_agent_worker/src/tui/agent_catalog.rs
+++ b/crates/coding_agent_worker/src/tui/agent_catalog.rs
@@ -118,6 +118,20 @@ impl AgentKind {
pub fn is_herdr(self) -> bool {
matches!(self, Self::HerdrClaude | Self::HerdrCodex)
}
+
+ /// Stable id used by `macrod detect-agents` and `macrod service --agent`.
+ pub fn id(self) -> &'static str {
+ match self {
+ Self::Hermes => "hermes",
+ Self::ClaudeCode => "claude-code",
+ Self::HerdrClaude => "herdr-claude",
+ Self::HerdrCodex => "herdr-codex",
+ Self::Codex => "codex",
+ Self::OpenClaw => "openclaw",
+ Self::OpenCode => "opencode",
+ Self::Custom => "custom",
+ }
+ }
}
/// Result of checking one preset against the local machine.
@@ -284,6 +298,15 @@ pub fn kind_for(harness: &Harness) -> Option<AgentKind> {
preset_for(harness).map(|preset| preset.kind())
}
+/// Re-detect the preset an existing launch configuration came from, when its
+/// prerequisites are still installed.
+pub fn detected_for(harness: &Harness, commands: &dyn CommandLookup) -> Option<DetectedAgent> {
+ preset_for(harness).and_then(|preset| match preset.detect(commands) {
+ Availability::Available(agent) => Some(agent),
+ Availability::Unavailable { .. } => None,
+ })
+}
+
/// Parse a custom command line into an ACP launch specification.
pub fn custom(command_line: &str) -> Result<DetectedAgent, String> {
let mut parts = shell_words::split(command_line)
diff --git a/docs/agent-guide/ai-chat.md b/docs/agent-guide/ai-chat.md
index b31cffac0c..7f9d20dac8 100644
--- a/docs/agent-guide/ai-chat.md
+++ b/docs/agent-guide/ai-chat.md
@@ -522,6 +522,10 @@ the shimmer.
**Done**. **Manage** on a paired machine opens **Runtimes** (Back returns to
Agents): built-in providers, **New runtime**, and the **Paired runtimes** list,
which appears once you have a paired runtime.
+ On the desktop app, **Runtimes** opens with a **This computer** card that sets
+ up the bundled macrod daemon in one click: **Set up** detects installed agents,
+ then **Start running agents here** configures, pairs (auto-approved, no code),
+ and starts it. The manual flow below remains for pairing other machines.
**New runtime** shows three steps: install macrod from the linked release,
run `./macrod` and configure your agent in Quickstart, then enter your pairing
code and click **Look up**. Review the request and click **Approve** to connect.
diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.md
index 9004813c0d..33af39d05a 100644
--- a/docs/agent-guide/settings.md
+++ b/docs/agent-guide/settings.md
@@ -526,7 +526,7 @@ New macrod sessions use the agent's saved model before sending the first prompt.
Changing that default applies to new sessions; existing sessions keep their selected model.
If the runtime rejects the saved model, the prompt fails instead of using a different model.
-The `Runtimes` section shows built-in Macro, Cursor, Claude, and Codex configuration, followed by paired macrod runtimes. Claude's card appears only with the `claude-cloud` flag, and Codex's only within the agents and Codex rollouts. The “Bring your own agent” card sits above the Agents / Runtimes navigation and is visible on both sections. It rotates Claude Code, OpenCode, OpenClaw, and Hermes; reduced motion keeps a static name. Its `New runtime` action opens the full-page pairing flow from either section: enter the code, look up the request, review the machine, name, sharing and permission consent, then Approve and Done. Back/Cancel returns to the runtime list. Destructive removal still requires confirmation. `/settings/runtimes` opens this section; legacy `/settings/harness?pair=…` links remain supported.
+The `Runtimes` section shows built-in Macro, Cursor, Claude, and Codex configuration, followed by paired macrod runtimes. Claude's card appears only with the `claude-cloud` flag, and Codex's only within the agents and Codex rollouts. On the desktop app only, a “This computer” card appears above the built-in runtimes: the bundled macrod daemon is set up from here with one click. `Set up` scans the machine for installed agents (Claude Code, Codex, OpenCode, OpenClaw), offers a workspace folder and a Full access checkbox, and `Start running agents here` configures, pairs, and starts the daemon — the pairing is approved automatically, no code is typed. While running the card shows the agent and workspace with a `Stop` action; a set-up-but-stopped runtime offers `Start`. The web app never shows this card. The “Bring your own agent” card sits above the Agents / Runtimes navigation and is visible on both sections. It rotates Claude Code, OpenCode, OpenClaw, and Hermes; reduced motion keeps a static name. Its `New runtime` action opens the full-page pairing flow from either section: enter the code, look up the request, review the machine, name, sharing and permission consent, then Approve and Done. Back/Cancel returns to the runtime list. Destructive removal still requires confirmation. `/settings/runtimes` opens this section; legacy `/settings/harness?pair=…` links remain supported.
Connection chips in agent replies open this page, including before any account is connected. Cursor's default-model picker uses
the same live model discovery and retains its existing save action.
diff --git a/nix/tauri-desktop.nix b/nix/tauri-desktop.nix
index f590986012..be301b7db8 100644
--- a/nix/tauri-desktop.nix
+++ b/nix/tauri-desktop.nix
@@ -161,6 +161,57 @@
doInstallCargoArtifacts = false;
};
+ # The macrod agent daemon, bundled with the desktop app as a Tauri
+ # sidecar so "run agents on this computer" needs no separate download.
+ # Built from the root workspace (not the nested Tauri one), natively for
+ # the bundle's platform; the standalone release tarballs keep their own
+ # musl/darwin pipeline in build_agent_daemon_on_tag.yml.
+ macrodBinary = craneLib.mkCargoDerivation {
+ pname = "macrod";
+ version = appVersion;
+ src = jsSrc;
+ cargoArtifacts = null;
+ cargoVendorDir = rootCargoVendorDir;
+ nativeBuildInputs = [
+ # aws-lc-sys (rustls' crypto provider) and bundled librdkafka build
+ # their C sources with cmake; see the matching notes on `libraries`
+ # in cloud-storage.nix.
+ pkgs.cmake
+ pkgs.git
+ pkgs.perl
+ pkgs.pkg-config
+ ];
+ buildInputs = [
+ pkgs.openssl
+ pkgs.openssl.dev
+ # librdkafka 2.12's bundled cmake-build needs curl headers even with
+ # WITH_CURL=0 (headers only; nothing links against libcurl).
+ pkgs.curl.dev
+ pkgs.libclang
+ pkgs.xz.out
+ ]
+ ++ lib.optionals pkgs.stdenv.isDarwin [ pkgs.libiconv ];
+ LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";
+ OPENSSL_NO_VENDOR = "1";
+ doCheck = false;
+ SQLX_OFFLINE = "true";
+ buildPhaseCargoCommand = ''
+ cargo build --release --package coding_agent_worker --bin macrod
+ '';
+ installPhaseCommand = ''
+ install -Dm0755 target/release/macrod "$out/bin/macrod"
+ '';
+ doInstallCargoArtifacts = false;
+ };
+
+ # Tauri sidecar sources carry the target triple in the file name; the
+ # bundler strips it when placing the binary next to the app executable.
+ rustHostTriple = pkgs.stdenv.hostPlatform.rust.rustcTarget;
+ installMacrodSidecar = ''
+ install -Dm0755 ${macrodBinary}/bin/macrod \
+ "src-tauri/binaries/macrod-${rustHostTriple}"
+ '';
+
frontend = pkgs.stdenvNoCC.mkDerivation {
pname = "macro-tauri-frontend";
version = appVersion;
@@ -681,6 +732,7 @@
active = true;
targets = [ "appimage" ];
useLocalToolsDir = true;
+ externalBin = [ "binaries/macrod" ];
linux.appimage.bundleMediaFramework = true;
linux.appimage.files = {
"/usr/bin/xdg-mime" = "${tauriXdgUtils}/bin/xdg-mime";
@@ -769,6 +821,7 @@
bundle = {
active = true;
targets = [ "app" ];
+ externalBin = [ "binaries/macrod" ];
};
}
(
@@ -792,6 +845,7 @@
fi
export PATH="$PATH:/usr/bin:/bin:/usr/sbin:/sbin"
${tauriDesktopPreBuild}
+ ${installMacrodSidecar}
'';
buildPhaseCargoCommand = ''
cargo tauri build --bundles app \
@@ -896,6 +950,15 @@
done < <(find "$app/Contents/Frameworks" -type f -print0)
fi
+ # Helper executables (the macrod sidecar) must be signed
+ # individually for notarization; the --deep pass below re-seals
+ # the bundle on top of them.
+ while IFS= read -r -d "" file; do
+ if otool -hv "$file" >/dev/null 2>&1; then
+ codesign "''${sign_args[@]}" "$file"
+ fi
+ done < <(find "$app/Contents/MacOS" -type f -print0)
+
codesign "''${sign_args[@]}" --deep "$app"
codesign --verify --deep --strict --verbose=2 "$app"
}
@@ -999,6 +1062,7 @@
preBuild = ''
test -e ${tauriAppImagePackagingTests}
${tauriDesktopPreBuild}
+ ${installMacrodSidecar}
runtime_library_path="$(while IFS= read -r store_path; do
if [ -d "$store_path/lib" ]; then
@@ -1057,6 +1121,7 @@
packages = {
js-node-modules = nodeModules;
+ macrod = macrodBinary;
}
// lib.optionalAttrs isLinux {
tauri-frontend = frontend;