SLOPSHOPPER

account-history-sync

Keep local Desktop Code history in sync with an inactive account.

panebandspinnercommandprocesstimer
v0.5.1no licenseupdated 2026-10-20roozbehid/ClaudeSync/mods/account-history-sync
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · account-history-sync
│ ┃ History sync ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ History sync ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ [ Copy diagnostics ] ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ [ › Accounts ] [ Sync ] [ Backups ] ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ Accounts │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ From · Confirm the account open in Claude │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ Sync paused after an error. │ ┃ › /history-sync │ ┃ Account open now: Choose the open account… │ ┃ │ ┃ To · inactive account: Choose destination… │ ┃ │ ┃ Copy saved Code history from this account │ ┃ into the destination. Keep the destination │ ┃ account inactive. │ ┃ │ ┃ [ Copy profile list ] │ ┃ │ ┃ [ Refresh accounts ] [ Continue to Sync ] │ ┃ ⟨Claude Code's own drawing⟩ [ History sync · Prompt · needs attention ] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ⟨Claude Code's own drawing⟩ [ History sync · Hint · needs attention ] ⟨Claude Code's own drawing⟩ [ History sync · Mode · needs attention ]

Draws

Band
⟨Claude Code's own drawing⟩ [ History sync · Prompt · needs attention ]
Pane · History sync
History sync [ Copy diagnostics ] [ › Accounts ] [ Sync ] [ Backups ] Accounts From · Confirm the account open in Claude Sync paused after an error. Account open now: Choose the open account… ▾ To · inactive account: Choose destination… ▾ Copy saved Code history from this account into the destination. Keep the destination account inactive. [ Copy profile list ] [ Refresh accounts ] [ Continue to Sync ] Prompt controls Show near the prompt: Menu button only ▾ Launcher placement: Compare all three locations ▾ Compare shows Prompt, Mode, and Hint labels. A location appears only if this Desktop build asks the mod to draw it. /history-sync always opens the pane. This launcher appears in the main conversation only. Claude decides where the settings pane opens. Account history sync runs on native Windows sessions.
Prompt hint
⟨Claude Code's own drawing⟩ [ History sync · Hint · needs attention ]
README

Account history sync mod

Windows plugin for Claude Code Mods. Once loaded, a History sync menu button appears in the enabled Code-session locations. Click it, choose an inactive destination in Accounts, then open Sync to preview, copy once, or start automatic syncing. Copying is always from this session's account into the destination. The source's Desktop metadata is never changed. Archive indexes and cards in the destination get verified backups.

The mod matches the current session ID to local Desktop history cards. A unique match supplies the source; check the displayed account before syncing. If the session appears in several profiles (including previously copied sessions), or has no Desktop card yet, click Sync settings and confirm which account is open. That confirmation lasts only for this session. No global CLI login or saved source choice is treated as Desktop's current account. A new session card is discovered after a turn or on the next 30-second check.

Auto-sync checks saved files every 30 seconds and 1.5 seconds after a main-agent turn completes. It uses PowerShell, without model calls. It starts paused in each session and after hot reload. Pause before switching accounts. Choosing another destination waits for any running copy and pauses automation. It does not run at shutdown. The destination and Details preference are remembered, along with the last successful result and eight recent backup receipts. Source confirmation and automatic-sync permission stay session-local. Selecting another destination clears its preview but keeps previous receipts with their original account direction.

Controls

Version 0.4.0 defaults to Compare all three locations: an above-prompt button, a SessionMode-area button, and a PromptHint-area button, labeled Prompt, Mode, and Hint. A site appears only when the host asks the mod to render it; native fixture tests validate all three, but do not prove this Desktop build paints each one. Accounts → Launcher placement keeps one location or restores comparison. The existing contents of each site are preserved.

By default, only a menu button appears at each enabled site. Account details, results, and errors stay inside the pane; Pause also appears beside the button while automation is running. The above-prompt launcher is omitted in subagent transcript panels. Under Accounts → Prompt controls, choose Menu button only, Status and quick controls, or Hide. Hiding it leaves /history-sync available. This preference is remembered without starting or stopping a sync.

Three additional DOM launchers provide a sidebar entry, header menu, and floating button. They open this same pane by activating its existing native button; they do not add another sync engine. Their temporary loader supports a Store-build comparison through a loopback DevTools session instead of patching installed files. Live injection needs a Desktop restart; see the instructions and current verification status there.

The optional status band shows source → destination and the last sync time for that direction, with Sync now, Sync settings, and collapsible Details. The official API does not offer a global Desktop toolbar slot; the DOM experiment adds its own controls to the page. Claude controls where the band and pane are placed.

The menu has three sections:

  • Accounts: confirm the source if needed and choose the inactive destination.
  • Sync: preview changes, sync once, and start or pause automation.
  • Backups: review recent backup paths, original directions, and interrupted copies.

Before and after preview

Version 0.5.1 includes local conversations that spawned cloud tasks, provided their local transcript exists. New destination cards omit the source's cloud task links; existing cards keep their own links. Account-bound environment scopes remain excluded.

Version 0.5.0 replaces the filename-heavy preview with a table showing the real session title, destination state before, destination state after, and change. Renames show the old title as well. Unchanged sessions are included; skipped and conflicting sessions show the destination remaining unchanged. A session without a saved title is labeled Untitled session. File IDs are available under the row's Details button and in copied diagnostic data.

  • All / Active / Archived: filters use the planned destination state. All also includes source cards that would remain absent, such as unfinished sessions.
  • Changes: show all sessions, additions/updates, or conflicts/skipped entries.
  • Search titles: matches both source and before/after destination titles.
  • Previous / Next: 15 sessions per page, sorted by title.
  • Copy filtered table: copies every matching row across pages as tab-separated text. Copy preview retains the complete held comparison regardless of filters.

Filtering, searching, paging, and copying do not run another plan, copy history, or enable automatic sync. Comparisons use the original plan snapshot; constructing a proposed update no longer mutates the destination snapshot. Up to 1,000 comparison rows are returned, with an explicit notice if a larger inventory is truncated. Use Preview again to refresh the snapshot.

Version 0.4.1 adds Copy diagnostics, Copy profile list, Copy preview, and Copy backup path. These copy through the clipboard API for the surface where the button was pressed. Diagnostics retain the complete error; Copy preview includes the held report beyond the panel's text display limit. A clipboard failure shows feedback without changing sync permission or starting a helper. Native Text elements do not expose a selection property, so these buttons provide copying even when Desktop does not allow selecting the pane's text with the mouse.

No slash command is required. The interactive preview uses fixture accounts and simulated operations only. Claude controls the actual styling and pane placement; this preview does not demonstrate host compatibility.

Load and install

For first-time persistent installation in Desktop, open PowerShell and run:

Set-Location C:\path\to\ClaudeSync
powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Build-Mod.ps1
claude plugin marketplace add C:\path\to\ClaudeSync
claude plugin install account-history-sync@account-history-tools --scope user

For an existing installation, update it instead:

