Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(desktop): keep macrod running and set up local agents in one click (#8956)
Eric Hayes6eb82affc4ae
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex e8c24355ff..184ff3a6e5 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -46,6 +46,11 @@ slides into a short window; the phone drawer shows late requests:Keep the popover's `flip` limited to `left-start`: an end fallback re-places itabove the event whenever a late section changes its height.+The desktop app's local runtime setup (find an agent, connect, create the+agent, retry, open a session) has a backend-free browser regression over a+scripted runtime:+`bunx playwright test --config src/features/local-runtime/browser-test/playwright.config.ts`.+Meeting-note creation, linking, optional team access, retry, and unlinking have desktop andphone browser coverage in `features/calendar-notes`:`bunx playwright test --config src/features/calendar-notes/browser-test/playwright.config.ts`.diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsxindex 2a3b5631a4..da7322b549 100644--- a/apps/web/src/components/app/Layout.tsx+++ b/apps/web/src/components/app/Layout.tsx@@ -52,7 +52,7 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';import { hasLoginCookie, updateCookie } from '@core/util/cookies';import { lazyNamed } from '@core/util/lazyNamed';-import { isPlatform } from '@core/util/platform';+import { isDesktopPlatform, isPlatform } from '@core/util/platform';import { useDesktopZoom } from '@macro/tauri/zoom';import { useUserInfoQuery } from '@queries/auth/user-info';import { queryClient } from '@queries/client';@@ -96,6 +96,10 @@ const Paywall = lazyNamed(() => import('@app/features/paywall/Paywall'),'Paywall');+const LocalRuntimeHost = lazyNamed(+ () => import('@app/features/local-runtime/local-runtime-host'),+ 'LocalRuntimeHost'+);const PropertyEditorModal = lazyNamed(() => import('@app/features/property/editor/PropertyEditorModal'),'PropertyEditorModal'@@ -281,6 +285,9 @@ export function AppChrome(props: ParentProps) {<PropertyEditorModal /></Suspense><GlobalBulkEditEntityModal />+ <Show when={isDesktopPlatform()}>+ <LocalRuntimeHost />+ </Show><NativeShareSheet /><MacroMcpSetupModal /><CreateChannelModal />diff --git a/apps/web/src/features/local-runtime/browser-test/fixture.tsx b/apps/web/src/features/local-runtime/browser-test/fixture.tsxnew file mode 100644index 0000000000..ac6ae175aa--- /dev/null+++ b/apps/web/src/features/local-runtime/browser-test/fixture.tsx@@ -0,0 +1,117 @@+import '@fontsource-variable/inter';+import '../../../index.css';+import type { MacrodStatus } from '@macro/tauri/macrod';+import { Button } from '@ui';+import { createSignal, Show } from 'solid-js';+import { render } from 'solid-js/web';+import { macroDarkTheme } from '../../theme/themes/macro-dark';+import { macroLightTheme } from '../../theme/themes/macro-light';+import type { NewLocalAgent, SetupCapabilities } from '../core/setup';+import { LocalRuntimeSetupDialog } from '../views/local-runtime-setup-dialog';+import { LocalRuntimeSetupPanel } from '../views/local-runtime-setup-panel';++const params = new URLSearchParams(location.search);+document.documentElement.dataset.themeLight = String(+ params.get('theme') !== 'dark'+);+const theme = params.get('theme') === 'dark' ? macroDarkTheme : macroLightTheme;+for (const [token, value] of Object.entries(theme.colorTokens)) {+ document.documentElement.style.setProperty(`--color-${token}`, value);+}++/**+ * `happy` connects and creates the agent; `fail-once` loses the first+ * pairing; `none` finds no agents; `hold` stops while linking.+ */+const scenario = params.get('scenario') ?? 'happy';+const delay = Number(params.get('delay') ?? 150);++const RUNNING: MacrodStatus = {+ phase: 'running',+ agentId: 'claude-code',+ agentName: 'Claude Code',+ workspace: '/Users/sample/Macro',+ pairingCode: null,+ pairingExpiresAt: null,+ harnessId: 'harness-1',+ lastError: null,+};++const wait = (ms: number) =>+ new Promise<void>((resolve) => setTimeout(resolve, ms));++let connects = 0;+const capabilities: SetupCapabilities = {+ detectAgents: async () => {+ await wait(delay);+ return scenario === 'none'+ ? []+ : [+ {+ id: 'codex',+ name: 'Codex',+ note: null,+ needs_install: true,+ },+ {+ id: 'claude-code',+ name: 'Claude Code',+ note: null,+ needs_install: false,+ },+ ];+ },+ startDaemon: async () => ({ ...RUNNING, phase: 'starting' }),+ waitForRunning: async (onPhase) => {+ connects++;+ onPhase('starting');+ await wait(delay);+ onPhase('pairing');+ if (scenario === 'hold') await new Promise(() => {});+ await wait(delay);+ if (scenario === 'fail-once' && connects === 1) {+ throw new Error('The pairing code expired before it was approved.');+ }+ return RUNNING;+ },+ listAgents: async () => [],+ loadModels: async () => ({+ status: 'available',+ currentModel: 'sonnet',+ models: [{ id: 'sonnet', name: 'Sonnet' }],+ }),+ createAgent: async (agent: NewLocalAgent) => {+ await wait(delay);+ return { botId: 'bot-1', name: agent.name, handle: agent.handle };+ },+ sleep: wait,+};++function Fixture() {+ const [open, setOpen] = createSignal(true);+ const [action, setAction] = createSignal('');+ return (+ <main class="min-h-screen bg-panel p-6">+ <Button type="button" variant="outline" onClick={() => setOpen(true)}>+ Open setup+ </Button>+ <p role="status" aria-label="Preview action" class="mt-3 text-sm">+ {action()}+ </p>+ <LocalRuntimeSetupDialog open={open()} onClose={() => setOpen(false)}>+ <Show when={open()}>+ <LocalRuntimeSetupPanel+ capabilities={capabilities}+ onOpenSession={(agent) => setAction(`Opened @${agent.handle}`)}+ defaultWorkspace="/Users/sample/Macro"+ autoStart={params.get('auto') !== 'false'}+ onClose={() => setOpen(false)}+ />+ </Show>+ </LocalRuntimeSetupDialog>+ </main>+ );+}++const root = document.getElementById('root');+if (root) render(() => <Fixture />, root);diff --git a/apps/web/src/features/local-runtime/browser-test/index.html b/apps/web/src/features/local-runtime/browser-test/index.htmlnew file mode 100644index 0000000000..119ee18a6a--- /dev/null+++ b/apps/web/src/features/local-runtime/browser-test/index.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="en" data-modality="keyboard">+ <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Local runtime setup</title></head>+ <body><div id="root"></div><script type="module" src="/fixture.tsx"></script></body>+</html>diff --git a/apps/web/src/features/local-runtime/browser-test/playwright.config.ts b/apps/web/src/features/local-runtime/browser-test/playwright.config.tsnew file mode 100644index 0000000000..02af8b059a--- /dev/null+++ b/apps/web/src/features/local-runtime/browser-test/playwright.config.ts@@ -0,0 +1,37 @@+import { fileURLToPath } from 'node:url';+import { defineConfig, devices } from '@playwright/test';++const directory = fileURLToPath(new URL('.', import.meta.url));+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));+const port = Number(process.env.LOCAL_RUNTIME_BROWSER_PORT ?? 3098);+export default defineConfig({+ testDir: directory,+ testMatch: '*.browser.e2e.ts',+ outputDir: `${directory}/test-results`,+ timeout: 45_000,+ fullyParallel: true,+ use: {+ baseURL: `http://127.0.0.1:${port}`,+ trace: 'retain-on-failure',+ screenshot: 'only-on-failure',+ contextOptions: { reducedMotion: 'reduce' },+ },+ webServer: {+ command: `bunx vite --config src/features/local-runtime/browser-test/vite.config.ts --port ${port}`,+ cwd: webDirectory,+ url: `http://127.0.0.1:${port}`,+ reuseExistingServer: false,+ timeout: 120_000,+ },+ projects: [+ {+ name: 'desktop',+ use: {+ ...devices['Desktop Chrome'],+ launchOptions: {+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,+ },+ },+ },+ ],+});diff --git a/apps/web/src/features/local-runtime/browser-test/setup.browser.e2e.ts b/apps/web/src/features/local-runtime/browser-test/setup.browser.e2e.tsnew file mode 100644index 0000000000..d3b8f1fed8--- /dev/null+++ b/apps/web/src/features/local-runtime/browser-test/setup.browser.e2e.ts@@ -0,0 +1,77 @@+import { expect, test } from '@playwright/test';++test('sets up the preferred agent and opens a session with it', async ({+ page,+}) => {+ await page.goto('/?scenario=happy');+ const dialog = page.getByRole('dialog', {+ name: 'Run agents on this computer',+ });+ await expect(dialog.getByText('Find an agent')).toBeVisible();+ await expect(dialog.getByText('@claude-code is ready')).toBeVisible();+ await expect(+ dialog.getByText('Sessions run in /Users/sample/Macro.')+ ).toBeVisible();++ await dialog.getByRole('button', { name: 'Start a session' }).click();+ await expect(dialog).toBeHidden();+ await expect(page.getByRole('status', { name: 'Preview action' })).toHaveText(+ 'Opened @claude-code'+ );+});++test('shows where setup is while it links the computer', async ({ page }) => {+ await page.goto('/?scenario=hold');+ const dialog = page.getByRole('dialog', {+ name: 'Run agents on this computer',+ });+ await expect(dialog.getByText('Found Claude Code')).toBeVisible();+ await expect(+ dialog.getByText('Linking this computer to your account…')+ ).toBeVisible();+ await expect(+ dialog.locator('li[aria-current="step"]', {+ hasText: 'Connect this computer',+ })+ ).toBeVisible();+});++test('recovers from a lost pairing with Try again', async ({ page }) => {+ await page.goto('/?scenario=fail-once');+ const dialog = page.getByRole('dialog', {+ name: 'Run agents on this computer',+ });+ await expect(+ dialog.getByText('The pairing code expired before it was approved.')+ ).toBeVisible();+ await dialog.getByRole('button', { name: 'Try again' }).click();+ await expect(dialog.getByText('@claude-code is ready')).toBeVisible();+});++test('lets the user pick another agent before setting up', async ({ page }) => {+ await page.goto('/?scenario=happy&auto=false');+ const dialog = page.getByRole('dialog', {+ name: 'Run agents on this computer',+ });+ await expect(+ dialog.getByText('Found Claude Code on this computer.')+ ).toBeVisible();+ await dialog.getByRole('button', { name: 'Options' }).click();+ await expect(dialog.getByLabel('Workspace folder')).toHaveValue(+ '/Users/sample/Macro'+ );+ await expect(dialog.getByText('Full access')).toBeVisible();+ await expect(+ dialog.getByRole('button', { name: 'Set up Claude Code' })+ ).toBeEnabled();+});++test('asks for an agent when none is installed', async ({ page }) => {+ await page.goto('/?scenario=none');+ const dialog = page.getByRole('dialog', {+ name: 'Run agents on this computer',+ });+ await expect(+ dialog.getByRole('button', { name: 'Scan again' })+ ).toBeVisible();+});diff --git a/apps/web/src/features/local-runtime/browser-test/vite.config.ts b/apps/web/src/features/local-runtime/browser-test/vite.config.tsnew file mode 100644index 0000000000..6339f6223e--- /dev/null+++ b/apps/web/src/features/local-runtime/browser-test/vite.config.ts@@ -0,0 +1,31 @@+import { fileURLToPath } from 'node:url';+import tailwind from '@tailwindcss/vite';+import { defineConfig } from 'vite';+import solidPlugin from 'vite-plugin-solid';+import solidSvg from 'vite-plugin-solid-svg';+import tsconfigPaths from 'vite-tsconfig-paths';++const directory = fileURLToPath(new URL('.', import.meta.url));+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));+const workspaceDirectory = fileURLToPath(+ new URL('../../../../../../', import.meta.url)+);++/** The real setup dialog and panel over a scripted local runtime. */+export default defineConfig({+ root: directory,+ cacheDir: `${directory}/.vite`,+ plugins: [+ solidPlugin(),+ solidSvg({ defaultAsComponent: true }),+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),+ tailwind(),+ ],+ resolve: { dedupe: ['solid-js'] },+ server: {+ host: '127.0.0.1',+ port: 3098,+ strictPort: true,+ fs: { allow: [workspaceDirectory] },+ },+});diff --git a/apps/web/src/features/local-runtime/components/setup-checklist.tsx b/apps/web/src/features/local-runtime/components/setup-checklist.tsxnew file mode 100644index 0000000000..68d8219f47--- /dev/null+++ b/apps/web/src/features/local-runtime/components/setup-checklist.tsx@@ -0,0 +1,81 @@+import CheckIcon from '@icon/system/regular/check.svg';+import CircleIcon from '@icon/system/regular/circle.svg';+import SpinnerIcon from '@icon/system/regular/spinner-gap.svg';+import WarningIcon from '@icon/system/regular/warning-circle.svg';+import { cn } from '@ui';+import { For, Match, Show, Switch } from 'solid-js';+import type { StepStatus } from '../core/setup';++export type ChecklistStep = {+ id: string;+ label: string;+ /** What the step is doing now, or what it found. */+ detail?: string;+ status: StepStatus;+};++/** Setup progress as an ordered list of steps. */+export function SetupChecklist(props: { steps: ChecklistStep[] }) {+ return (+ <ol class="flex flex-col gap-3" aria-live="polite">+ <For each={props.steps}>+ {(step) => (+ <li+ class="flex items-start gap-3"+ aria-current={step.status === 'active' ? 'step' : undefined}+ >+ <span+ aria-hidden="true"+ class={cn(+ 'mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full [&_svg]:size-3.5',+ step.status === 'done' && 'bg-success-bg text-success',+ step.status === 'failed' && 'text-failure [&_svg]:size-5',+ step.status === 'active' && 'text-ink [&_svg]:size-4',+ step.status === 'pending' && 'text-ink-extra-muted'+ )}+ >+ <Switch>+ <Match when={step.status === 'done'}>+ <CheckIcon />+ </Match>+ <Match when={step.status === 'failed'}>+ <WarningIcon />+ </Match>+ <Match when={step.status === 'active'}>+ <SpinnerIcon class="animate-spin" />+ </Match>+ <Match when={step.status === 'pending'}>+ <CircleIcon />+ </Match>+ </Switch>+ </span>+ <div class="min-w-0">+ <p+ class={cn(+ 'text-sm/5',+ step.status === 'pending' ? 'text-ink-muted' : 'text-ink'+ )}+ >+ {step.label}+ </p>+ <Show when={step.detail}>+ {(detail) => (+ <p+ class={cn(+ 'text-xs',+ step.status === 'failed'+ ? 'text-failure'+ : 'text-ink-muted'+ )}+ >+ {detail()}+ </p>+ )}+ </Show>+ </div>+ </li>+ )}+ </For>+ </ol>+ );+}diff --git a/apps/web/src/features/local-runtime/core/setup.test.ts b/apps/web/src/features/local-runtime/core/setup.test.tsnew file mode 100644index 0000000000..a0ffac0506--- /dev/null+++ b/apps/web/src/features/local-runtime/core/setup.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it } from 'vitest';+import {+ agentHandle,+ chooseModel,+ offeredAgents,+ type SetupState,+ stepStatus,+} from './setup';++const detected = (id: string) => ({+ id,+ name: id,+ note: null,+ needs_install: false,+});++describe('offeredAgents', () => {+ it('prefers Claude Code, then Codex, and hides herdr and custom agents', () => {+ const offered = offeredAgents([+ detected('opencode'),+ detected('herdr-claude'),+ detected('codex'),+ detected('custom'),+ detected('claude-code'),+ ]);+ expect(offered.map((agent) => agent.id)).toEqual([+ 'claude-code',+ 'codex',+ 'opencode',+ ]);+ });+});++describe('chooseModel', () => {+ it('keeps the runtime’s current model when it is in the catalog', () => {+ expect(+ chooseModel({+ status: 'available',+ currentModel: 'b',+ models: [+ { id: 'a', name: 'A' },+ { id: 'b', name: 'B' },+ ],+ })+ ).toBe('b');+ });++ it('falls back to the first model, and to none for an empty catalog', () => {+ expect(+ chooseModel({ status: 'available', models: [{ id: 'a', name: 'A' }] })+ ).toBe('a');+ expect(chooseModel({ status: 'available', models: [] })).toBeUndefined();+ });++ it('uses the default model when the runtime has no model selection', () => {+ expect(chooseModel({ status: 'unsupported', models: [] })).toBe('default');+ });+});++describe('agentHandle', () => {+ it('slugs the agent name', () => {+ expect(agentHandle('Claude Code')).toBe('claude-code');+ expect(agentHandle(' OpenCode! ')).toBe('opencode');+ });+});++describe('stepStatus', () => {+ const statuses = (state: SetupState) =>+ (['detect', 'connect', 'agent'] as const).map((step) =>+ stepStatus(state, step)+ );++ it('marks earlier steps done and later ones pending', () => {+ expect(statuses({ kind: 'running', step: 'connect' })).toEqual([+ 'done',+ 'active',+ 'pending',+ ]);+ expect(+ statuses({ kind: 'failed', step: 'agent', message: 'nope' })+ ).toEqual(['done', 'done', 'failed']);+ expect(statuses({ kind: 'no-agents' })).toEqual([+ 'failed',+ 'pending',+ 'pending',+ ]);+ });+});diff --git a/apps/web/src/features/local-runtime/core/setup.ts b/apps/web/src/features/local-runtime/core/setup.tsnew file mode 100644index 0000000000..f09a74d93d--- /dev/null+++ b/apps/web/src/features/local-runtime/core/setup.ts@@ -0,0 +1,145 @@+import type {+ MacrodDetectedAgent,+ MacrodStartOptions,+ MacrodStatus,+} from '@macro/tauri/macrod';+import type { LoadAgentModelsResponse } from '@service-agent-harness/generated/schemas';+import { match } from 'ts-pattern';++/**+ * One-click local runtime setup on the desktop app: find a coding agent+ * installed on this computer, connect the bundled macrod daemon to the+ * user's account, and create a Macro agent that runs on it.+ */++/** The steps the user watches, in order. */+export const SETUP_STEPS = ['detect', 'connect', 'agent'] as const;+export type SetupStep = (typeof SETUP_STEPS)[number];++export type ReadyAgent = {+ botId: string;+ name: string;+ handle: string;+};++export type SetupState =+ | { kind: 'idle' }+ | { kind: 'running'; step: SetupStep; phase?: MacrodStatus['phase'] }+ | { kind: 'no-agents' }+ | { kind: 'failed'; step: SetupStep; message: string }+ | { kind: 'ready'; agent: ReadyAgent; workspace: string | null };++export type StepStatus = 'pending' | 'active' | 'done' | 'failed';++/** What the user may override before running; everything has a default. */+export type SetupChoices = {+ /** Preset id from detection; the preferred detected agent when absent. */+ agentId?: string;+ workspace?: string;+ fullAccess: boolean;+};++/** An agent already bound to a runtime, as far as setup cares. */+type BoundAgent = {+ botId: string;+ name: string;+ handle: string;+ harnessId: string | null;+};++export type NewLocalAgent = {+ name: string;+ handle: string;+ description: string;+ harnessId: string;+ defaultModel: string;+ autoAcceptPermissions: boolean;+};++/**+ * Everything setup does outside itself. Production wires the Tauri bridge and+ * the agent queries; tests pass fakes.+ */+export type SetupCapabilities = {+ detectAgents: () => Promise<MacrodDetectedAgent[]>;+ startDaemon: (options: MacrodStartOptions) => Promise<MacrodStatus>;+ /**+ * Resolves with the daemon's status once it is running; rejects on an+ * error phase or when it never gets there.+ */+ waitForRunning: (+ onPhase: (phase: MacrodStatus['phase']) => void+ ) => Promise<MacrodStatus>;+ listAgents: () => Promise<BoundAgent[]>;+ loadModels: (harnessId: string) => Promise<LoadAgentModelsResponse>;+ createAgent: (agent: NewLocalAgent) => Promise<ReadyAgent>;+ /** Waits between model-load attempts while the runtime comes online. */+ sleep: (ms: number) => Promise<void>;+};++/**+ * Agents in the order setup prefers them. Herdr variants need a running herdr+ * terminal, so a headless desktop daemon never picks them by itself.+ */+const AGENT_PREFERENCE = [+ 'claude-code',+ 'codex',+ 'opencode',+ 'openclaw',+ 'hermes',+];++/** The agents setup offers, preferred first. */+export function offeredAgents(+ detected: readonly MacrodDetectedAgent[]+): MacrodDetectedAgent[] {+ const rank = (agent: MacrodDetectedAgent) => {+ const index = AGENT_PREFERENCE.indexOf(agent.id);+ return index === -1 ? AGENT_PREFERENCE.length : index;+ };+ return detected+ .filter((agent) => !agent.id.startsWith('herdr-') && agent.id !== 'custom')+ .sort((a, b) => rank(a) - rank(b));+}++/** The model a new agent starts on, or none while the catalog is empty. */+export function chooseModel(+ response: LoadAgentModelsResponse+): string | undefined {+ if (response.status === 'unsupported') return 'default';+ const current = response.currentModel;+ if (current && response.models.some((model) => model.id === current)) {+ return current;+ }+ return response.models[0]?.id ?? current ?? undefined;+}++export function agentHandle(name: string): string {+ return name+ .toLowerCase()+ .replace(/[^a-z0-9_-]+/g, '-')+ .replace(/^-+|-+$/g, '');+}++export function stepStatus(state: SetupState, step: SetupStep): StepStatus {+ const index = SETUP_STEPS.indexOf(step);+ const at = (current: SetupStep, here: StepStatus): StepStatus => {+ const currentIndex = SETUP_STEPS.indexOf(current);+ if (index < currentIndex) return 'done';+ if (index > currentIndex) return 'pending';+ return here;+ };+ return match(state)+ .with({ kind: 'idle' }, (): StepStatus => 'pending')+ .with({ kind: 'ready' }, (): StepStatus => 'done')+ .with({ kind: 'no-agents' }, () => at('detect', 'failed'))+ .with({ kind: 'running' }, (s) => at(s.step, 'active'))+ .with({ kind: 'failed' }, (s) => at(s.step, 'failed'))+ .exhaustive();+}++export 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;+}diff --git a/apps/web/src/features/local-runtime/local-runtime-host.tsx b/apps/web/src/features/local-runtime/local-runtime-host.tsxnew file mode 100644index 0000000000..1abed16c1b--- /dev/null+++ b/apps/web/src/features/local-runtime/local-runtime-host.tsx@@ -0,0 +1,83 @@+import { t } from '@app/lib/i18n';+import { useKeyedPersistentToasts } from '@core/component/Toast/useKeyedPersistentToasts';+import { fireAndForget } from '@core/util/fireAndForget';+import { MacrodPairingApprover } from '@macro/tauri/MacrodPairingApprover';+import { macrodInspect, macrodSupport } from '@macro/tauri/macrod';+import { createSignal, onMount, Show } from 'solid-js';+import { LocalRuntimeSetup } from './local-runtime-setup';+import { LocalRuntimeSetupDialog } from './views/local-runtime-setup-dialog';++/** The single key of the first-run prompt; it has no per-item identity. */+const PROMPT_KEY = 'setup';++type Probe = { needsSetup: boolean; defaultWorkspace?: string };++/**+ * Everything the desktop app does for its bundled agent runtime outside+ * Settings: approve the daemon's pairings, and on a computer where it was+ * never set up, offer one-click setup once. Mount once, on desktop, inside+ * the authenticated shell.+ */+export function LocalRuntimeHost() {+ const [probe, setProbe] = createSignal<Probe>();+ const [dialogOpen, setDialogOpen] = createSignal(false);++ onMount(() => {+ fireAndForget(+ (async () => {+ const support = await macrodSupport();+ if (!support.supported) {+ setProbe({ needsSetup: false });+ return;+ }+ const inspection = await macrodInspect();+ setProbe({+ needsSetup: !inspection.exists,+ defaultWorkspace: support.defaultWorkspace ?? undefined,+ });+ })(),+ 'local-runtime-host'+ );+ });++ useKeyedPersistentToasts({+ items: () => (probe()?.needsSetup ? [PROMPT_KEY] : []),+ key: (key) => key,+ // Advisory: Settings › Runtimes keeps setup reachable, so a close sticks.+ persistKey: 'macro:local-runtime-prompt:dismissed',+ itemsLoaded: () => probe() !== undefined,+ toast: (_key, dismiss) => ({+ title: t('localRuntime.promptTitle'),+ content(): string {+ return t('localRuntime.promptBody');+ },+ actions: [+ {+ label: t('localRuntime.setUp'),+ onClick: () => {+ dismiss();+ setDialogOpen(true);+ },+ },+ ],+ }),+ });++ return (+ <>+ <MacrodPairingApprover />+ <LocalRuntimeSetupDialog+ open={dialogOpen()}+ onClose={() => setDialogOpen(false)}+ >+ <Show when={dialogOpen()}>+ <LocalRuntimeSetup+ defaultWorkspace={probe()?.defaultWorkspace}+ autoStart+ onClose={() => setDialogOpen(false)}+ />+ </Show>+ </LocalRuntimeSetupDialog>+ </>+ );+}diff --git a/apps/web/src/features/local-runtime/local-runtime-setup.tsx b/apps/web/src/features/local-runtime/local-runtime-setup.tsxnew file mode 100644index 0000000000..e022fe59df--- /dev/null+++ b/apps/web/src/features/local-runtime/local-runtime-setup.tsx@@ -0,0 +1,42 @@+import { openAgentComposer } from '@app/features/agents-view/primitives/open-composer';+import { createWorkspaceMode } from '@app/features/agents-view/primitives/workspace-mode';+import { createRecentAgentSelections } from '@app/features/block-agent/context/recent-agent-selections';+import { useSplitLayout } from '@components/app/split-layout/layout';+import { useUserId } from '@core/context/user';+import type { MacrodStatus } from '@macro/tauri/macrod';+import type { ReadyAgent } from './core/setup';+import { useSetupCapabilities } from './queries/setup-capabilities';+import { LocalRuntimeSetupPanel } from './views/local-runtime-setup-panel';++/**+ * The setup panel with production capabilities: the Tauri bridge, the agent+ * queries, and the Agents composer for the first session.+ */+export function LocalRuntimeSetup(props: {+ defaultWorkspace?: string;+ running?: MacrodStatus;+ autoStart?: boolean;+ onClose?: () => void;+}) {+ const capabilities = useSetupCapabilities();+ const userId = useUserId();+ const layout = useSplitLayout();++ const openSession = (agent: ReadyAgent) => {+ // The composer opens on the agent last chosen, in Code mode.+ createRecentAgentSelections(userId()).remember(agent.botId);+ createWorkspaceMode(userId()).setMode('code');+ openAgentComposer(layout);+ };++ return (+ <LocalRuntimeSetupPanel+ capabilities={capabilities}+ onOpenSession={openSession}+ defaultWorkspace={props.defaultWorkspace}+ running={props.running}+ autoStart={props.autoStart}+ onClose={props.onClose}+ />+ );+}diff --git a/apps/web/src/features/local-runtime/primitives/local-runtime-setup.test.ts b/apps/web/src/features/local-runtime/primitives/local-runtime-setup.test.tsnew file mode 100644index 0000000000..4bfc87e160--- /dev/null+++ b/apps/web/src/features/local-runtime/primitives/local-runtime-setup.test.ts@@ -0,0 +1,206 @@+import type { MacrodStatus } from '@macro/tauri/macrod';+import { createRoot } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import type { NewLocalAgent, SetupCapabilities } from '../core/setup';+import { createLocalRuntimeSetup } from './local-runtime-setup';++const RUNNING: MacrodStatus = {+ phase: 'running',+ agentId: 'claude-code',+ agentName: 'Claude Code',+ workspace: '/home/me/Macro',+ pairingCode: null,+ pairingExpiresAt: null,+ harnessId: 'harness-1',+ lastError: null,+};++function fakeCapabilities(+ overrides: Partial<SetupCapabilities> = {}+): SetupCapabilities {+ return {+ detectAgents: async () => [+ { id: 'codex', name: 'Codex', note: null, needs_install: false },+ {+ id: 'claude-code',+ name: 'Claude Code',+ note: null,+ needs_install: true,+ },+ ],+ startDaemon: async () => ({ ...RUNNING, phase: 'starting' }),+ waitForRunning: async (onPhase) => {+ onPhase('pairing');+ return RUNNING;+ },+ listAgents: async () => [],+ loadModels: async () => ({+ status: 'available',+ currentModel: 'sonnet',+ models: [{ id: 'sonnet', name: 'Sonnet' }],+ }),+ createAgent: async (agent: NewLocalAgent) => ({+ botId: 'bot-1',+ name: agent.name,+ handle: agent.handle,+ }),+ sleep: async () => {},+ ...overrides,+ };+}++function withSetup(caps: SetupCapabilities) {+ return createRoot((dispose) => ({+ setup: createLocalRuntimeSetup(caps),+ dispose,+ }));+}++describe('createLocalRuntimeSetup', () => {+ it('starts the preferred agent and creates a Macro agent on its runtime', async () => {+ const startDaemon = vi.fn(async () => RUNNING);+ const createAgent = vi.fn(async (agent: NewLocalAgent) => ({+ botId: 'bot-1',+ name: agent.name,+ handle: agent.handle,+ }));+ const { setup, dispose } = withSetup(+ fakeCapabilities({ startDaemon, createAgent })+ );++ await setup.run({ workspace: ' /tmp/work ', fullAccess: true });++ expect(startDaemon).toHaveBeenCalledWith({+ agent: 'claude-code',+ workspace: '/tmp/work',+ scope: 'private',+ allowPermissionBypass: true,+ });+ expect(createAgent).toHaveBeenCalledWith({+ name: 'Claude Code',+ handle: 'claude-code',+ description: 'Runs Claude Code on this computer with your own login.',+ harnessId: 'harness-1',+ defaultModel: 'sonnet',+ autoAcceptPermissions: true,+ });+ expect(setup.state()).toEqual({+ kind: 'ready',+ agent: { botId: 'bot-1', name: 'Claude Code', handle: 'claude-code' },+ workspace: '/home/me/Macro',+ });+ dispose();+ });++ it('reuses an agent already bound to the runtime', async () => {+ const createAgent = vi.fn();+ const { setup, dispose } = withSetup(+ fakeCapabilities({+ createAgent,+ listAgents: async () => [+ {+ botId: 'bot-9',+ name: 'Mine',+ handle: 'mine',+ harnessId: 'harness-1',+ },+ ],+ })+ );++ await setup.run({ fullAccess: false });++ expect(createAgent).not.toHaveBeenCalled();+ expect(setup.state()).toMatchObject({+ kind: 'ready',+ agent: { botId: 'bot-9', handle: 'mine' },+ });+ dispose();+ });++ it('reports no agents without starting anything', async () => {+ const startDaemon = vi.fn();+ const { setup, dispose } = withSetup(+ fakeCapabilities({ detectAgents: async () => [], startDaemon })+ );++ await setup.run({ fullAccess: false });++ expect(setup.state()).toEqual({ kind: 'no-agents' });+ expect(startDaemon).not.toHaveBeenCalled();+ dispose();+ });++ it('fails the connect step with the daemon’s message', async () => {+ const { setup, dispose } = withSetup(+ fakeCapabilities({+ waitForRunning: async () => {+ throw new Error('the pairing code expired before it was approved');+ },+ })+ );++ await setup.run({ fullAccess: false });++ expect(setup.state()).toEqual({+ kind: 'failed',+ step: 'connect',+ message: 'the pairing code expired before it was approved',+ });+ dispose();+ });++ it('waits for the new runtime’s models, and resumes at the agent step on retry', async () => {+ let loads = 0;+ const startDaemon = vi.fn(async () => RUNNING);+ const createAgent = vi.fn(async (agent: NewLocalAgent) => ({+ botId: 'bot-1',+ name: agent.name,+ handle: agent.handle,+ }));+ const { setup, dispose } = withSetup(+ fakeCapabilities({+ startDaemon,+ createAgent,+ loadModels: async () => {+ loads++;+ if (loads < 3) throw new Error('runtime not connected');+ return { status: 'available', models: [{ id: 'm', name: 'M' }] };+ },+ })+ );++ await setup.run({ fullAccess: false });+ expect(setup.state().kind).toBe('ready');+ expect(loads).toBe(3);+ expect(createAgent).toHaveBeenCalledWith(+ expect.objectContaining({ defaultModel: 'm' })+ );++ // A failure after connecting retries without re-pairing.+ createAgent.mockRejectedValueOnce(new Error('handle rejected'));+ const second = withSetup(fakeCapabilities({ startDaemon, createAgent }));+ await second.setup.run({ fullAccess: false });+ expect(second.setup.state()).toMatchObject({+ kind: 'failed',+ step: 'agent',+ message: 'handle rejected',+ });+ await second.setup.run();+ expect(second.setup.state().kind).toBe('ready');+ expect(startDaemon).toHaveBeenCalledTimes(2);+ second.dispose();+ dispose();+ });++ it('finishes an already running daemon without starting it', async () => {+ const startDaemon = vi.fn();+ const { setup, dispose } = withSetup(fakeCapabilities({ startDaemon }));++ await setup.adopt(RUNNING, { fullAccess: false });++ expect(startDaemon).not.toHaveBeenCalled();+ expect(setup.state().kind).toBe('ready');+ dispose();+ });+});diff --git a/apps/web/src/features/local-runtime/primitives/local-runtime-setup.ts b/apps/web/src/features/local-runtime/primitives/local-runtime-setup.tsnew file mode 100644index 0000000000..0fd9269e99--- /dev/null+++ b/apps/web/src/features/local-runtime/primitives/local-runtime-setup.ts@@ -0,0 +1,199 @@+import type { MacrodDetectedAgent, MacrodStatus } from '@macro/tauri/macrod';+import { Telemetry } from '@macro-inc/observability';+import { err, ok, type Result, ResultAsync } from 'neverthrow';+import { createSignal } from 'solid-js';+import {+ agentHandle,+ chooseModel,+ errorMessage,+ offeredAgents,+ type ReadyAgent,+ type SetupCapabilities,+ type SetupChoices,+ type SetupState,+ type SetupStep,+} from '../core/setup';++/**+ * A freshly paired runtime reports its catalog only after its first+ * heartbeat, so a new agent's model load retries for a little while.+ */+const MODEL_LOAD_ATTEMPTS = 10;+const MODEL_LOAD_INTERVAL_MS = 1500;++const FALLBACK_ERRORS: Record<SetupStep, string> = {+ detect: 'Could not look for agents on this computer.',+ connect: 'Could not connect this computer to your account.',+ agent: 'Could not create your agent.',+};++/**+ * Runs the local runtime setup steps and exposes their progress. A failed+ * step can be retried; once the daemon is connected, a retry resumes at the+ * agent step instead of re-pairing.+ */+export function createLocalRuntimeSetup(caps: SetupCapabilities) {+ const [state, setState] = createSignal<SetupState>({ kind: 'idle' });+ const [agents, setAgents] = createSignal<MacrodDetectedAgent[]>();+ const [scanning, setScanning] = createSignal(false);+ /** The running daemon once connect succeeded, for resuming. */+ let connected: MacrodStatus | undefined;+ let lastChoices: SetupChoices = { fullAccess: false };++ const attempt = async <T>(+ step: SetupStep,+ work: () => Promise<T>+ ): Promise<Result<T, string>> => {+ setState({ kind: 'running', step });+ // Error messages can carry local paths, so the span records only the+ // outcome; the user sees the message.+ const span = Telemetry.span(`local_runtime.setup.${step}`);+ const result = await span.run(+ async () =>+ await ResultAsync.fromPromise(work(), (error) =>+ errorMessage(error, FALLBACK_ERRORS[step])+ )+ );+ span.setAttr('local_runtime.outcome', result.isOk() ? 'success' : 'error');+ span.end();+ if (result.isErr()) {+ setState({ kind: 'failed', step, message: result.error });+ }+ return result;+ };++ /** Look for installed agents without running setup, for the options. */+ const scan = async (): Promise<MacrodDetectedAgent[]> => {+ setScanning(true);+ const result = await ResultAsync.fromPromise(caps.detectAgents(), () => []);+ setScanning(false);+ const found = offeredAgents(result.isOk() ? result.value : []);+ setAgents(found);+ return found;+ };++ const connect = async (+ choices: SetupChoices+ ): Promise<Result<MacrodStatus, string>> => {+ const found = await attempt('detect', async () => {+ const offered = await scan();+ return choices.agentId+ ? offered.find((agent) => agent.id === choices.agentId)+ : offered[0];+ });+ if (found.isErr()) return err(found.error);+ const agent = found.value;+ if (!agent) {+ setState({ kind: 'no-agents' });+ return err('no-agents');+ }++ return await attempt('connect', async () => {+ await caps.startDaemon({+ agent: agent.id,+ workspace: choices.workspace?.trim() || undefined,+ scope: 'private',+ allowPermissionBypass: choices.fullAccess,+ });+ return await caps.waitForRunning((phase) =>+ setState({ kind: 'running', step: 'connect', phase })+ );+ });+ };++ const loadModel = async (harnessId: string): Promise<string> => {+ let lastError: unknown;+ for (let tries = 0; tries < MODEL_LOAD_ATTEMPTS; tries++) {+ if (tries > 0) await caps.sleep(MODEL_LOAD_INTERVAL_MS);+ const result = await ResultAsync.fromPromise(+ caps.loadModels(harnessId),+ (error) => error+ );+ if (result.isErr()) {+ lastError = result.error;+ continue;+ }+ const model = chooseModel(result.value);+ if (model) return model;+ }+ throw lastError ?? new Error('Your agent did not report any models.');+ };++ /** Reuse an agent already bound to this runtime, or create one. */+ const ensureAgent = async (+ status: MacrodStatus,+ choices: SetupChoices+ ): Promise<ReadyAgent> => {+ const harnessId = status.harnessId;+ if (!harnessId) throw new Error('This computer is not connected yet.');+ const existing = (await caps.listAgents()).find(+ (agent) => agent.harnessId === harnessId+ );+ if (existing) return existing;+ const name = status.agentName ?? 'Local agent';+ return await caps.createAgent({+ name,+ handle: agentHandle(name),+ description: `Runs ${name} on this computer with your own login.`,+ harnessId,+ defaultModel: await loadModel(harnessId),+ autoAcceptPermissions: choices.fullAccess,+ });+ };++ const finish = async (status: MacrodStatus, choices: SetupChoices) => {+ const agent = await attempt('agent', () => ensureAgent(status, choices));+ if (agent.isErr()) return;+ setState({+ kind: 'ready',+ agent: agent.value,+ workspace: status.workspace,+ });+ };++ // Every step sets a running state synchronously as it starts, so this+ // also covers the moment between one step finishing and the next.+ const inProgress = () => state().kind === 'running';++ /** Run every step, or resume after the daemon already connected. */+ const run = async (choices: SetupChoices = lastChoices) => {+ if (inProgress()) return;+ lastChoices = choices;+ // One trace per attempt, each step a child span.+ const span = Telemetry.span('local_runtime.setup');+ span.setAttr('local_runtime.resumed', connected !== undefined);+ await span.run(async () => {+ const status: Result<MacrodStatus, string> = connected+ ? ok(connected)+ : await connect(choices);+ if (status.isOk()) {+ connected = status.value;+ if (status.value.harnessId) {+ span.setAttr('harness.id', status.value.harnessId);+ }+ if (status.value.agentId) {+ span.setAttr('local_runtime.agent', status.value.agentId);+ }+ await finish(status.value, choices);+ }+ });+ span.setAttr('local_runtime.outcome', state().kind);+ span.end();+ };++ /** Start over from detection, e.g. after changing the options. */+ const restart = async (choices: SetupChoices) => {+ if (inProgress()) return;+ connected = undefined;+ await run(choices);+ };++ /** Finish setup for a daemon that is already running. */+ const adopt = async (status: MacrodStatus, choices: SetupChoices) => {+ if (inProgress()) return;+ connected = status;+ await run(choices);+ };++ return { state, agents, scanning, scan, run, restart, adopt };+}diff --git a/apps/web/src/features/local-runtime/queries/setup-capabilities.ts b/apps/web/src/features/local-runtime/queries/setup-capabilities.tsnew file mode 100644index 0000000000..3aa8610cf7--- /dev/null+++ b/apps/web/src/features/local-runtime/queries/setup-capabilities.ts@@ -0,0 +1,105 @@+import { fireAndForget } from '@core/util/fireAndForget';+import {+ type MacrodStatus,+ macrodDetectAgents,+ macrodStart,+ macrodStatus,+ onMacrodStatus,+} from '@macro/tauri/macrod';+import {+ fetchAgentsList,+ useCreateAgentMutation,+} from '@queries/agents/agents';+import { agentModelsQueryOptions } from '@queries/agents/models';+import { queryClient } from '@queries/client';+import type { SetupCapabilities } from '../core/setup';++/**+ * Connecting covers pairing, which the app approves on its own, plus a first+ * adapter install; past this the daemon is stuck, not slow.+ */+const CONNECT_TIMEOUT_MS = 3 * 60 * 1000;++/** Resolve once the daemon runs, reporting each phase on the way. */+async function waitForRunning(+ onPhase: (phase: MacrodStatus['phase']) => void+): Promise<MacrodStatus> {+ // A promise settles once; later status events are no-ops.+ let resolveRunning: (status: MacrodStatus) => void = () => {};+ let rejectRunning: (error: Error) => void = () => {};+ const running = new Promise<MacrodStatus>((resolve, reject) => {+ resolveRunning = resolve;+ rejectRunning = reject;+ });+ const handle = (status: MacrodStatus) => {+ onPhase(status.phase);+ if (status.phase === 'running' && status.harnessId) {+ resolveRunning(status);+ } else if (status.phase === 'error') {+ rejectRunning(+ new Error(status.lastError ?? 'The local runtime stopped.')+ );+ }+ };++ const unlisten = await onMacrodStatus(handle);+ const timer = setTimeout(+ () => rejectRunning(new Error('Connecting this computer took too long.')),+ CONNECT_TIMEOUT_MS+ );+ try {+ // Listen first, then read: an event between the two is in the snapshot.+ handle(await macrodStatus());+ return await running;+ } finally {+ clearTimeout(timer);+ fireAndForget(unlisten(), 'local-runtime-setup');+ }+}++/** The production capabilities: the Tauri bridge and the agent queries. */+export function useSetupCapabilities(): SetupCapabilities {+ const createAgent = useCreateAgentMutation();+ return {+ detectAgents: macrodDetectAgents,+ startDaemon: macrodStart,+ waitForRunning,+ listAgents: async () =>+ (await fetchAgentsList()).map((agent) => ({+ botId: agent.bot.id,+ name: agent.bot.name,+ handle: agent.bot.handle,+ harnessId: agent.harness_id ?? null,+ })),+ // A catalog that was empty a moment ago is no answer for a runtime that+ // just came online, so always ask again.+ loadModels: async (harnessId) =>+ await queryClient.fetchQuery({+ ...agentModelsQueryOptions({ harness: 'macrod', harnessId }),+ staleTime: 0,+ }),+ createAgent: async (agent) => {+ const created = await createAgent.mutateAsync({+ name: agent.name,+ handle: agent.handle,+ description: agent.description,+ harness: 'macrod',+ harnessId: agent.harnessId,+ defaultModel: agent.defaultModel,+ instructions: '',+ channelIds: [],+ channelScope: 'all',+ mcp: { scope: 'owner_connections' },+ autoAcceptPermissions: agent.autoAcceptPermissions,+ isCoding: true,+ });+ return {+ botId: created.bot.id,+ name: created.bot.name,+ handle: created.bot.handle,+ };+ },+ sleep: async (ms) =>+ await new Promise((resolve) => setTimeout(resolve, ms)),+ };+}diff --git a/apps/web/src/features/local-runtime/views/local-runtime-setup-dialog.tsx b/apps/web/src/features/local-runtime/views/local-runtime-setup-dialog.tsxnew file mode 100644index 0000000000..3eeb22b44c--- /dev/null+++ b/apps/web/src/features/local-runtime/views/local-runtime-setup-dialog.tsx@@ -0,0 +1,48 @@+import { t } from '@app/lib/i18n';+import LaptopIcon from '@icon/system/regular/laptop.svg';+import XIcon from '@icon/system/regular/x.svg';+import { Button, Dialog, Panel } from '@ui';+import type { JSX } from 'solid-js';++/** Setup in a dialog, for setup started outside Settings. */+export function LocalRuntimeSetupDialog(props: {+ open: boolean;+ onClose: () => void;+ /** The setup panel. */+ children: JSX.Element;+}) {+ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => (open ? undefined : props.onClose())}+ position="center"+ class="w-120"+ >+ <Panel depth={2} active class="rounded-xl text-ink">+ <Panel.Header class="gap-2 px-5">+ <span aria-hidden="true" class="text-ink-muted [&_svg]:size-4">+ <LaptopIcon />+ </span>+ <Dialog.Title class="text-sm font-semibold">+ {t('localRuntime.title')}+ </Dialog.Title>+ <div class="ml-auto">+ <Button+ variant="ghost"+ size="icon-sm"+ label={t('localRuntime.close')}+ aria-label={t('localRuntime.close')}+ onClick={() => props.onClose()}+ >+ <XIcon />+ </Button>+ </div>+ </Panel.Header>+ <Panel.Body class="flex flex-col gap-4 p-5">+ <p class="text-sm text-ink-muted">{t('localRuntime.description')}</p>+ {props.children}+ </Panel.Body>+ </Panel>+ </Dialog>+ );+}diff --git a/apps/web/src/features/local-runtime/views/local-runtime-setup-panel.test.tsx b/apps/web/src/features/local-runtime/views/local-runtime-setup-panel.test.tsxnew file mode 100644index 0000000000..f16a77b3e3--- /dev/null+++ b/apps/web/src/features/local-runtime/views/local-runtime-setup-panel.test.tsx@@ -0,0 +1,117 @@+import type { MacrodStatus } from '@macro/tauri/macrod';+import { fireEvent, render, screen } from '@solidjs/testing-library';+import { describe, expect, it, vi } from 'vitest';+import type {+ NewLocalAgent,+ ReadyAgent,+ SetupCapabilities,+} from '../core/setup';+import { LocalRuntimeSetupPanel } from './local-runtime-setup-panel';++const RUNNING: MacrodStatus = {+ phase: 'running',+ agentId: 'claude-code',+ agentName: 'Claude Code',+ workspace: '/home/me/Macro',+ pairingCode: null,+ pairingExpiresAt: null,+ harnessId: 'harness-1',+ lastError: null,+};++function capabilities(+ overrides: Partial<SetupCapabilities> = {}+): SetupCapabilities {+ return {+ detectAgents: async () => [+ {+ id: 'claude-code',+ name: 'Claude Code',+ note: null,+ needs_install: false,+ },+ ],+ startDaemon: async () => RUNNING,+ waitForRunning: async () => RUNNING,+ listAgents: async () => [],+ loadModels: async () => ({+ status: 'available',+ models: [{ id: 'sonnet', name: 'Sonnet' }],+ }),+ createAgent: async (agent: NewLocalAgent) => ({+ botId: 'bot-1',+ name: agent.name,+ handle: agent.handle,+ }),+ sleep: async () => {},+ ...overrides,+ };+}++describe('LocalRuntimeSetupPanel', () => {+ it('sets up the agent it found and opens a session with it', async () => {+ const onClose = vi.fn();+ const onOpenSession = vi.fn((_agent: ReadyAgent) => {});+ render(() => (+ <LocalRuntimeSetupPanel+ capabilities={capabilities()}+ onOpenSession={onOpenSession}+ defaultWorkspace="/home/me/Macro"+ onClose={onClose}+ />+ ));++ expect(+ await screen.findByText('Found Claude Code on this computer.')+ ).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Set up Claude Code' }));++ expect(await screen.findByText('@claude-code is ready')).toBeTruthy();+ expect(screen.getByText('Sessions run in /home/me/Macro.')).toBeTruthy();++ fireEvent.click(screen.getByRole('button', { name: 'Start a session' }));+ expect(onOpenSession).toHaveBeenCalledWith({+ botId: 'bot-1',+ name: 'Claude Code',+ handle: 'claude-code',+ });+ expect(onClose).toHaveBeenCalledOnce();+ });++ it('shows the failed step and recovers on Try again', async () => {+ let attempts = 0;+ const caps = capabilities({+ waitForRunning: async () => {+ attempts++;+ if (attempts === 1) throw new Error('the pairing code expired');+ return RUNNING;+ },+ });+ render(() => (+ <LocalRuntimeSetupPanel+ capabilities={caps}+ onOpenSession={() => {}}+ autoStart+ />+ ));++ expect(await screen.findByText('the pairing code expired')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }));+ expect(await screen.findByText('@claude-code is ready')).toBeTruthy();+ });++ it('asks to install an agent when none is found', async () => {+ render(() => (+ <LocalRuntimeSetupPanel+ capabilities={capabilities({ detectAgents: async () => [] })}+ onOpenSession={() => {}}+ autoStart+ />+ ));++ expect(+ await screen.findByRole('button', { name: 'Scan again' })+ ).toBeTruthy();+ expect(screen.queryByRole('button', { name: /^Set up/ })).toBeNull();+ });+});diff --git a/apps/web/src/features/local-runtime/views/local-runtime-setup-panel.tsx b/apps/web/src/features/local-runtime/views/local-runtime-setup-panel.tsxnew file mode 100644index 0000000000..0ce8ec4b09--- /dev/null+++ b/apps/web/src/features/local-runtime/views/local-runtime-setup-panel.tsx@@ -0,0 +1,370 @@+import { SettingsSelect } from '@app/features/settings/components/settings-select';+import { t } from '@app/lib/i18n';+import { fireAndForget } from '@core/util/fireAndForget';+import CaretDownIcon from '@icon/system/regular/caret-down.svg';+import CheckCircleIcon from '@icon/system/regular/check-circle.svg';+import SpinnerIcon from '@icon/system/regular/spinner-gap.svg';+import type { MacrodStatus } from '@macro/tauri/macrod';+import { Button, cn } from '@ui';+import { createSignal, Match, onMount, Show, Switch } from 'solid-js';+import { match } from 'ts-pattern';+import {+ type ChecklistStep,+ SetupChecklist,+} from '../components/setup-checklist';+import {+ type ReadyAgent,+ SETUP_STEPS,+ type SetupCapabilities,+ type SetupChoices,+ type SetupState,+ type SetupStep,+ stepStatus,+} from '../core/setup';+import { createLocalRuntimeSetup } from '../primitives/local-runtime-setup';++/**+ * The whole local runtime setup in one place: the agent it found, optional+ * overrides, live progress, and a way into the first session. Hosted by the+ * first-run dialog and the Settings card, through the `LocalRuntimeSetup`+ * entry point that supplies the production capabilities.+ */+export function LocalRuntimeSetupPanel(props: {+ capabilities: SetupCapabilities;+ /** Open a first session with the agent setup made. */+ onOpenSession: (agent: ReadyAgent) => void;+ defaultWorkspace?: string;+ /**+ * A daemon that already runs but has no agent yet: setup skips straight to+ * creating one.+ */+ running?: MacrodStatus;+ /** Start right away rather than waiting for the Set up button. */+ autoStart?: boolean;+ onClose?: () => void;+}) {+ const setup = createLocalRuntimeSetup(props.capabilities);+ const [optionsOpen, setOptionsOpen] = createSignal(false);+ const [agentId, setAgentId] = createSignal<string>();+ const [workspace, setWorkspace] = createSignal(props.defaultWorkspace ?? '');+ const [fullAccess, setFullAccess] = createSignal(false);++ const choices = (): SetupChoices => ({+ agentId: agentId() ?? setup.agents()?.[0]?.id,+ workspace: workspace(),+ fullAccess: fullAccess(),+ });+ const chosenAgent = () => {+ const id = choices().agentId;+ return setup.agents()?.find((agent) => agent.id === id);+ };+ const agentName = () => props.running?.agentName ?? chosenAgent()?.name ?? '';++ const start = () => {+ const running = props.running;+ fireAndForget(+ running ? setup.adopt(running, choices()) : setup.restart(choices()),+ 'local-runtime-setup'+ );+ };++ onMount(() => {+ if (props.running) {+ start();+ return;+ }+ fireAndForget(+ (async () => {+ await setup.scan();+ if (props.autoStart && (setup.agents()?.length ?? 0) > 0) start();+ })(),+ 'local-runtime-setup'+ );+ });++ const openSession = (agent: ReadyAgent) => {+ props.onOpenSession(agent);+ props.onClose?.();+ };++ const detail = (state: SetupState, step: SetupStep): string | undefined =>+ match(step)+ .with('detect', () =>+ stepStatus(state, 'detect') === 'done' && agentName()+ ? t('localRuntime.stepDetectDone', { agent: agentName() })+ : undefined+ )+ .with('connect', () =>+ state.kind === 'running' && state.step === 'connect'+ ? match(state.phase)+ .with('installing-adapter', () =>+ t('localRuntime.stepConnectInstalling', { agent: agentName() })+ )+ .with('pairing', () => t('localRuntime.stepConnectPairing'))+ .otherwise(() => t('localRuntime.stepConnectStarting'))+ : undefined+ )+ .with('agent', () =>+ state.kind === 'ready'+ ? t('localRuntime.stepAgentDone', { handle: state.agent.handle })+ : undefined+ )+ .exhaustive();++ const steps = (): ChecklistStep[] => {+ const state = setup.state();+ return SETUP_STEPS.map((step) => ({+ id: step,+ label: match(step)+ .with('detect', () => t('localRuntime.stepDetect'))+ .with('connect', () => t('localRuntime.stepConnect'))+ .with('agent', () => t('localRuntime.stepAgent'))+ .exhaustive(),+ detail:+ state.kind === 'failed' && state.step === step+ ? state.message+ : detail(state, step),+ status: stepStatus(state, step),+ }));+ };++ const failed = () => setup.state().kind === 'failed';+ const ready = () => {+ const state = setup.state();+ return state.kind === 'ready' ? state : undefined;+ };++ return (+ <div class="flex flex-col gap-4">+ <Switch>+ <Match when={ready()}>+ {(state) => (+ <div class="flex flex-col gap-4">+ <div class="flex items-start gap-3">+ <CheckCircleIcon+ aria-hidden="true"+ class="mt-0.5 size-5 shrink-0 text-success"+ />+ <div class="min-w-0">+ <p class="text-sm font-medium text-ink">+ {t('localRuntime.readyTitle', {+ handle: state().agent.handle,+ })}+ </p>+ <p class="mt-0.5 text-sm text-ink-muted">+ {t('localRuntime.readyDescription')}+ </p>+ <Show when={state().workspace}>+ {(dir) => (+ <p class="mt-1 text-xs text-ink-extra-muted">+ {t('localRuntime.readyWorkspace', {+ workspace: dir(),+ })}+ </p>+ )}+ </Show>+ </div>+ </div>+ <div class="flex items-center gap-2">+ <Button+ type="button"+ variant="cta"+ size="sm"+ onClick={() => openSession(state().agent)}+ >+ {t('localRuntime.startSession')}+ </Button>+ <Show when={props.onClose}>+ {(close) => (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => close()()}+ >+ {t('localRuntime.done')}+ </Button>+ )}+ </Show>+ </div>+ </div>+ )}+ </Match>++ <Match when={setup.state().kind === 'idle' && setup.scanning()}>+ <p class="flex items-center gap-2 text-sm text-ink-muted">+ <SpinnerIcon aria-hidden="true" class="size-4 animate-spin" />+ {t('localRuntime.scanning')}+ </p>+ </Match>++ <Match+ when={+ setup.state().kind === 'no-agents' ||+ (setup.state().kind === 'idle' && setup.agents()?.length === 0)+ }+ >+ <div class="flex flex-col items-start gap-2">+ <p class="text-sm text-ink-muted">{t('localRuntime.noAgents')}</p>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={setup.scanning()}+ onClick={() => fireAndForget(setup.scan(), 'local-runtime-setup')}+ >+ {t('localRuntime.scanAgain')}+ </Button>+ </div>+ </Match>++ <Match when={setup.state().kind === 'idle'}>+ <div class="flex flex-col gap-3">+ <Show when={chosenAgent()}>+ {(agent) => (+ <p class="text-sm text-ink">+ {t('localRuntime.found', { agent: agent().name })}+ </p>+ )}+ </Show>+ <SetupOptions+ open={optionsOpen()}+ onToggle={() => setOptionsOpen(!optionsOpen())}+ agents={(setup.agents() ?? []).map((agent) => ({+ id: agent.id,+ name: agent.name,+ }))}+ agentId={choices().agentId}+ onAgent={setAgentId}+ needsInstall={chosenAgent()?.needs_install === true}+ workspace={workspace()}+ onWorkspace={setWorkspace}+ fullAccess={fullAccess()}+ onFullAccess={setFullAccess}+ />+ <div>+ <Button+ type="button"+ variant="cta"+ size="sm"+ disabled={!chosenAgent()}+ onClick={start}+ >+ {chosenAgent()+ ? t('localRuntime.setUpWith', { agent: agentName() })+ : t('localRuntime.setUp')}+ </Button>+ </div>+ </div>+ </Match>++ <Match when>+ <div class="flex flex-col gap-4">+ <SetupChecklist steps={steps()} />+ <Show when={failed()}>+ <div>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() =>+ fireAndForget(setup.run(choices()), 'local-runtime-setup')+ }+ >+ {t('localRuntime.tryAgain')}+ </Button>+ </div>+ </Show>+ </div>+ </Match>+ </Switch>+ </div>+ );+}++function SetupOptions(props: {+ open: boolean;+ onToggle: () => void;+ agents: { id: string; name: string }[];+ agentId: string | undefined;+ onAgent: (id: string) => void;+ needsInstall: boolean;+ workspace: string;+ onWorkspace: (value: string) => void;+ fullAccess: boolean;+ onFullAccess: (value: boolean) => void;+}) {+ return (+ <div class="flex flex-col gap-3">+ <button+ type="button"+ class="flex w-fit items-center gap-1 text-xs font-medium text-ink-muted not-touch:hover:text-ink"+ aria-expanded={props.open}+ onClick={() => props.onToggle()}+ >+ {t('localRuntime.options')}+ <CaretDownIcon+ aria-hidden="true"+ class={cn('size-3 transition-transform', props.open && 'rotate-180')}+ />+ </button>+ <Show when={props.open}>+ <div class="flex flex-col gap-4">+ <Show when={props.agents.length > 1}>+ <div class="flex w-full max-w-72 flex-col gap-1.5">+ <span class="text-xs font-medium text-ink">+ {t('localRuntime.agentLabel')}+ </span>+ <SettingsSelect+ label={t('localRuntime.agentLabel')}+ options={props.agents}+ value={props.agentId}+ onChange={props.onAgent}+ />+ </div>+ </Show>+ <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"+ >+ {t('localRuntime.workspaceLabel')}+ </label>+ <input+ id="local-runtime-workspace"+ type="text"+ spellcheck={false}+ class="settings-input min-w-0"+ value={props.workspace}+ onInput={(event) => props.onWorkspace(event.currentTarget.value)}+ />+ <p class="text-xs text-ink-extra-muted">+ {t('localRuntime.workspaceHint')}+ </p>+ </div>+ <label class="flex w-fit items-start gap-2 text-sm text-ink">+ <input+ type="checkbox"+ class="mt-0.5"+ checked={props.fullAccess}+ onChange={(event) =>+ props.onFullAccess(event.currentTarget.checked)+ }+ />+ <span>+ {t('localRuntime.fullAccess')}+ <span class="block text-xs text-ink-extra-muted">+ {t('localRuntime.fullAccessHint')}+ </span>+ </span>+ </label>+ <Show when={props.needsInstall}>+ <p class="text-xs text-ink-extra-muted">+ {t('localRuntime.connectorHint')}+ </p>+ </Show>+ </div>+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/settings/components/local-runtime-card.tsx b/apps/web/src/features/settings/components/local-runtime-card.tsxindex 69033a5210..3a62a0e12d 100644--- a/apps/web/src/features/settings/components/local-runtime-card.tsx+++ b/apps/web/src/features/settings/components/local-runtime-card.tsx@@ -1,13 +1,12 @@+import { LocalRuntimeSetup } from '@app/features/local-runtime/local-runtime-setup';import { toast } from '@core/component/Toast/Toast';import { fireAndForget } from '@core/util/fireAndForget';import { isDesktopPlatform } from '@core/util/platform';import LaptopIcon from '@icon/system/regular/laptop.svg';import SpinnerIcon from '@icon/system/regular/spinner-gap.svg';import {- type MacrodDetectedAgent,type MacrodStatus as MacrodSnapshot,type MacrodSupport,- macrodDetectAgents,macrodInspect,macrodStart,macrodStatus,@@ -15,7 +14,7 @@ import {macrodSupport,onMacrodStatus,} from '@macro/tauri/macrod';-import { useApproveHarnessPairingMutation } from '@queries/harnesses/harnesses';+import { useAgentsQuery } from '@queries/agents/agents';import type { UnlistenFn } from '@tauri-apps/api/event';import { Button } from '@ui';import {@@ -28,7 +27,6 @@ import {} 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;@@ -39,55 +37,27 @@ function errorMessage(error: unknown, fallback: string): string {/*** 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.+ * Setup runs through the shared `LocalRuntimeSetupPanel`, which also creates+ * an agent on the runtime; the app-wide `MacrodPairingApprover` approves the+ * daemon's pairing code, 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 agentsQuery = useAgentsQuery();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);+ /** Whether a config already exists on disk (daemon may be stopped). */+ const [configured, setConfigured] = createSignal(false);+ /** The setup panel, and the running daemon it finishes when set. */+ const [setup, setSetup] = createSignal<{ running?: MacrodSnapshot }>();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);- }+ if (next.phase === 'running') setConfigured(true);};onMount(() => {@@ -101,9 +71,6 @@ export function LocalRuntimeCard() {]);if (disposed) return;setSupport(supportInfo);- if (!workspace() && supportInfo.defaultWorkspace) {- setWorkspace(supportInfo.defaultWorkspace);- }handleStatus(current);if (!supportInfo.supported) return;unlisten = await onMacrodStatus(handleStatus);@@ -112,7 +79,7 @@ export function LocalRuntimeCard() {return;}const inspection = await macrodInspect();- if (!disposed && inspection.paired) setPaired(true);+ if (!disposed && inspection.exists) setConfigured(true);} catch (error) {console.error('could not probe the bundled macrod daemon', error);}@@ -125,47 +92,11 @@ export function LocalRuntimeCard() {});});- 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);- }+ /** The agent bound to the running daemon, once the agents list answers. */+ const boundAgent = () => {+ const harnessId = snapshot()?.harnessId;+ if (!harnessId || !agentsQuery.isSuccess) return undefined;+ return agentsQuery.data.find((agent) => agent.harness_id === harnessId);};const startExisting = async () => {@@ -230,7 +161,7 @@ export function LocalRuntimeCard() {}/></div>- <Show when={phase() === 'running'}>+ <Show when={phase() === 'running' && !setup()}><Buttontype="button"variant="outline"@@ -249,6 +180,20 @@ export function LocalRuntimeCard() {</p><Switch>+ <Match when={setup()}>+ {(open) => (+ <div class="mt-4">+ <LocalRuntimeSetup+ defaultWorkspace={+ support()?.defaultWorkspace ?? undefined+ }+ running={open().running}+ onClose={() => setSetup(undefined)}+ />+ </div>+ )}+ </Match>+<Match when={working()}><div class="mt-4 flex items-center gap-2 text-sm text-ink-muted"><SpinnerIcon class="size-4 animate-spin" />@@ -257,27 +202,7 @@ export function LocalRuntimeCard() {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>+ Connecting this computer to your account…</Match><Match when>Starting…</Match></Switch>@@ -285,27 +210,50 @@ export function LocalRuntimeCard() {</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>+ <Show+ when={boundAgent()}+ fallback={+ <div class="mt-4 flex flex-wrap items-center gap-3">+ <p class="text-sm text-ink-muted">+ <span class="font-medium text-ink">+ {snapshot()?.agentName ?? 'Your agent'}+ </span>{' '}+ is connected, but no Macro agent runs on it yet.+ </p>+ <Button+ type="button"+ variant="cta"+ size="sm"+ onClick={() => setSetup({ running: snapshot() })}+ >+ Create agent+ </Button>+ </div>+ }+ >+ {(agent) => (+ <p class="mt-4 text-sm text-ink-muted">+ <span class="font-medium text-ink">+ @{agent().bot.handle}+ </span>{' '}+ is ready+ <Show when={snapshot()?.workspace}>+ {(dir) => (+ <>+ {' '}+ in <span class="font-mono text-xs">{dir()}</span>+ </>+ )}+ </Show>+ . Keep the app open while you use it.+ </p>+ )}+ </Show></Match><Match when={phase() === 'error'}><div class="mt-4 flex flex-wrap items-center gap-3">- <p class="text-sm text-negative">+ <p class="text-sm text-failure">{snapshot()?.lastError ?? 'The local runtime stopped.'}</p><Button@@ -314,9 +262,9 @@ export function LocalRuntimeCard() {size="sm"disabled={busy()}onClick={() =>- paired()+ configured()? fireAndForget(startExisting(), 'local-runtime-card')- : openSetup()+ : setSetup({})}>Try again@@ -324,143 +272,7 @@ export function LocalRuntimeCard() {</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()}>+ <Match when={configured()}><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.@@ -485,7 +297,7 @@ export function LocalRuntimeCard() {type="button"variant="cta"size="sm"- onClick={openSetup}+ onClick={() => setSetup({})}>Set up</Button>diff --git a/apps/web/src/lib/i18n/locales/en.ts b/apps/web/src/lib/i18n/locales/en.tsindex ba423e0a0e..0d72346d07 100644--- a/apps/web/src/lib/i18n/locales/en.ts+++ b/apps/web/src/lib/i18n/locales/en.ts@@ -4,6 +4,7 @@ import commands from './en/commands';import common from './en/common';import create from './en/create';import entityActions from './en/entity-actions';+import localRuntime from './en/local-runtime';import mobile from './en/mobile';import nav from './en/nav';import settingsLanguage from './en/settings-language';@@ -22,6 +23,7 @@ export default {common,create,entityActions,+ localRuntime,mobile,nav,settingsLanguage,diff --git a/apps/web/src/lib/i18n/locales/en/local-runtime.ts b/apps/web/src/lib/i18n/locales/en/local-runtime.tsnew file mode 100644index 0000000000..d470547177--- /dev/null+++ b/apps/web/src/lib/i18n/locales/en/local-runtime.ts@@ -0,0 +1,40 @@+export default {+ title: 'Run agents on this computer',+ description:+ 'Macro runs the coding agents you already have, like Claude Code and Codex, right here with your own subscriptions and files.',+ scanning: 'Looking for agents on this computer…',+ found: 'Found {{agent}} on this computer.',+ noAgents:+ 'No supported agents were found. Install Claude Code, Codex, OpenCode, or OpenClaw, then scan again.',+ scanAgain: 'Scan again',+ setUp: 'Set up',+ setUpWith: 'Set up {{agent}}',+ options: 'Options',+ agentLabel: 'Agent',+ workspaceLabel: 'Workspace folder',+ workspaceHint: "Where sessions run. Created if it doesn't exist.",+ fullAccess: 'Full access',+ fullAccessHint:+ 'Let agents run commands and edit files without asking each time.',+ connectorHint: 'A small connector is downloaded on first start.',+ stepDetect: 'Find an agent',+ stepDetectDone: 'Found {{agent}}',+ stepConnect: 'Connect this computer',+ stepConnectStarting: 'Starting the local runtime…',+ stepConnectInstalling: 'Installing the {{agent}} connector…',+ stepConnectPairing: 'Linking this computer to your account…',+ stepAgent: 'Create your agent',+ stepAgentDone: '@{{handle}} is ready',+ tryAgain: 'Try again',+ readyTitle: '@{{handle}} is ready',+ readyDescription:+ 'Mention it in any channel or start a session. It runs on this computer while Macro is open.',+ readyWorkspace: 'Sessions run in {{workspace}}.',+ startSession: 'Start a session',+ done: 'Done',+ close: 'Close',+ later: 'Not now',+ promptTitle: 'Run agents on this computer',+ promptBody:+ 'Use Claude Code, Codex, and other agents you have installed from Macro, in one click.',+};diff --git a/apps/web/src/lib/queries/agents/agents.ts b/apps/web/src/lib/queries/agents/agents.tsindex 00d5b9fe9e..4116eddb23 100644--- a/apps/web/src/lib/queries/agents/agents.ts+++ b/apps/web/src/lib/queries/agents/agents.ts@@ -66,6 +66,14 @@ export function useAgentsQuery(enabled: Accessor<boolean> = () => true) {}));}+/** The saved agents, from the cache when fresh, for imperative callers. */+export async function fetchAgentsList(): Promise<AgentWithHarnessId[]> {+ return await queryClient.fetchQuery({+ queryKey: agentKeys.list.queryKey,+ queryFn: fetchAgents,+ });+}+export function invalidateAgents() {return queryClient.invalidateQueries({ queryKey: agentKeys.list.queryKey });}diff --git a/apps/web/src/lib/queries/harnesses/harnesses.ts b/apps/web/src/lib/queries/harnesses/harnesses.tsindex 0bd0d64eed..213a1c60a9 100644--- a/apps/web/src/lib/queries/harnesses/harnesses.ts+++ b/apps/web/src/lib/queries/harnesses/harnesses.ts@@ -90,6 +90,32 @@ export function useApproveHarnessPairingMutation() {}));}+/**+ * Approves a pairing opened by this computer's own daemon, granting exactly+ * the permission-bypass ceiling the daemon requested from its config, so a+ * re-pair keeps the access the user chose at setup.+ */+export function useApproveOwnHarnessPairingMutation() {+ return useMutation(() => ({+ gcTime: 0,+ mutationFn: async (code: string) => {+ const pairing = await throwOnErr(() =>+ storageServiceClient.getHarnessPairing({ code })+ );+ return await throwOnErr(() =>+ storageServiceClient.approveHarnessPairing({+ code,+ allow_permission_bypass:+ pairing.requested_allow_permission_bypass ?? false,+ })+ );+ },+ onSuccess: async () => await invalidateHarnesses(),+ onError: (error) =>+ console.error('failed to approve local harness pairing', error),+ }));+}+export function useDeleteHarnessMutation() {return useMutation(() => ({gcTime: 0,diff --git a/apps/web/src/lib/tauri/MacrodPairingApprover.test.tsx b/apps/web/src/lib/tauri/MacrodPairingApprover.test.tsxnew file mode 100644index 0000000000..734b9e6b74--- /dev/null+++ b/apps/web/src/lib/tauri/MacrodPairingApprover.test.tsx@@ -0,0 +1,65 @@+import { render, waitFor } from '@solidjs/testing-library';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { MacrodPairingApprover } from './MacrodPairingApprover';+import type { MacrodStatus } from './macrod';++const daemon = vi.hoisted(() => ({+ snapshot: undefined as MacrodStatus | undefined,+ emit: undefined as ((status: MacrodStatus) => void) | undefined,+ approve: vi.fn((_code: string) => {}),+}));++vi.mock('./macrod', () => ({+ macrodStatus: async () => daemon.snapshot,+ onMacrodStatus: async (callback: (status: MacrodStatus) => void) => {+ daemon.emit = callback;+ return () => {};+ },+}));+vi.mock('@queries/harnesses/harnesses', () => ({+ useApproveOwnHarnessPairingMutation: () => ({ mutate: daemon.approve }),+}));++function status(+ phase: MacrodStatus['phase'],+ pairingCode: string | null = null+): MacrodStatus {+ return {+ phase,+ agentId: null,+ agentName: null,+ workspace: null,+ pairingCode,+ pairingExpiresAt: null,+ harnessId: null,+ lastError: null,+ };+}++describe('MacrodPairingApprover', () => {+ beforeEach(() => {+ daemon.snapshot = status('stopped');+ daemon.emit = undefined;+ daemon.approve.mockClear();+ });++ it('approves a pairing that opened before it mounted', async () => {+ daemon.snapshot = status('pairing', 'ABCD-1234');+ render(() => <MacrodPairingApprover />);+ await waitFor(() =>+ expect(daemon.approve).toHaveBeenCalledWith('ABCD-1234')+ );+ });++ it('approves each new code from a re-pair once', async () => {+ render(() => <MacrodPairingApprover />);+ await waitFor(() => expect(daemon.emit).toBeDefined());++ daemon.emit?.(status('pairing', 'AAAA-1111'));+ daemon.emit?.(status('pairing', 'AAAA-1111'));+ daemon.emit?.(status('running'));+ daemon.emit?.(status('pairing', 'BBBB-2222'));++ expect(daemon.approve.mock.calls).toEqual([['AAAA-1111'], ['BBBB-2222']]);+ });+});diff --git a/apps/web/src/lib/tauri/MacrodPairingApprover.tsx b/apps/web/src/lib/tauri/MacrodPairingApprover.tsxnew file mode 100644index 0000000000..677d6f656b--- /dev/null+++ b/apps/web/src/lib/tauri/MacrodPairingApprover.tsx@@ -0,0 +1,49 @@+import { fireAndForget } from '@core/util/fireAndForget';+import { useApproveOwnHarnessPairingMutation } from '@queries/harnesses/harnesses';+import type { UnlistenFn } from '@tauri-apps/api/event';+import { onCleanup, onMount } from 'solid-js';+import { type MacrodStatus, macrodStatus, onMacrodStatus } from './macrod';++/**+ * Approves every pairing code the bundled macrod daemon opens, with the+ * signed-in session, wherever the user is in the app. The daemon re-pairs+ * on its own (an expired credential, a supervisor restart), and nobody types+ * a code on the desktop app, so approval cannot wait for Settings to be open.+ * Mounted by `LocalRuntimeHost`.+ */+export function MacrodPairingApprover() {+ const approve = useApproveOwnHarnessPairingMutation();+ // One attempt per code: a failed approval lets the pairing expire, and the+ // supervisor restarts the daemon with a fresh code.+ const attemptedCodes = new Set<string>();++ const handleStatus = (status: MacrodStatus) => {+ const code = status.pairingCode;+ if (status.phase !== 'pairing' || !code || attemptedCodes.has(code)) return;+ attemptedCodes.add(code);+ approve.mutate(code);+ };++ onMount(() => {+ let disposed = false;+ let unlisten: UnlistenFn | undefined;+ const subscribe = async () => {+ unlisten = await onMacrodStatus(handleStatus);+ if (disposed) {+ fireAndForget(unlisten(), 'macrod-pairing-approver');+ return;+ }+ // A pairing opened before this mounted (e.g. before sign-in) only+ // shows up in the snapshot.+ handleStatus(await macrodStatus());+ };+ fireAndForget(subscribe(), 'macrod-pairing-approver');+ onCleanup(() => {+ disposed = true;+ const dispose = unlisten;+ if (dispose) fireAndForget(dispose(), 'macrod-pairing-approver');+ });+ });++ return null;+}diff --git a/apps/web/tauri/src-tauri/src/desktop/macrod.rs b/apps/web/tauri/src-tauri/src/desktop/macrod.rsindex dac928fdf3..a29e4c5167 100644--- a/apps/web/tauri/src-tauri/src/desktop/macrod.rs+++ b/apps/web/tauri/src-tauri/src/desktop/macrod.rs@@ -8,6 +8,11 @@//! to the webview as a `macrod-status` event, and exposes commands to detect//! installed agents, start or stop the daemon, and read the snapshot.//!+//! Once started, the daemon is kept up: an unexpected exit (a crash, a lost+//! connection, an expired pairing) restarts it with backoff until the user+//! stops it, and app launch resumes any configured daemon the user has not+//! stopped.+//!//! 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@@ -16,6 +21,7 @@use std::path::PathBuf;use std::process::Stdio;use std::sync::{Arc, Mutex, OnceLock};+use std::time::Duration;use serde::{Deserialize, Serialize};use tauri::{AppHandle, Emitter, Manager};@@ -24,6 +30,18 @@ use tokio::io::AsyncBufReadExt as _;/// The webview event carrying each [`MacrodStatus`] change.const STATUS_EVENT: &str = "macrod-status";+/// The first restart delay after an unexpected exit; doubles per consecutive+/// failure up to [`RESTART_MAX_DELAY`].+const RESTART_BASE_DELAY: Duration = Duration::from_secs(1);+const RESTART_MAX_DELAY: Duration = Duration::from_secs(60);++/// How long to wait before restart attempt `attempt` (1-based).+fn restart_delay(attempt: u32) -> Duration {+ RESTART_BASE_DELAY+ .saturating_mul(1 << attempt.saturating_sub(1).min(6))+ .min(RESTART_MAX_DELAY)+}+/// Where the daemon lifecycle currently stands.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "kebab-case")]@@ -116,6 +134,11 @@ struct Inner {status: MacrodStatus,/// Increments per start so a stale reader task cannot clobber a newer run.generation: u64,+ /// Whether the daemon should be up: set by a start, cleared by a stop.+ /// An exit while this is set is unexpected and triggers a restart.+ wanted: bool,+ /// Consecutive restarts without reaching `running`, for backoff.+ restarts: u32,}fn emit_status(app: &AppHandle, status: &MacrodStatus) {@@ -318,9 +341,29 @@ pub(crate) async fn macrod_start(state: tauri::State<'_, MacrodState>,options: MacrodStartOptions,) -> Result<MacrodStatus, String> {- stop_child(&app, &state.inner).await;+ stop_child(&state.inner).await;+ {+ let mut inner = state.inner.lock().expect("macrod state lock");+ inner.wanted = true;+ inner.restarts = 0;+ }+ set_autostart(&app, true);+ let status =+ launch(&app, &state.inner, &options, None)?.expect("an unconditional launch always spawns");+ emit_status(&app, &status);+ Ok(status)+}- let mut command = macrod_command(&app)?;+/// Spawn `macrod service` and attach its readers. With `resume`, this is a+/// supervisor restart after that generation exited: it spawns nothing+/// (returns `None`) when a start or stop has happened since.+fn launch(+ app: &AppHandle,+ state: &Arc<Mutex<Inner>>,+ options: &MacrodStartOptions,+ resume: Option<u64>,+) -> Result<Option<MacrodStatus>, String> {+ let mut command = macrod_command(app)?;command.arg("service");if let Some(agent) = &options.agent {command.args(["--agent", agent]);@@ -337,37 +380,26 @@ pub(crate) async fn macrod_start(if allowed { "true" } else { "false" },]);}- let mut child = command+ command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())- .kill_on_drop(true)+ .kill_on_drop(true);++ // Spawn under the lock so a concurrent start or stop cannot interleave+ // with a supervisor restart.+ let mut inner = state.lock().expect("macrod state lock");+ if resume.is_some_and(|generation| inner.generation != generation || !inner.wanted) {+ return Ok(None);+ }+ let mut child = command.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 {+ if let Some(stderr) = child.stderr.take() {tauri::async_runtime::spawn(async move {let mut lines = tokio::io::BufReader::new(stderr).lines();while let Ok(Some(line)) = lines.next_line().await {@@ -375,9 +407,58 @@ pub(crate) async fn macrod_start(}});}- set_autostart(&app, true);- emit_status(&app, &status);- Ok(status)+ inner.child = Some(child);+ inner.generation += 1;+ inner.status = MacrodStatus {+ phase: MacrodPhase::Starting,+ ..MacrodStatus::default()+ };+ tauri::async_runtime::spawn(read_events(+ app.clone(),+ state.clone(),+ inner.generation,+ stdout,+ ));+ Ok(Some(inner.status.clone()))+}++/// Restart the daemon once the backoff for this failure elapses, unless a+/// start or stop superseded `generation` meanwhile. A spawn failure counts as+/// another failure and schedules the next attempt.+fn schedule_restart(app: AppHandle, state: Arc<Mutex<Inner>>, generation: u64) {+ let attempt = {+ let mut inner = state.lock().expect("macrod state lock");+ inner.restarts += 1;+ inner.restarts+ };+ let delay = restart_delay(attempt);+ tracing::warn!(target: "macrod", attempt, ?delay, "macrod exited unexpectedly; restarting");+ tauri::async_runtime::spawn(async move {+ tokio::time::sleep(delay).await;+ match launch(+ &app,+ &state,+ &MacrodStartOptions::default(),+ Some(generation),+ ) {+ Ok(Some(status)) => emit_status(&app, &status),+ Ok(None) => {}+ Err(error) => {+ tracing::warn!(target: "macrod", "macrod restart failed: {error}");+ let status = {+ let mut inner = state.lock().expect("macrod state lock");+ if inner.generation != generation || !inner.wanted {+ return;+ }+ inner.status.phase = MacrodPhase::Error;+ inner.status.last_error = Some(error);+ inner.status.clone()+ };+ emit_status(&app, &status);+ schedule_restart(app, state, generation);+ }+ }+ });}/// Fold the service's stdout into the snapshot until it closes.@@ -399,24 +480,34 @@ async fn read_events(return;}inner.status.apply(&event);+ if inner.status.phase == MacrodPhase::Running {+ inner.restarts = 0;+ }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 = {+ // why; otherwise show it as starting again, or stopped when unwanted.+ let (status, restart) = {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.phase = if inner.wanted {+ MacrodPhase::Starting+ } else {+ MacrodPhase::Stopped+ };}- inner.status.clone()+ (inner.status.clone(), inner.wanted)};emit_status(&app, &status);+ if restart {+ schedule_restart(app, inner, generation);+ }}/// Stop the supervised daemon and stop auto-starting it.@@ -426,7 +517,8 @@ pub(crate) async fn macrod_stop(state: tauri::State<'_, MacrodState>,) -> Result<MacrodStatus, String> {set_autostart(&app, false);- stop_child(&app, &state.inner).await;+ state.inner.lock().expect("macrod state lock").wanted = false;+ stop_child(&state.inner).await;let status = {let mut inner = state.inner.lock().expect("macrod state lock");inner.status = MacrodStatus::default();@@ -451,6 +543,7 @@ pub(crate) fn macrod_status(state: tauri::State<'_, MacrodState>) -> MacrodStatupub(crate) fn kill_now(state: &MacrodState) {let child = {let mut inner = state.inner.lock().expect("macrod state lock");+ inner.wanted = false;inner.generation += 1;inner.child.take()};@@ -460,7 +553,7 @@ pub(crate) fn kill_now(state: &MacrodState) {}/// Kill the child, invalidating any reader still attached to it.-async fn stop_child(_app: &AppHandle, inner: &Arc<Mutex<Inner>>) {+async fn stop_child(inner: &Arc<Mutex<Inner>>) {let child = {let mut inner = inner.lock().expect("macrod state lock");inner.generation += 1;@@ -510,24 +603,27 @@ fn set_autostart(app: &AppHandle, autostart: bool) {}}-fn autostart_enabled(app: &AppHandle) -> bool {+/// Whether the user explicitly stopped the daemon. Only a stop opts out of+/// auto-start; a missing or unreadable marker does not.+fn stopped_by_user(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)+ .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.+/// At app launch: resume the daemon whenever a config exists and the user has+/// not stopped it, so agents are reachable without opening settings. A config+/// whose credential lapsed re-pairs, and the webview approves the new code.pub(crate) fn autostart(app: &AppHandle) {let app = app.clone();tauri::async_runtime::spawn(async move {- if !autostart_enabled(&app) || macrod_binary(&app).is_none() {+ if stopped_by_user(&app) || macrod_binary(&app).is_none() {return;}- let paired = match macrod_query(&app, &["inspect"]).await {+ let configured = match macrod_query(&app, &["inspect"]).await {Ok(inspection) => inspection- .get("paired")+ .get("exists").and_then(serde_json::Value::as_bool).unwrap_or(false),Err(error) => {@@ -535,7 +631,7 @@ pub(crate) fn autostart(app: &AppHandle) {false}};- if !paired {+ if !configured {return;}let state = app.state::<MacrodState>();@@ -544,3 +640,15 @@ pub(crate) fn autostart(app: &AppHandle) {}});}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn restart_delay_doubles_up_to_the_cap() {+ let seconds: Vec<u64> = (1..=9).map(|n| restart_delay(n).as_secs()).collect();+ assert_eq!(seconds, [1, 2, 4, 8, 16, 32, 60, 60, 60]);+ assert_eq!(restart_delay(u32::MAX), RESTART_MAX_DELAY);+ }+}diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.mdindex 32ea4028fa..6b9d0b8b40 100644--- a/docs/agent-guide/settings.md+++ b/docs/agent-guide/settings.md@@ -661,7 +661,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, and Codex configuration, followed by paired macrod runtimes. Codex's card appears 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.+The `Runtimes` section shows built-in Macro, Cursor, and Codex configuration, followed by paired macrod runtimes. Codex's card appears 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 and names the one it will use (Claude Code first, then Codex, OpenCode, OpenClaw, Hermes); `Options` changes the agent, workspace folder, and Full access. `Set up <agent>` then walks a three-step checklist — Find an agent, Connect this computer (start, install the connector, link to the account; the pairing is approved automatically, no code is typed), Create your agent (a private `@<agent>` coding agent bound to this runtime) — and ends on `@<agent> is ready` with `Start a session`, which opens the Agents composer in Code mode on that agent. A failed step shows its error and `Try again`, which resumes at the failed step. A desktop app that was never set up also shows a one-time “Run agents on this computer” prompt whose `Set up` runs the same flow in a dialog; closing the prompt sticks. A running runtime with no agent bound to it offers `Create agent`. The app then keeps the daemon up: it restarts after any unexpected exit (with backoff) and on every launch until the user presses `Stop`, and any re-pairing is approved from wherever the user is in the app, not only on this card. While running the card shows the bound agent and workspace with a `Stop` action; a 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 usesthe same live model discovery and retains its existing save action.diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.ymlindex 18f8a7a889..bf9e5620e0 100644--- a/rules/ast-grep/ts-feature-components-presentational.yml+++ b/rules/ast-grep/ts-feature-components-presentational.yml@@ -23,6 +23,7 @@ files:- apps/web/src/features/agent-activity/components/**- apps/web/src/features/agent-dms/components/**- apps/web/src/features/agent-conversations/components/**+ - apps/web/src/features/local-runtime/components/**- apps/web/src/features/agent-interactions/components/**- apps/web/src/features/billing-lab/components/**- apps/web/src/features/paywall/components/ai-usage-limit-dialog*diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.ymlindex cd9fd976f9..a6ac4d295a 100644--- a/rules/ast-grep/ts-feature-core-pure.yml+++ b/rules/ast-grep/ts-feature-core-pure.yml@@ -25,6 +25,7 @@ files:- apps/web/src/features/agent-activity/core/**- apps/web/src/features/agent-dms/core/**- apps/web/src/features/agent-conversations/core/**+ - apps/web/src/features/local-runtime/core/**- apps/web/src/features/agent-interactions/core/**- apps/web/src/features/billing-lab/core/**- apps/web/src/features/calendar-team/core/**diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.ymlindex 2ac69e0d5a..b54231bb24 100644--- a/rules/ast-grep/ts-feature-data-no-ui.yml+++ b/rules/ast-grep/ts-feature-data-no-ui.yml@@ -30,9 +30,11 @@ files:- apps/web/src/features/agent-activity/queries/**- apps/web/src/features/agent-dms/queries/**- apps/web/src/features/agent-conversations/queries/**+ - apps/web/src/features/local-runtime/queries/**- apps/web/src/features/agent-activity/primitives/**- apps/web/src/features/agent-dms/primitives/**- apps/web/src/features/agent-conversations/primitives/**+ - apps/web/src/features/local-runtime/primitives/**- apps/web/src/features/agent-interactions/queries/**- apps/web/src/features/agent-interactions/primitives/**- apps/web/src/features/billing-lab/queries/**diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.ymlindex 6f75fda2fe..0c2eb9fbba 100644--- a/rules/ast-grep/ts-feature-layers-use-context.yml+++ b/rules/ast-grep/ts-feature-layers-use-context.yml@@ -49,15 +49,19 @@ files:- apps/web/src/features/agent-activity/queries/**- apps/web/src/features/agent-dms/queries/**- apps/web/src/features/agent-conversations/queries/**+ - apps/web/src/features/local-runtime/queries/**- apps/web/src/features/agent-activity/primitives/**- apps/web/src/features/agent-dms/primitives/**- apps/web/src/features/agent-conversations/primitives/**+ - apps/web/src/features/local-runtime/primitives/**- apps/web/src/features/agent-activity/components/**- apps/web/src/features/agent-dms/components/**- apps/web/src/features/agent-conversations/components/**+ - apps/web/src/features/local-runtime/components/**- apps/web/src/features/agent-activity/views/**- apps/web/src/features/agent-dms/views/**- apps/web/src/features/agent-conversations/views/**+ - apps/web/src/features/local-runtime/views/**- apps/web/src/features/agent-interactions/queries/**- apps/web/src/features/agent-interactions/primitives/**- apps/web/src/features/agent-interactions/components/**diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.ymlindex 6a325d15f6..e3211d4367 100644--- a/rules/ast-grep/tsx-feature-components-presentational.yml+++ b/rules/ast-grep/tsx-feature-components-presentational.yml@@ -23,6 +23,7 @@ files:- apps/web/src/features/agent-activity/components/**- apps/web/src/features/agent-dms/components/**- apps/web/src/features/agent-conversations/components/**+ - apps/web/src/features/local-runtime/components/**- apps/web/src/features/agent-interactions/components/**- apps/web/src/features/billing-lab/components/**- apps/web/src/features/paywall/components/ai-usage-limit-dialog*diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.ymlindex 0f44f27150..c80b39001f 100644--- a/rules/ast-grep/tsx-feature-core-pure.yml+++ b/rules/ast-grep/tsx-feature-core-pure.yml@@ -25,6 +25,7 @@ files:- apps/web/src/features/agent-activity/core/**- apps/web/src/features/agent-dms/core/**- apps/web/src/features/agent-conversations/core/**+ - apps/web/src/features/local-runtime/core/**- apps/web/src/features/agent-interactions/core/**- apps/web/src/features/billing-lab/core/**- apps/web/src/features/calendar-team/core/**diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.ymlindex 0005417383..2075b0b2df 100644--- a/rules/ast-grep/tsx-feature-data-no-ui.yml+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml@@ -30,9 +30,11 @@ files:- apps/web/src/features/agent-activity/queries/**- apps/web/src/features/agent-dms/queries/**- apps/web/src/features/agent-conversations/queries/**+ - apps/web/src/features/local-runtime/queries/**- apps/web/src/features/agent-activity/primitives/**- apps/web/src/features/agent-dms/primitives/**- apps/web/src/features/agent-conversations/primitives/**+ - apps/web/src/features/local-runtime/primitives/**- apps/web/src/features/agent-interactions/queries/**- apps/web/src/features/agent-interactions/primitives/**- apps/web/src/features/billing-lab/queries/**diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.ymlindex 305dcd3cd2..0eeb60eeb4 100644--- a/rules/ast-grep/tsx-feature-layers-use-context.yml+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml@@ -49,15 +49,19 @@ files:- apps/web/src/features/agent-activity/queries/**- apps/web/src/features/agent-dms/queries/**- apps/web/src/features/agent-conversations/queries/**+ - apps/web/src/features/local-runtime/queries/**- apps/web/src/features/agent-activity/primitives/**- apps/web/src/features/agent-dms/primitives/**- apps/web/src/features/agent-conversations/primitives/**+ - apps/web/src/features/local-runtime/primitives/**- apps/web/src/features/agent-activity/components/**- apps/web/src/features/agent-dms/components/**- apps/web/src/features/agent-conversations/components/**+ - apps/web/src/features/local-runtime/components/**- apps/web/src/features/agent-activity/views/**- apps/web/src/features/agent-dms/views/**- apps/web/src/features/agent-conversations/views/**+ - apps/web/src/features/local-runtime/views/**- apps/web/src/features/agent-interactions/queries/**- apps/web/src/features/agent-interactions/primitives/**- apps/web/src/features/agent-interactions/components/**