claude plugin marketplace update account-history-tools
claude plugin update account-history-sync@account-history-tools --scope user

Installation can be completed even while the rollout blocks execution. Then:

  1. Open Claude Desktop and sign into the account you want to copy from.
  2. Open the Code tab and a native Windows local session.
  3. Run /reload-plugins, or start a fresh Code session. In /plugin, verify account-history-sync is installed and enabled.
  4. Look for the History sync · Prompt, Mode, or Hint buttons at the sites Desktop renders. No slash command is needed. /history-sync is the fallback.
  5. Click History sync → Accounts. Check From, then choose the other, inactive account in To. Confirm the open account if discovery is ambiguous.
  6. Click Continue to Sync, then Preview, Sync now, or Start auto-sync. Open Backups to see receipts. Enable the optional status band for a Sync now shortcut.
  7. Before changing accounts, click Pause auto-sync. Open a fresh session in the other account; check its source and choose the destination before restarting.

If the controls are missing and /history-sync is unknown, check the rollout from PowerShell:

claude plugin test C:\path\to\ClaudeSync\mods\account-history-sync

For a temporary CLI session instead of persistent installation:

claude --plugin-dir C:\path\to\ClaudeSync\mods\account-history-sync

The menu button appears above Claude's prompt. /history-sync also opens its settings pane. Desktop WSL sessions do not support Mods according to the current docs.

If the plugin is enabled but both its UI and /history-sync are missing, check the session's environment first. Desktop can list the Windows-installed plugin while the selected Code session runs in WSL, where plugins are unavailable. Opening a native Windows Code session in the same signed-in account provides the controller. Keep the other account inactive and confirm the displayed source before copying. The controller can copy eligible WSL history cards from the Windows side; WSL execution itself does not host this Mod.

For a read-only profile query from PowerShell:

Set-Location C:\path\to\ClaudeSync
.\Sync-ClaudeHistory.ps1 -Mode Profiles

It lists full profile IDs, known email labels, their sources, and session counts. Use -ConfigPath "$env:LOCALAPPDATA\ClaudeHistorySync\profiles.json" to query the Mod's configured roots instead. Labels identify folders; this query does not authenticate which Desktop account is currently open.

Anthropic documents engine 2.1.287 or later as the Mods baseline. However, Desktop 2.19675.0, bundling 2.1.286, was observed rendering this mod and passed all three native fixture tests, including Desktop-surface menu interactions. Observed loading is stronger evidence than assuming a build cannot load solely from its version. The terminal CLI's rollout result is separate: CLI 2.1.288 still reported a cached disabled switch while Desktop's engine ran these tests. No real account history sync or full account-switch test was performed.

For a missing UI, check that Desktop's session loaded the plugin, and run tests with its actual worker executable. A terminal claude --version or test result does not establish Desktop's engine or rollout state. Updating the plugin does not update Desktop's Code engine. See the Desktop UI and loading review for evidence and ideas from the reference UI project.

Commands

  • /history-sync opens the settings pane (optional unless the launcher is hidden).
  • /history-sync accounts opens account selection.
  • /history-sync backups opens recent backup receipts.
  • /history-sync profiles lists emails, IDs, and session counts.
  • /history-sync to <destination-email-or-id> selects the inactive destination.
  • /history-sync preview checks without writing Desktop history.
  • /history-sync sync copies once, declaring the source active and destination inactive.
  • /history-sync start enables automatic copying for this session with the same declaration.
  • /history-sync pause waits for the current operation and releases the controller.
  • /history-sync status prints status.

Ambiguous emails require full account-GUID\organization-GUID profile IDs. CLI commands accept selectors without spaces. A compatibility pair <source> <destination> command can confirm an unresolved source, but cannot reverse a source already identified in this session. The destination is remembered; permission to auto-sync is not remembered. Multiple sessions share an exclusive controller lease. Pause the controller in its original session to switch control; after a crashed or ended session, its lease expires within three minutes.

Configuration and recovery

The helper initializes %LOCALAPPDATA%\ClaudeHistorySync\profiles.json with SessionsRoot: "Auto". Discovery first reads the running Desktop's --user-data-dir argument in the current Windows session, following relocated data directories without pinning a username, app version, or Store publisher ID. When Desktop is closed or process inspection is unavailable, it checks regular, Store, and Claude-Data installations under the current user's application-data directories. Duplicate process paths are collapsed. Multiple candidates produce an error listing the paths; discovery never chooses by modification time.

If an older config pins a directory that has moved, back up that config and change SessionsRoot to "Auto". Explicit custom paths are still honored and are never silently replaced. If discovery cannot find a root, open Desktop and a Code session and refresh accounts. For an ambiguous installation, set an explicit absolute history path after checking which directory Desktop uses. Large previews are transferred through a private snapshot file instead of process stdout, which Claude can truncate. Each session overwrites its own snapshot under mod-previews beside the config. The file is limited to the host's 4 MiB read limit; omitted rows and report entries are explicitly marked as truncated. These snapshots contain history titles and should stay private.

Automatic discovery handles data-root moves while the claude-code-sessions layout remains compatible; an upstream history-format change may require an update. Discovery creates that private config but does not edit history. Put profile-labels.json alongside it for manual email labels. Settings, state, and backups live outside the plugin install/cache folder.

Desktop can save a correctly named card before its CLI session starts. A missing, null, or empty CLI session ID now marks that card Pending in inventory and Skipped in the plan. The card and its archive state stay untouched, including when it is in the destination. Incorrect nonempty CLI IDs, filename/session-ID mismatches, missing working directories, malformed JSON, and invalid archive flags still stop the plan. Preview returns up to 1,000 report entries and explicitly reports truncation beyond that limit.

Sync preserves local parent/side-session links, fork origins and fork-point messages, and explicit detachment. Existing copies missing this metadata are repaired on the next sync even when their titles match. Preview details show the parent before and after. Children with unavailable or mismatched ancestors, deletion-marked parents, or cyclic lineage are skipped with a reason; the tool does not resurrect a missing parent. Cloud task ownership remains account-specific.

For custom roots or existing labels, set ACCOUNT_HISTORY_SYNC_CONFIG to the full path of a profiles.json before starting Claude, or through Claude's environment settings. The script uses that config's directory for state and the mod controller. It must support private Windows ACLs. Configuration and labels use the same format as the standalone script. No credentials or tokens are copied into the plugin.

The Backups section shows up to eight recent receipts, and automatic failures pause syncing. Use the standalone engine's Undo with that config and printed backup, after closing Claude. Undo is deliberately not automated by the mod:

.\Sync-ClaudeHistory.ps1 -Mode Undo -ConfigPath "$env:LOCALAPPDATA\ClaudeHistorySync\profiles.json" -Backup 'C:\printed\backup\path' -WhatIf

After reviewing, remove -WhatIf to restore. A timed-out helper can leave a prepared receipt under state\pairs\PAIR_HASH\backups; inspect that before retrying. Backups include conversation summaries and should stay private.

Mods' published API does not provide a current account ID. Matching a session's local card is account-folder discovery, not authentication; check the source shown in the UI. If ambiguous, the mod relies on your session-local confirmation. Before preview, arming, or sync, the helper rejects a source outside the session's matching profiles, when matches exist. It cannot verify that the destination is inactive. File hashes and atomic replacement reduce write races but cannot prevent Desktop from later writing cached metadata. It syncs local history cards and environment references, not cloud session ownership, credentials, or transcripts. See the repository README for eligibility and policies.

Tests

node --test .\mods\account-history-sync\tests\controller.test.mjs
.\Test-SessionsDiscovery.ps1
.\Test-ModBridge.ps1
claude plugin test .\mods\account-history-sync

Node is needed only for the independent controller tests, not to run the mod. PowerShell bridge tests use isolated local fixtures and never modify real history. Claude's native test runner requires Mods to load in the executable running the tests. Rebuild the fixture preview after changing the UI with node .\tools\Build-UiPreview.mjs. The DOM fixture suite runs separately with npm ci --ignore-scripts and npm test under experiments/dom-launchers; those packages are not shipped in the native plugin.

Source 3 files
hooks/register.mjs 119 lines
1import { createController } from './controller.mjs';
2import { renderBand, renderPane, renderLauncher, launcherVisible } from './ui.mjs';
3
4const PANE = 'history-sync';
5const HELP = 'Open History sync above the prompt or use /history-sync. Optional commands: accounts, backups, profiles, to <inactive-destination-email-or-id>, preview, sync, start, pause, status. Pause before switching accounts.';
6
7export function register(on) {
8  const controller = createController();
9  on('session.start', async ($, e, next) => {
10    const adapter = {
11      root: $.plugin.root,
12      windows: (await $.env.get('OS')) === 'Windows_NT',
13      processRun: (argv, options) => $.process.run(argv, options),
14      readText: path => $.fs.read(path),
15      redraw: () => $.ui.invalidate('ui.render'),
16      log: text => $.ui.log(text),
17      now: () => $.clock.now(),
18      sessionId: () => $.session.id(),
19      envGet: () => $.env.get('ACCOUNT_HISTORY_SYNC_CONFIG'),
20      storeGet: key => $.store.get(key),
21      storeSet: (key, value) => $.store.set(key, value),
22      every: (ms, fn) => $.clock.every(ms, fn),
23      after: (ms, fn) => $.clock.after(ms, fn),
24    };
25    await controller.initialize(adapter);
26    await $.command.register({ name: 'history-sync', description: 'Manage local account history sync', argumentHint: '[accounts|backups|to|preview|sync|start|pause|status]', immediate: true });
27    return next(e);
28  });
29  on('session.end', async ($, e, next) => {
30    controller.stop();
31    // No last-minute writes on logout, resume, clear, or shutdown.
32    return next(e);
33  });
34  on('turn.complete', async ($, e, next) => {
35    const result = await next(e);
36    if (!e.agentId) { await controller.reopen(); controller.afterTurn(); }
37    return result;
38  });
39  on('command.run', { command: 'history-sync' }, async ($, e) => {
40    const args = (e.args || '').trim().split(/\s+/).filter(Boolean);
41    try {
42      await controller.reopen();
43      switch (args[0] || '') {
44        case '': case 'accounts': case 'backups':
45          if (args[0]) controller.showSection(args[0]);
46          if (!controller.view.source || !controller.view.target) controller.showSection(args[0] === 'backups' ? 'backups' : 'accounts');
47          await $.ui.open({ id: PANE, title: 'History sync', focus: true, closeOnEscape: true });
48          await controller.refresh();
49          return {};
50        case 'profiles': {
51          await controller.refresh();
52          return { text: controller.view.profiles.map(p => `${p.Email || p.Label} | ${p.Id} | ${p.Sessions} sessions`).join('\n') || controller.statusText() };
53        }
54        case 'to':
55          if (args.length !== 2) return { text: HELP };
56          await controller.refresh();
57          await controller.choose(controller.view.source, controller.resolveSelector(args[1]));
58          return { text: controller.statusText() };
59        case 'pair': // Compatibility: cannot replace an already identified current source.
60          if (args.length !== 3) return { text: HELP };
61          await controller.refresh();
62          await controller.choose(controller.resolveSelector(args[1]), controller.resolveSelector(args[2]));
63          return { text: controller.statusText() };
64        case 'preview': await controller.preview(); return { text: controller.statusText() };
65        case 'sync': await controller.sync(); return { text: controller.statusText() };
66        case 'start': await controller.start(); return { text: controller.statusText() };
67        case 'pause': await controller.pause(); return { text: controller.statusText() };
68        case 'status': return { text: controller.statusText() };
69        default: return { text: HELP };
70      }
71    } catch (error) { return { text: error.message }; }
72  });
73  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
74    if (e.requestId !== PANE) return next(e);
75    const { Box, Text, Button, Select, Input } = $.ui.resolve(e);
76    return renderPane({ Box, Text, Button, Select, Input }, controller,
77      (text, surface) => $.ui.copy({ text, surface: surface || e.surface }));
78  });
79  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
80    const existing = await next(e);
81    if (e.props?.hasSurvey || e.props?.view?.agentId || !launcherVisible(controller.view, 'band')) return existing;
82    const { Box, Text, Button } = $.ui.resolve(e);
83    return Box({ flexDirection: 'column', children: [existing,
84      renderBand({ Box, Text, Button }, controller, async () => {
85        await controller.reopen();
86        if (!controller.view.source || !controller.view.target) controller.showSection('accounts');
87        await $.ui.open({ id: PANE, title: 'History sync', focus: true, closeOnEscape: true });
88        await controller.refresh();
89      }),
90    ] });
91  });
92  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
93    const existing = await next(e);
94    if (!launcherVisible(controller.view, 'mode')) return existing;
95    const { Box, Button } = $.ui.resolve(e);
96    return Box({ flexDirection: 'row', flexWrap: 'wrap', gap: 1, children: [existing,
97      renderLauncher({ Box, Button }, controller, async () => {
98        await controller.reopen();
99        if (!controller.view.source || !controller.view.target) controller.showSection('accounts');
100        await $.ui.open({ id: PANE, title: 'History sync', focus: true, closeOnEscape: true });
101        await controller.refresh();
102      }, 'mode'),
103    ] });
104  });
105  on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
106    const existing = await next(e);
107    if (!launcherVisible(controller.view, 'hint')) return existing;
108    const { Box, Button } = $.ui.resolve(e);
109    return Box({ flexDirection: 'row', flexWrap: 'wrap', gap: 1, children: [existing,
110      renderLauncher({ Box, Button }, controller, async () => {
111        await controller.reopen();
112        if (!controller.view.source || !controller.view.target) controller.showSection('accounts');
113        await $.ui.open({ id: PANE, title: 'History sync', focus: true, closeOnEscape: true });
114        await controller.refresh();
115      }, 'hint'),
116    ] });
117  });
118}
119
hooks/controller.mjs 286 lines
1const PROFILE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2
3export function describeResult(result) {
4  const mode = result.Action === 'Plan' ? 'Preview' : 'Synced';
5  return `${mode}: ${result.Additions ?? 0} added, ${result.Updates ?? 0} updated, ${result.Conflicts ?? 0} conflicts, ${result.Skipped ?? 0} skipped.`;
6}
7
8export function createController() {
9  const view = {
10    profiles: [], source: '', sourceCandidates: [], target: '', enabled: false, busy: false,
11    status: 'Finding the account for this session…', error: '',
12    backup: '', report: [], previewRows: [], previewFilter: 'all', previewChanges: 'all', previewSearch: '', previewPage: 0,
13    selectedPreview: '', configPath: '', lastSync: '', copyStatus: '',
14    section: 'accounts', expanded: false, promptDisplay: 'launcher', launcherPlacement: 'all', preview: null, lastResult: null, receipts: [], notice: '',
15  };
16  let api;
17  let owner = '';
18  let configOverride = '';
19  let running = null;
20  let ended = false;
21  let interval = null;
22  let debounce = null;
23  let revision = 0;
24
25  function redraw() { api.redraw('ui.render'); }
26  async function remember(key, value) {
27    try { await api.storeSet(key, value); }
28    catch { view.notice = 'Could not remember preferences or recent results. Any backup already created remains on disk.'; redraw(); }
29  }
30  function showSection(section) {
31    if (!['accounts', 'sync', 'backups'].includes(section)) return;
32    view.section = section; redraw();
33  }
34  function filterPreview(value) {
35    if (!['all', 'active', 'archived'].includes(value)) return;
36    view.previewFilter = value; view.previewPage = 0; redraw();
37  }
38  function filterPreviewChanges(value) {
39    if (!['all', 'changes', 'issues'].includes(value)) return;
40    view.previewChanges = value; view.previewPage = 0; redraw();
41  }
42  function searchPreview(value) { view.previewSearch = String(value).slice(0, 200); view.previewPage = 0; redraw(); }
43  function pagePreview(value) { if (Number.isInteger(value) && value >= 0) { view.previewPage = value; redraw(); } }
44  function selectPreview(file) { if (view.previewRows.some(r => r.File === file)) { view.selectedPreview = view.selectedPreview === file ? '' : file; redraw(); } }
45  function clearPreview() { view.report = []; view.previewRows = []; view.preview = null; view.previewPage = 0; view.selectedPreview = ''; }
46  async function copyText(text, writer, surface) {
47    try {
48      const result = await writer(text, surface);
49      view.copyStatus = result?.isCopied ? 'Copied to clipboard.' : `Could not copy to clipboard (${result?.reason || 'unavailable'}).`;
50    } catch (error) { view.copyStatus = `Copy failed: ${error.message}`; }
51    redraw();
52  }
53  async function toggleDetails() {
54    view.expanded = !view.expanded; redraw();
55    await remember('expanded', view.expanded);
56  }
57  async function choosePromptDisplay(value) {
58    if (!['launcher', 'compact', 'hidden'].includes(value)) return;
59    view.promptDisplay = value; redraw();
60    await remember('promptDisplay', value);
61  }
62  async function chooseLauncherPlacement(value) {
63    if (!['all', 'band', 'mode', 'hint'].includes(value)) return;
64    view.launcherPlacement = value; redraw();
65    await remember('launcherPlacement', value);
66  }
67  async function rememberBackup(result, pair) {
68    const receipt = { backup: result.Backup, source: pair?.source || '', target: pair?.target || '',
69      at: new Date(await api.now()).toISOString(), status: result.Ok ? 'complete' : 'prepared',
70      message: result.Ok ? describeResult(result) : result.Error || 'Sync interrupted; inspect this backup before retrying.' };
71    view.receipts = [receipt, ...view.receipts.filter(r => r.backup !== receipt.backup)].slice(0, 8);
72    await remember('receipts', view.receipts);
73  }
74  function selectedPair() {
75    if (!PROFILE_ID.test(view.source)) throw new Error('Confirm which account is open in Sync settings first.');
76    if (!PROFILE_ID.test(view.target)) throw new Error('Choose an inactive destination account first.');
77    if (view.source === view.target) throw new Error('Source and destination must be different.');
78    if (!view.profiles.some(p => p.Id === view.source) || !view.profiles.some(p => p.Id === view.target)) {
79      throw new Error('A selected profile is no longer available. Refresh profiles.');
80    }
81    return { source: view.source, target: view.target };
82  }
83  async function bridge(action, pair, keepLease = false) {
84    if (api.windows === false) throw new Error('Account history sync runs on native Windows sessions.');
85    const argv = ['powershell.exe', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
86      '-File', `${api.root}/scripts/HistorySync-Bridge.ps1`, '-Action', action];
87    if (configOverride) argv.push('-ConfigPath', configOverride);
88    if (pair) argv.push('-SourceProfile', pair.source, '-TargetProfile', pair.target);
89    if (action !== 'Release') argv.push('-SessionId', owner);
90    if (['Arm', 'Sync', 'Release'].includes(action)) argv.push('-OwnerSession', owner);
91    if (keepLease) argv.push('-KeepLease');
92    if (action === 'Plan') argv.push('-PreviewFile');
93    const processResult = await api.processRun(argv, { timeoutMs: 90_000 });
94    let result;
95    if (processResult.isStdoutTruncated) throw new Error('History helper output was truncated by Claude. Reload the updated History sync plugin and try again.');
96    try { result = JSON.parse(processResult.stdout.trim()); }
97    catch { throw new Error(`History helper returned invalid output (exit ${processResult.exitCode}). ${processResult.stderr?.slice(0, 500) || ''}`); }
98    if (processResult.exitCode === 0 && result.Ok && result.PreviewPath) {
99      if (action !== 'Plan' || result.Action !== 'Plan' || !Number.isInteger(result.PreviewBytes) || result.PreviewBytes < 1 || result.PreviewBytes > 4 * 1024 * 1024) {
100        throw new Error('History helper returned invalid preview-file metadata.');
101      }
102      try { result = JSON.parse(await api.readText(result.PreviewPath)); }
103      catch (error) { throw new Error(`Could not read the history preview: ${error.message}`); }
104      if (result.Action !== 'Plan' || !Array.isArray(result.Rows) || !Array.isArray(result.Report)) {
105        throw new Error('History helper returned an invalid preview file.');
106      }
107    }
108    if (result.Backup) { view.backup = result.Backup; await rememberBackup({ ...result, Ok: result.Ok && processResult.exitCode === 0 }, pair); }
109    if (result.ConfigPath) view.configPath = result.ConfigPath;
110    if (processResult.exitCode !== 0 || !result.Ok) throw new Error(result.Error || processResult.stderr || 'History helper failed.');
111    return result;
112  }
113  async function release() {
114    if (!owner) return;
115    try { await bridge('Release'); }
116    catch (error) { view.error = `Paused; controller lease expires within three minutes. ${error.message}`; }
117  }
118  async function run(label, work) {
119    if (ended || running) return null;
120    view.busy = true; view.error = ''; view.status = label; redraw();
121    // Promise.resolve defers work until running is assigned, including synchronous failures.
122    running = Promise.resolve().then(work).catch(async error => {
123      view.enabled = false;
124      view.error = error.message;
125      view.status = 'Sync paused after an error.';
126      await release();
127      return null;
128    }).finally(() => { running = null; view.busy = false; redraw(); });
129    return running;
130  }
131  async function sync(automatic = false) {
132    if (automatic && !view.enabled) return null;
133    return run('Checking saved history…', async () => {
134      const pair = selectedPair();
135      const result = await bridge('Sync', pair, view.enabled);
136      view.status = describeResult(result);
137      const at = new Date(await api.now()).toISOString();
138      view.lastSync = new Date(at).toLocaleTimeString();
139      view.lastResult = { source: pair.source, target: pair.target, at, message: view.status, backup: result.Backup || '' };
140      await remember('lastResult', view.lastResult);
141      if (result.Backup) api.log(`History backup: ${result.Backup}`);
142      return result;
143    });
144  }
145  async function pause() {
146    revision += 1;
147    view.enabled = false;
148    debounce?.cancel(); debounce = null;
149    redraw();
150    if (running) await running;
151    view.enabled = false;
152    await release();
153    view.status = 'Auto-sync paused.';
154    redraw();
155  }
156  async function refresh() {
157    return run('Finding local profiles…', async () => {
158      const result = await bridge('Profiles');
159      view.profiles = result.Profiles || [];
160      view.sourceCandidates = result.SessionProfiles || [];
161      const previousSource = view.source;
162      const previousTarget = view.target;
163      const wasEnabled = view.enabled;
164      if (view.source && !view.profiles.some(p => p.Id === view.source)) view.source = '';
165      if (result.CurrentProfile) view.source = result.CurrentProfile;
166      else if (view.sourceCandidates.length && !view.sourceCandidates.includes(view.source)) view.source = '';
167      if (previousSource !== view.source) {
168        revision += 1; view.enabled = false;
169        debounce?.cancel(); debounce = null;
170        if (previousSource) await release();
171      }
172      if (view.target && !view.profiles.some(p => p.Id === view.target)) { view.target = ''; view.enabled = false; }
173      if (view.target === view.source) view.target = '';
174      if (previousSource === view.source && previousTarget !== view.target && wasEnabled) await release();
175      if (previousSource !== view.source || previousTarget !== view.target) clearPreview();
176      view.status = view.source ? 'This account → inactive destination. Choose a destination and sync.' :
177        view.sourceCandidates.length > 1 ? 'This session exists in several accounts. Confirm the open account in Sync settings.' :
178        'No account folder identifies this session yet. Confirm the open account in Sync settings, or refresh after a turn.';
179      return result;
180    });
181  }
182  async function choose(source, target) {
183    if (view.source && source !== view.source) throw new Error('Source is this session’s account. Switch accounts and open a fresh session to reverse the direction.');
184    if (source && (!view.profiles.some(p => p.Id === source) || (view.sourceCandidates.length && !view.sourceCandidates.includes(source)))) {
185      throw new Error('The chosen source does not contain this session. Refresh profiles.');
186    }
187    // Confirming an ambiguous source is session-local, never a saved login assumption.
188    await pause();
189    if (view.source && source !== view.source) throw new Error('The current source changed while waiting. Choose the destination again.');
190    view.source = source; view.target = target;
191    clearPreview();
192    await remember('destination', target);
193    view.status = source ? 'This account → selected destination. Destination must be inactive.' : 'Destination selected. Confirm the open account in Sync settings.';
194    redraw();
195  }
196  async function preview() {
197    return run('Building a read-only preview…', async () => {
198      const result = await bridge('Plan', selectedPair());
199      view.report = result.Report || [];
200      view.previewRows = Array.isArray(result.Rows) ? result.Rows : [];
201      view.previewPage = 0; view.selectedPreview = '';
202      view.status = describeResult(result);
203      view.preview = { source: view.source, target: view.target, message: view.status,
204        writes: result.Writes ?? 0, reportTotal: result.ReportTotal ?? view.report.length,
205        reportTruncated: result.ReportTruncated === true, rowsTotal: result.RowsTotal ?? view.previewRows.length,
206        rowsTruncated: result.RowsTruncated === true, at: new Date(await api.now()).toISOString() };
207      return result;
208    });
209  }
210  async function start() {
211    const startingRevision = revision;
212    const result = await run('Starting auto-sync…', async () => {
213      const pair = selectedPair();
214      await bridge('Arm', pair);
215      if (ended || startingRevision !== revision) { await release(); return null; }
216      view.enabled = true;
217      view.status = 'Auto-sync active: source → destination every 30 seconds.';
218      return true;
219    });
220    if (result && view.enabled) await sync(true);
221  }
222  function stop() {
223    revision += 1;
224    ended = true; view.enabled = false;
225    interval?.cancel(); debounce?.cancel();
226  }
227  async function initialize(adapter) {
228    api = adapter;
229    if (api.windows === false) {
230      view.error = 'Account history sync runs on native Windows sessions.';
231      return;
232    }
233    owner = await api.sessionId();
234    configOverride = (await api.envGet('ACCOUNT_HISTORY_SYNC_CONFIG')) || '';
235    view.source = ''; view.sourceCandidates = [];
236    const saved = await api.storeGet('destination');
237    view.target = typeof saved === 'string' ? saved : '';
238    view.expanded = (await api.storeGet('expanded')) === true;
239    const promptDisplay = await api.storeGet('promptDisplay');
240    view.promptDisplay = ['launcher', 'compact', 'hidden'].includes(promptDisplay) ? promptDisplay : 'launcher';
241    const placement = await api.storeGet('launcherPlacement');
242    view.launcherPlacement = ['all', 'band', 'mode', 'hint'].includes(placement) ? placement : 'all';
243    const receipts = await api.storeGet('receipts');
244    view.receipts = Array.isArray(receipts) ? receipts.filter(r => r && typeof r.backup === 'string' && r.backup && typeof r.message === 'string' &&
245      PROFILE_ID.test(r.source) && PROFILE_ID.test(r.target) && !Number.isNaN(Date.parse(r.at)) &&
246      ['complete', 'prepared'].includes(r.status)).slice(0, 8) : [];
247    view.backup = view.receipts[0]?.backup || '';
248    const lastResult = await api.storeGet('lastResult');
249    view.lastResult = lastResult && PROFILE_ID.test(lastResult.source) && PROFILE_ID.test(lastResult.target) &&
250      typeof lastResult.message === 'string' && !Number.isNaN(Date.parse(lastResult.at)) ? lastResult : null;
251    view.lastSync = view.lastResult ? new Date(view.lastResult.at).toLocaleTimeString() : '';
252    // Never persist auto-enable across sessions, login changes or hot reloads.
253    await release();
254    await refresh();
255    interval = api.every(30_000, async () => { if (ended) return; if (view.enabled) await sync(true); else if (!view.source) await refresh(); });
256  }
257  function afterTurn() {
258    if (ended) return;
259    if (!view.enabled && view.source) return;
260    debounce?.cancel();
261    debounce = api.after(1500, async () => { if (ended) return; if (view.enabled) await sync(true); else if (!view.source) await refresh(); });
262  }
263  async function reopen() {
264    if (!ended) return;
265    if (running) await running;
266    await release();
267    ended = false;
268    view.enabled = false; view.error = '';
269    interval = null; debounce = null;
270    await initialize(api);
271    view.status = `Session changed; auto-sync paused. ${view.status}`;
272    redraw();
273  }
274  function resolveSelector(selector) {
275    const matches = view.profiles.filter(p => p.Id === selector || p.Email?.toLowerCase() === selector.toLowerCase());
276    if (matches.length !== 1) throw new Error('Profile selector is unknown or ambiguous. Use a full profile ID from /history-sync profiles.');
277    return matches[0].Id;
278  }
279  function statusText() {
280    return `${view.enabled ? 'Auto-sync active' : 'Auto-sync paused'}; ${view.source || '(confirm open account)'} → ${view.target || '(choose destination)'}. ${view.status}${view.error ? ` ${view.error}` : ''}`;
281  }
282  return { view, initialize, refresh, choose, preview, start, pause, sync, stop, afterTurn, reopen, resolveSelector, statusText,
283    showSection, toggleDetails, choosePromptDisplay, chooseLauncherPlacement, copyText,
284    filterPreview, filterPreviewChanges, searchPreview, pagePreview, selectPreview };
285}
286
hooks/ui.mjs 269 lines
1export function accountLabel(view, id, empty = 'Choose destination') {
2  if (!id) return empty;
3  const profile = view.profiles.find(p => p.Id === id);
4  const [account, org] = id.split('\\');
5  const name = profile?.Email || (profile?.Label && profile.Label !== account ? profile.Label : `Account ${account.slice(0, 8)}`);
6  // Organizations can share an email; keep them distinguishable in every picker.
7  return `${name} · ${org?.slice(0, 8) || ''}`;
8}
9
10function mode(view) {
11  if (view.error) return 'Error · auto-sync paused';
12  if (view.busy) return 'Working…';
13  return view.enabled ? 'Auto · every 30s' : 'Paused';
14}
15
16function samePair(view, result) {
17  return result && result.source === view.source && result.target === view.target;
18}
19
20function time(at, full = false) {
21  return full ? new Date(at).toLocaleString() : new Date(at).toLocaleTimeString();
22}
23
24function action(Button, controller, key, label, work, needsPair = false) {
25  const v = controller.view;
26  const ready = !needsPair || Boolean(v.source && v.target && v.source !== v.target);
27  return Button({ key, label, dimColor: v.busy || !ready, onPress: async () => {
28    await controller.reopen();
29    if (!v.busy && (!needsPair || (v.source && v.target && v.source !== v.target))) await work();
30  } });
31}
32
33function automatic(Button, controller) {
34  const v = controller.view;
35  return Button({ key: 'auto', label: v.enabled ? 'Pause auto-sync' : 'Start auto-sync',
36    dimColor: !v.enabled && (v.busy || !v.source || !v.target || v.source === v.target), onPress: async () => {
37      await controller.reopen();
38      if (v.enabled) await controller.pause();
39      else if (!v.busy && v.source && v.target && v.source !== v.target) await controller.start();
40    } });
41}
42
43export function launcherVisible(view, site) {
44  return view.promptDisplay !== 'hidden' && (view.launcherPlacement === 'all' || view.launcherPlacement === site);
45}
46
47export function renderLauncher({ Box, Button }, controller, openSettings, site) {
48  const v = controller.view;
49  const location = v.launcherPlacement === 'all' ? ` · ${ {band:'Prompt', mode:'Mode', hint:'Hint'}[site] }` : '';
50  const status = v.error ? ' · needs attention' : v.enabled ? ' · Auto' : '';
51  return Box({ flexDirection: 'row', flexWrap: 'wrap', gap: 1, children: [
52    Button({ key: site === 'band' ? 'settings' : `settings-${site}`, label: `History sync${location}${status}`,
53      ...(site === 'band' ? {hotkey: 's'} : {}), onPress: openSettings }),
54    ...(v.enabled ? [automatic(Button, controller)] : []),
55  ] });
56}
57
58export function renderBand({ Box, Text, Button }, controller, openSettings) {
59  const v = controller.view;
60  if (v.promptDisplay === 'hidden') return null;
61  if (v.promptDisplay !== 'compact') return renderLauncher({ Box, Button }, controller, openSettings, 'band');
62  const direction = `${accountLabel(v, v.source, 'Confirm this account')} → ${accountLabel(v, v.target)}`;
63  const last = samePair(v, v.lastResult) ? ` · Last ${time(v.lastResult.at)}` : '';
64  return Box({ flexDirection: 'column', children: [
65    Box({ flexDirection: 'row', flexWrap: 'wrap', gap: 1, children: [
66      Text({ bold: true, children: `History sync · ${mode(v)}` }),
67      action(Button, controller, 'sync', 'Sync now', () => controller.sync(), true),
68      ...(v.enabled ? [automatic(Button, controller)] : []),
69      Button({ key: 'settings', label: 'Sync settings', hotkey: 's', onPress: openSettings }),
70      Button({ key: 'details', label: v.expanded ? 'Less' : 'Details', onPress: () => controller.toggleDetails() }),
71    ] }),
72    Text({ dimColor: true, children: `${direction}${last}` }),
73    ...(v.error ? [Text({ color: 'red', children: v.error })] : []),
74    ...(v.busy ? [Text({ children: v.status })] : []),
75    ...(v.expanded ? [
76      Text({ children: samePair(v, v.lastResult) ? v.lastResult.message : v.source && v.target ? 'Ready to preview or sync this direction.' : 'Choose an inactive destination in Sync settings.' }),
77      ...(samePair(v, v.lastResult) && v.lastResult.backup ? [Text({ dimColor: true, children: 'Verified backup saved · details in Backups' })] : []),
78      Text({ dimColor: true, children: 'Source stays untouched. Pause before switching accounts.' }),
79    ] : []),
80  ] });
81}
82
83export function profilesText(view) {
84  return view.profiles.map(p => `${accountLabel(view, p.Id)} | ${p.Id} | ${p.Sessions} sessions`).join('\n');
85}
86
87export function filteredPreviewRows(view) {
88  const search = view.previewSearch.trim().toLocaleLowerCase();
89  return view.previewRows.filter(r =>
90    (view.previewFilter === 'all' || (r.After && (view.previewFilter === 'archived' ? r.After.Archived : !r.After.Archived))) &&
91    (view.previewChanges === 'all' || (view.previewChanges === 'changes' ? ['Add','Update'].includes(r.Action) : ['Conflict','Skipped'].includes(r.Action))) &&
92    (!search || [r.Title,r.Before?.Title,r.After?.Title].some(t => t?.toLocaleLowerCase().includes(search)))
93  ).sort((a,b) => a.Title.localeCompare(b.Title) || a.File.localeCompare(b.File));
94}
95
96function archiveState(state) { return state ? state.Archived ? 'Archived' : 'Active' : 'Not present'; }
97
98export function previewTableText(rows) {
99  const cell = text => String(text ?? '').replace(/[\t\r\n]+/g,' ');
100  return [['Session','Change','Before title','Before state','After title','After state','Reason','Session file'],
101    ...rows.map(r => [r.Title,r.Action,r.Before?.Title,archiveState(r.Before),r.After?.Title,archiveState(r.After),r.Detail,r.File]),
102  ].map(row => row.map(cell).join('\t')).join('\n');
103}
104
105export function previewText(view) {
106  const p = view.preview;
107  if (!p) return '';
108  return ['Preview only — no history writes performed.',
109    `From: ${accountLabel(view, p.source)} | ${p.source}`,
110    `To: ${accountLabel(view, p.target)} | ${p.target}`, time(p.at, true), p.message,
111    `Planned operations: ${p.writes}`,
112    ...(view.previewRows.length ? [previewTableText(view.previewRows)] : view.report.map(r => `${r.Action}: ${r.File}\n${r.Detail}`)),
113    ...(p.reportTruncated ? [`Report limited to ${view.report.length} of ${p.reportTotal} entries.`] : []),
114    ...(p.rowsTruncated ? [`Comparison limited to ${view.previewRows.length} of ${p.rowsTotal} sessions.`] : []),
115  ].join('\n');
116}
117
118export function diagnosticsText(view) {
119  return ['History sync diagnostics', `From: ${accountLabel(view, view.source, 'Unconfirmed')} | ${view.source}`,
120    `To: ${accountLabel(view, view.target)} | ${view.target}`, mode(view), view.status,
121    ...(view.error ? [`Error: ${view.error}`] : []), `Config: ${view.configPath || '(default)'}`,
122    profilesText(view), ...(view.preview ? [previewText(view)] : []),
123    ...(view.backup ? [`Latest backup: ${view.backup}`] : []),
124  ].join('\n');
125}
126
127function renderPreviewTable({Box,Text,Button,Select,Input}, controller, copy) {
128  const v=controller.view;
129  const filtered=filteredPreviewRows(v);
130  const pageCount=Math.max(1,Math.ceil(filtered.length/15));
131  const page=Math.min(v.previewPage,pageCount-1);
132  const pageRows=filtered.slice(page*15,(page+1)*15);
133  const selected=v.previewRows.find(r=>r.File===v.selectedPreview);
134  const widths=['36%','23%','23%','18%'];
135  const cell=(content,index)=>Box({width:widths[index],flexShrink:0,flexDirection:'column',paddingX:1,children:content});
136  const stateCell=(state,row)=>[Text({bold:true,children:archiveState(state)}),
137    ...(state && state.Title!==row.Title ? [Text({dimColor:true,children:state.Title.slice(0,1000)})] : [])];
138  const filters=Box({flexDirection:'row',flexWrap:'wrap',gap:1,children:['all','active','archived'].map(key=>Button({
139    key:`filter-${key}`,label:`${v.previewFilter===key?'› ':''}${{all:'All',active:'Active',archived:'Archived'}[key]}`,
140    dimColor:v.previewFilter!==key,onPress:()=>controller.filterPreview(key),
141  }))});
142  const search=Input ? [Input({key:'preview-search',label:'Search titles',placeholder:'Session title…',value:v.previewSearch,
143    onInput:value=>controller.searchPreview(value),onSubmit:value=>controller.searchPreview(value)})] : [];
144  return [
145    Text({bold:true,children:'Destination before → after'}),
146    Text({dimColor:true,children:'Active and Archived filter the planned destination state. All also includes sessions left absent. Titles come from the source when available.'}),
147    filters,
148    Select({key:'preview-changes',label:'Changes',value:v.previewChanges,
149      options:[{value:'all',label:'All sessions'},{value:'changes',label:'Additions and updates'},{value:'issues',label:'Conflicts and skipped'}],
150      onSelect:value=>controller.filterPreviewChanges(value)}),
151    ...search,
152    copy('copy-filtered','Copy filtered table',()=>previewTableText(filtered)),
153    Text({dimColor:true,children:`${filtered.length} of ${v.previewRows.length} sessions · page ${page+1} of ${pageCount}`}),
154    ...(v.preview.rowsTruncated ? [Text({dimColor:true,children:`Comparison contains the first ${v.previewRows.length} of ${v.preview.rowsTotal} sessions.`})] : []),
155    Box({flexDirection:'column',borderStyle:'single',children:[
156      Box({flexDirection:'row',children:['Session','Before','After','Change'].map((label,i)=>cell([Text({bold:true,children:label})],i))}),
157      ...pageRows.map(r=>Box({key:`preview-row-${r.File}`,flexDirection:'row',paddingY:1,children:[
158        cell([Text({children:r.Title.slice(0,1000)})],0),cell(stateCell(r.Before,r),1),cell(stateCell(r.After,r),2),
159        cell([Text({children:r.Action}),Button({key:`details-${r.File}`,label:'Details',onPress:()=>controller.selectPreview(r.File)})],3),
160      ]})),
161      ...(!pageRows.length?[Text({dimColor:true,children:'No sessions match these filters.'})]:[]),
162    ]}),
163    Box({flexDirection:'row',gap:1,children:[
164      Button({key:'preview-prev',label:'Previous',dimColor:page===0,onPress:()=>{if(page>0)controller.pagePreview(page-1);}}),
165      Button({key:'preview-next',label:'Next',dimColor:page>=pageCount-1,onPress:()=>{if(page<pageCount-1)controller.pagePreview(page+1);}}),
166    ]}),
167    ...(selected?[
168      Text({bold:true,children:selected.Title.slice(0,1000)}),
169      Text({children:`${selected.Action}: ${selected.Detail}`}),
170      Text({children:`Before: ${selected.Before?.Title||'Not present'} · ${archiveState(selected.Before)}\nAfter: ${selected.After?.Title||'Not present'} · ${archiveState(selected.After)}`}),
171      ...(selected.Before?.ParentSessionId||selected.After?.ParentSessionId||selected.Before?.LineageDetached||selected.After?.LineageDetached ? [
172        Text({children:`Parent before: ${selected.Before?.ParentSessionId||'None'}\nParent after: ${selected.After?.ParentSessionId||'None'}`}),
173        Text({dimColor:true,children:`Side session after: ${selected.After?.SideSession?'Yes':'No'} · ${selected.After?.LineageDetached?'Detached':'Attached'}`}),
174      ]:[]),
175      Text({dimColor:true,children:`Changed fields: ${selected.ChangedFields?.join(', ')||'None'}\nSession file: ${selected.File}`}),
176    ]:[]),
177  ];
178}
179
180export function renderPane({ Box, Text, Button, Select, Input }, controller, writer = async () => ({isCopied:false,reason:'no-clipboard'})) {
181  const v = controller.view;
182  const row = children => Box({ flexDirection: 'row', flexWrap: 'wrap', gap: 1, children });
183  const heading = text => Text({ bold: true, children: text });
184  const note = text => Text({ dimColor: true, children: text });
185  const go = section => controller.showSection(section);
186  const copy = (key, label, getText) => Button({key, label, onPress: press => controller.copyText(getText(), writer, press?.surface)});
187  const section = v.section || 'accounts';
188  let content;
189  if (section === 'accounts') {
190    const sourceChoices = v.profiles.filter(p => !v.sourceCandidates.length || v.sourceCandidates.includes(p.Id));
191    content = [
192      heading('Accounts'),
193      Text({ children: `From · ${accountLabel(v, v.source, 'Confirm the account open in Claude')}` }),
194      ...(v.source ? [note('This session’s account is the source.')] : [
195        Text({ children: v.status }),
196        Select({ key: 'source-confirmation', label: 'Account open now', value: '',
197          options: [{ value: '', label: 'Choose the open account…' }, ...sourceChoices.map(p => ({ value: p.Id, label: accountLabel(v, p.Id) }))],
198          onSelect: async value => { await controller.reopen(); if (!v.busy && value) await controller.choose(value, v.target === value ? '' : v.target); } }),
199      ]),
200      Select({ key: 'target', label: 'To · inactive account', value: v.target,
201        options: [{ value: '', label: 'Choose destination…' }, ...v.profiles.filter(p => p.Id !== v.source).map(p => ({
202          value: p.Id, label: `${accountLabel(v, p.Id)} · ${p.Sessions} sessions`,
203        }))],
204        onSelect: async value => { await controller.reopen(); if (!v.busy) await controller.choose(v.source, value); } }),
205      note('Copy saved Code history from this account into the destination. Keep the destination account inactive.'),
206      copy('copy-profiles', 'Copy profile list', () => profilesText(v)),
207      row([action(Button, controller, 'refresh', 'Refresh accounts', () => controller.refresh()),
208        action(Button, controller, 'continue', 'Continue to Sync', () => go('sync'), true)]),
209      heading('Prompt controls'),
210      Select({ key: 'prompt-display', label: 'Show near the prompt', value: v.promptDisplay,
211        options: [{ value: 'launcher', label: 'Menu button only' }, { value: 'compact', label: 'Status and quick controls' },
212          { value: 'hidden', label: 'Hide — open with /history-sync' }],
213        onSelect: value => controller.choosePromptDisplay(value) }),
214      Select({ key: 'launcher-placement', label: 'Launcher placement', value: v.launcherPlacement,
215        options: [{ value: 'all', label: 'Compare all three locations' }, { value: 'band', label: 'Above the prompt' },
216          { value: 'mode', label: 'Session mode area' }, { value: 'hint', label: 'Prompt hint area' }],
217        onSelect: value => controller.chooseLauncherPlacement(value) }),
218      note('Compare shows Prompt, Mode, and Hint labels. A location appears only if this Desktop build asks the mod to draw it. /history-sync always opens the pane.'),
219      note('This launcher appears in the main conversation only. Claude decides where the settings pane opens.'),
220    ];
221  } else if (section === 'sync') {
222    content = [
223      heading('Sync'),
224      Text({ children: `${accountLabel(v, v.source, 'Confirm this account')} → ${accountLabel(v, v.target)}` }),
225      ...(!v.source || !v.target ? [note('Choose accounts before previewing or syncing.'),
226        Button({ key: 'choose-accounts', label: 'Choose accounts', onPress: () => go('accounts') })] : []),
227      row([action(Button, controller, 'preview', 'Preview', () => controller.preview(), true),
228        action(Button, controller, 'sync', 'Sync now', () => controller.sync(), true)]),
229      heading('Automatic sync'),
230      Text({ children: mode(v) }),
231      note('Checks saved history every 30 seconds and shortly after a turn finishes. Starts paused in each session.'),
232      row([automatic(Button, controller)]),
233      note('Pause before switching accounts. Changing the destination pauses automatic sync.'),
234      heading('Results'),
235      Text({ children: v.status }),
236      ...(samePair(v, v.lastResult) ? [Text({ children: `${v.lastResult.message}\nLast sync: ${time(v.lastResult.at, true)}` })] : [note('No completed sync for this direction yet.')]),
237      ...(v.preview ? [Text({ children: v.preview.message }),
238        copy('copy-preview', 'Copy preview', () => previewText(v)),
239        ...(v.preview.reportTruncated ? [note(`Showing ${v.report.length} of ${v.preview.reportTotal} report entries.`)] : []),
240        ...(v.previewRows.length ? renderPreviewTable({Box,Text,Button,Select,Input},controller,copy) :
241          v.report.length ? [Text({children:v.report.map(r=>`${r.Action}: ${r.File}\n${r.Detail}`).join('\n').slice(0,9500)})] : [note('No sessions in this preview.')])] : []),
242    ];
243  } else {
244    content = [
245      heading('Backups'),
246      note('Each modifying sync backs up the destination cards and archive index. Recent backups include their original direction.'),
247      ...(v.receipts.length ? v.receipts.flatMap((r, index) => [
248        heading(`${index === 0 ? 'Latest backup' : 'Backup'} · ${r.status === 'prepared' ? 'Interrupted — inspect before retrying' : 'Complete'}`),
249        Text({ children: `${accountLabel(v, r.source)} → ${accountLabel(v, r.target)}\n${time(r.at, true)}\n${r.message}` }),
250        Text({ children: r.backup }),
251        copy(`copy-backup-${index}`, 'Copy backup path', () => r.backup),
252      ]) : [note('No backup recorded yet. A preview or sync with no changes creates no backup.')]),
253      heading('Restore'),
254      note('Fully exit Claude before restoring a backup with the standalone Undo command. Review the restore with -WhatIf first.'),
255    ];
256  }
257  return Box({ flexDirection: 'column', gap: 1, padding: 1, children: [
258    heading('History sync'),
259    copy('copy-diagnostics', 'Copy diagnostics', () => diagnosticsText(v)),
260    row(['accounts', 'sync', 'backups'].map((key, i) => Button({ key: `nav-${key}`,
261      label: `${section === key ? '› ' : ''}${['Accounts', 'Sync', 'Backups'][i]}`, hotkey: ['a', 's', 'b'][i],
262      dimColor: section !== key, onPress: () => go(key) }))),
263    ...content,
264    ...(v.error ? [Text({ color: 'red', children: v.error })] : []),
265    ...(v.notice ? [note(v.notice)] : []),
266    ...(v.copyStatus ? [note(v.copyStatus)] : []),
267  ] });
268}
269