The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Guide multi-machine onboarding and refresh branch search (#292)
Dee02453b8a7a14
diff --git a/.github/assets/machines/README.md b/.github/assets/machines/README.mdindex e586a7ea8..8e8ff4f69 100644--- a/.github/assets/machines/README.md+++ b/.github/assets/machines/README.md@@ -20,3 +20,14 @@ node tool/check_machines_coverage.mjsThis gate covers the four new files: the panel, SVG widget, resource model, and toolbar notification controller. It does not assert whole-application coverage or replace testing on two physical computers.For a disposable interactive review, build `tool/machines_preview.dart` and launch its executable with `FLUTTER_TEST=1`. Use `MACHINES_PREVIEW_EMPTY=1` for the first-computer experience, or `MACHINES_PREVIEW_GUEST=1` for sign-in. F6 simulates a newly discovered Mac mini; its fixture password is `123456`. F7 simulates a model becoming ready; F8 adds a model to the catalog. Account edits, links, password operations, model operations, and resource values in this entrypoint remain in memory. Copy and Download use the actual system clipboard/browser. Restore the regular build afterward with `flutter build macos --debug --target lib/main.dart`.++The three-step toolbar onboarding has a separate review entrypoint:++```sh+flutter build macos --debug --target tool/onboarding_preview.dart+FLUTTER_TEST=1 build/macos/Build/Products/Debug/Harness.app/Contents/MacOS/Harness+```++The footer switches between First harness, Another computer, Local AI, and Receiving computer. These controls reset disposable fixtures; they are not part of the production UI. Click the toolbar icon with the blue dot to see its invitation. Red counts continue to represent real unread work or newly available machines/models. Opening a panel acknowledges its dot without completing the step; dismissing Machines allows users with one computer to explore Models. Completion observes usable harnesses, remote access, and a harness using an own-grid model. Onboarding preferences are stored per account on this device, not synchronized between computers.++Run `flutter test test/workspace_onboarding_test.dart test/toolbar_onboarding_test.dart` for preference isolation, progress, setup, connection retry, offline recovery, and model-discovery checks. Restore the normal `lib/main.dart` build after the interactive review.diff --git a/.github/assets/machines/branch-search.png b/.github/assets/machines/branch-search.pngnew file mode 100644index 000000000..75e4dec8dBinary files /dev/null and b/.github/assets/machines/branch-search.png differdiff --git a/.github/assets/machines/onboarding-another-computer.png b/.github/assets/machines/onboarding-another-computer.pngnew file mode 100644index 000000000..15a99a3dcBinary files /dev/null and b/.github/assets/machines/onboarding-another-computer.png differdiff --git a/.github/assets/machines/onboarding-first-harness.png b/.github/assets/machines/onboarding-first-harness.pngnew file mode 100644index 000000000..391c1ef27Binary files /dev/null and b/.github/assets/machines/onboarding-first-harness.png differdiff --git a/.github/assets/machines/onboarding-local-models.png b/.github/assets/machines/onboarding-local-models.pngnew file mode 100644index 000000000..8365d1eabBinary files /dev/null and b/.github/assets/machines/onboarding-local-models.png differdiff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 65b5607fc..6cdcb61eb 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -567,7 +567,7 @@ describe('BackendSocket outbound queue', () => {await socket.stop()})- it('returns Git branch choices only to the requesting encrypted connection', async () => {+ it.each([false, true])('returns refreshed=%s Git branch choices only to the requesting encrypted connection', async refresh => {const preview = { isGit: true, root: '/remote/workspace', branch: 'main', branches: [{ ref: 'refs/heads/private-branch', name: 'private-branch', remote: false }] }const read = vi.spyOn(gitProject, 'readGitProject').mockResolvedValue(preview)const socket = new BackendSocket('token')@@ -575,7 +575,7 @@ describe('BackendSocket outbound queue', () => {const ws = wsMock.instances[0]ws.open()vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'git_project_info', payload: {- requestId: 'preview-1', path: '/remote/workspace',+ requestId: 'preview-1', path: '/remote/workspace', refresh,} })vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({@@ -585,7 +585,7 @@ describe('BackendSocket outbound queue', () => {type: 'git_project_info', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-request' } },} })await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('viewer-a', 'git_project_info_result', 'preview-1', preview))- expect(read).toHaveBeenCalledWith('/remote/workspace')+ expect(read).toHaveBeenCalledWith('/remote/workspace', { refresh })expect(parseSent(ws)).toContainEqual(expect.objectContaining({ targetConnId: 'viewer-a', frame: {type: 'git_project_info_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },} }))@@ -637,7 +637,7 @@ describe('BackendSocket outbound queue', () => {type: 'git_project_info', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-request' } },} })await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('viewer-a', 'git_project_info_result', 'git-error', { error: 'UNAVAILABLE' }))- expect(read).toHaveBeenCalledWith('')+ expect(read).toHaveBeenCalledWith('', { refresh: false })await socket.stop()})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 6fc719c59..3bdad2aa1 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -2435,7 +2435,7 @@ export class BackendSocket {case 'git_project_info': {const path = typeof payload.path === 'string' ? payload.path : ''- void readGitProject(path)+ void readGitProject(path, { refresh: payload.refresh === true }).then(result => reply(type, requestId, result)).catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))returndiff --git a/cli/src/lib/gitProject.spec.ts b/cli/src/lib/gitProject.spec.tsindex 34d0b255f..4655d86e6 100644--- a/cli/src/lib/gitProject.spec.ts+++ b/cli/src/lib/gitProject.spec.ts@@ -60,6 +60,56 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {expect(await readGitProject('relative/path')).toEqual({ error: 'INVALID_PATH' })})+ it('discovers a newly pushed branch without fetching objects, then fetches only on Start', async () => {+ const remote = join(root, 'remote.git')+ const clone = join(root, 'other computer')+ await git('clone', '--bare', repo, remote)+ await git('clone', '--no-local', '--single-branch', '--branch', 'main', remote, clone)+ const there = async (...args: string[]) => (await exec('git', ['-C', clone, ...args])).stdout.trim()+ await git('remote', 'add', 'origin', remote)+ await git('switch', '-c', 'feat/toolbar-onboarding')+ await writeFile(join(repo, 'src', 'value'), 'new remote work')+ await git('commit', '-am', 'new work')+ await git('push', 'origin', 'feat/toolbar-onboarding')+ await writeFile(join(clone, 'src', 'value'), 'unsaved local work')+ const refs = await there('show-ref')+ expect((await readGitProject(clone) as any).branches.map((b: any) => b.name)).not.toContain('origin/feat/toolbar-onboarding')+ const info = await readGitProject(clone, { refresh: true })+ expect(info).toMatchObject({ refreshed: true, branch: 'main', branches: expect.arrayContaining([+ { ref: 'refs/remotes/origin/feat/toolbar-onboarding', name: 'origin/feat/toolbar-onboarding', remote: true },+ ]) })+ expect(await there('show-ref')).toBe(refs)+ expect(await readFile(join(clone, 'src', 'value'), 'utf8')).toBe('unsaved local work')+ const path = await prepare('worktree', 'refs/remotes/origin/feat/toolbar-onboarding', clone,+ { branchName: 'feat/toolbar-onboarding' })+ expect(await readFile(join(path, 'src', 'value'), 'utf8')).toBe('new remote work')+ expect(await there('branch', '--show-current')).toBe('main')+ })++ it('keeps saved branches from unreachable remotes and refreshes the others', async () => {+ const remote = join(root, 'remote.git')+ await git('clone', '--bare', repo, remote)+ await git('remote', 'add', 'origin', join(root, 'missing.git'))+ await git('remote', 'add', 'upstream', remote)+ const info = await readGitProject(repo, { refresh: true })+ expect(info).toMatchObject({ refreshed: false, branches: expect.arrayContaining([+ { ref: 'refs/remotes/origin/feature', name: 'origin/feature', remote: true },+ { ref: 'refs/remotes/upstream/main', name: 'upstream/main', remote: true },+ ]) })+ expect(await git('branch', '--show-current')).toBe('main')+ })++ it('removes deleted remote choices after a successful lookup without changing saved refs', async () => {+ const remote = join(root, 'remote.git')+ await git('clone', '--bare', repo, remote)+ await git('remote', 'add', 'origin', remote)+ await exec('git', ['-C', remote, 'branch', '-D', 'feature'])+ const info = await readGitProject(repo, { refresh: true }) as { branches: Array<{ name: string }> }+ expect(info.branches.map(b => b.name)).toContain('feature')+ expect(info.branches.map(b => b.name)).not.toContain('origin/feature')+ expect(await git('show-ref', '--verify', 'refs/remotes/origin/feature')).toBeTruthy()+ })+it('starts concurrent worktrees on distinct branches from the chosen ref and preserves dirty source files', async () => {await writeFile(join(repo, 'src', 'value'), 'my uncommitted work')const paths = await Promise.all([prepare('worktree'), prepare('worktree', 'refs/remotes/origin/feature')])diff --git a/cli/src/lib/gitProject.ts b/cli/src/lib/gitProject.tsindex 47b9b233e..b4fd510f5 100644--- a/cli/src/lib/gitProject.ts+++ b/cli/src/lib/gitProject.ts@@ -61,8 +61,33 @@ async function mainCheckout(root: string, trees: Worktree[]): Promise<string | nreturn null}-/** Read only: listing a branch never checks it out or fetches from a remote. */-export async function readGitProject(path: string) {+const branchRefreshes = new Map<string, Promise<Map<string, string[] | null>>>()++/** Share a refresh across pickers/worktrees. Ask for names only: downloading+ * objects is deferred until Start, and no repository files or refs change. */+async function refreshBranches(path: string): Promise<Map<string, string[] | null>> {+ const common = await git(path, ['rev-parse', '--git-common-dir'])+ const key = await real(isAbsolute(common) ? common : join(path, common))+ const pending = branchRefreshes.get(key)+ if (pending) return pending+ const refresh = (async () => {+ const remotes = (await git(path, ['remote'])).split('\n').filter(Boolean)+ return new Map(await Promise.all(remotes.map(async remote => {+ const names = await git(path, ['ls-remote', '--heads', '--', remote], 8_000)+ .then(output => output.split('\n').flatMap(line => {+ const ref = line.split('\t')[1]+ return ref?.startsWith('refs/heads/') ? [ref.slice('refs/heads/'.length)] : []+ }), () => null)+ return [remote, names] as const+ })))+ })()+ branchRefreshes.set(key, refresh)+ try { return await refresh } finally { branchRefreshes.delete(key) }+}++/** Cached choices are immediate. A picker can separately request a bounded+ * remote refresh, including branches excluded by a single-branch clone. */+export async function readGitProject(path: string, options: { refresh?: boolean } = {}) {if (!validGitPath(path)) return { error: 'INVALID_PATH' }let root: stringtry { root = await git(path, ['rev-parse', '--show-toplevel']) }@@ -71,6 +96,7 @@ export async function readGitProject(path: string) {return !failure.killed && failure.code === 128 ? { isGit: false, branches: [] } : { error: 'GIT_UNAVAILABLE' }}try {+ const discovered = options.refresh ? await refreshBranches(path).catch(() => null) : undefinedconst [branch, refs, trees, originHead, marked] = await Promise.all([git(path, ['symbolic-ref', '--quiet', 'HEAD']).then(ref => ref.replace(/^refs\/heads\//, '')).catch(() => null),git(path, ['for-each-ref', '--format=%(refname)%09%(refname:short)%09%(symref)', 'refs/heads', 'refs/remotes']),@@ -86,11 +112,20 @@ export async function readGitProject(path: string) {const harness = !ref.startsWith('refs/remotes/') && (marked.has(name) || name.startsWith('harness/'))return [{ ref, name, remote: ref.startsWith('refs/remotes/'), ...(worktree ? { worktree } : {}), ...(harness ? { harness } : {}) }]})+ for (const [remote, names] of discovered ?? []) {+ if (names === null) continue // Offline: retain this remote's saved choices.+ const prefix = `refs/remotes/${remote}/`+ for (let i = branches.length - 1; i >= 0; i--) {+ if (branches[i]!.ref.startsWith(prefix)) branches.splice(i, 1)+ }+ branches.push(...names.map(name => ({ ref: `${prefix}${name}`, name: `${remote}/${name}`, remote: true })))+ }// Where new work starts by default: the remote's default branch, as a clone names it, else its// main or master.const known = new Set(branches.map(row => row.ref))const defaultRef = [originHead, 'refs/remotes/origin/main', 'refs/remotes/origin/master'].find(ref => ref && known.has(ref))- const found = { isGit: true, root, branch, branches, ...(defaultRef ? { defaultRef } : {}) }+ const found = { isGit: true, root, branch, branches, ...(defaultRef ? { defaultRef } : {}),+ ...(discovered === undefined ? {} : { refreshed: discovered !== null && [...discovered.values()].every(names => names !== null) }) }// A worktree is a temporary folder. The launcher shows its repository.const main = await mainCheckout(root, trees)if (!main) return found@@ -141,7 +176,10 @@ export async function prepareGitProject(source: string, options: GitProjectOptioroot = await git(source, ['rev-parse', '--show-toplevel'])if (options.ref && !creating) {if (!/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/.test(options.ref)) throw new Error('Invalid branch')- await git(source, ['show-ref', '--verify', '--hash', '--', options.ref])+ // A freshly discovered remote branch may not have been fetched yet.+ if (!(options.worktree && !existing && remoteBranch(options.ref))) {+ await git(source, ['show-ref', '--verify', '--hash', '--', options.ref])+ }}// New work starts from where its branch is now, not from the last fetch: a remote branch is// fetched; a local one is fetched against its upstream and the newer of the two taken, so nothing@@ -229,6 +267,17 @@ export async function prepareGitProject(source: string, options: GitProjectOptioif (!destination) throw new GitProjectError('WORKTREE_FAILED', 'Could not create a worktree folder. Check folder permissions, then retry.')const remote = remoteBranch(options.ref)try {+ if (!existing && remote?.branch === branch) {+ // A single-branch clone has no tracking rule for this newly discovered+ // branch. Add only the chosen branch when the person starts it.+ const key = `remote.${remote.remote}.fetch`+ const mappings = (await git(source, ['config', '--get-all', key]).catch(() => ''))+ .split('\n').map(ref => ref.replace(/^\+/, ''))+ if (!mappings.includes(remote.refspec.slice(1)) &&+ !mappings.includes(`refs/heads/*:refs/remotes/${remote.remote}/*`)) {+ await git(source, ['config', '--add', key, remote.refspec])+ }+ }await git(source, existing? ['worktree', 'add', '--', destination, branch]// A remote branch checked out under its own name tracks it; a new branch from one must not,diff --git a/desktop/design/search-freshness.md b/desktop/design/search-freshness.mdnew file mode 100644index 000000000..8caf37669--- /dev/null+++ b/desktop/design/search-freshness.md@@ -0,0 +1,41 @@+# Search freshness++Search should show saved results immediately, preserve the query and selection,+and update the data without making typing wait for another machine.++| Place | Refresh behavior |+| --- | --- |+| New Harness (⌘N) → Branch, including shared Store/launch entry points | Read saved Git metadata first. Entering Branch checks remote branch names in the background, at most once per 10 seconds in that picker. Refresh or ⌘/Ctrl+R bypasses that interval. |+| New Harness → Open Folder | Read one directory when entering or revisiting it. Keep saved suggestions visible during refresh. Typing within the same directory only filters those suggestions. |+| New Harness → New Project | Refresh the parent folder on entry/revisit so a project created elsewhere becomes an “Open existing” choice. |+| Remote folder browser | Read the directory on navigation. Refresh or ⌘/Ctrl+R updates the current directory while preserving its rows, selection, and typed path. |+| Recent projects | Combine saved project history with live harness project metadata. This is a list of used projects, not a recursive disk index. Open Folder discovers other folders. |+| Open Harness (⌘O), project/machine groups, and Harnesses | Filter the live harness inventory, including its branch metadata. These surfaces do not query every repository's Git branches. |++## Cost and failure behavior++- Branch discovery asks each configured Git remote for names with `ls-remote+ --heads`. It does not download commits, change refs, check out branches, or+ alter working files. Start fetches the chosen branch when needed.+- Concurrent branch checks share one lookup per repository, including linked+ worktrees. Each remote has an 8-second deadline. Failed remotes retain saved+ choices; successful remotes contribute new names and remove deleted names.+- Remote folder completion has an 80 ms debounce, lists one level, coalesces+ in-flight requests, and retains at most 16 directory listings. Manual refresh+ and revisiting a directory reuse visible rows while requesting fresh data.+- Late replies cannot replace a newer machine/project selection or query.+ Refresh failures offer a retry and retain previously usable results.+- No new background polling or network request per search keystroke.++## Checks++Regression tests cover a branch pushed after a single-branch clone, opening that+branch, offline/partial/timeout replies, deleted branches, concurrent refreshes,+preserving dirty files, hidden branch names, folder revisits, changed project+names, late replies, live ⌘O metadata, and keyboard/layout behavior.++On the development Mac, saved Git refs took a median 20 ms to read. A GitHub+names-only lookup returned 175 branches (13.7 KB) in 1.0 second. In a debug+controller test, filtering 2,000 refs over 100 queries took roughly 3 ms at the+median and 4 ms at the 95th percentile. These are observations, not latency+guarantees; remote folder speed also depends on the connection and directory.diff --git a/desktop/lib/core/git_worktree.dart b/desktop/lib/core/git_worktree.dartindex 12817dcbf..34fa080e9 100644--- a/desktop/lib/core/git_worktree.dart+++ b/desktop/lib/core/git_worktree.dart@@ -232,9 +232,72 @@ typedef GitProcessStarter = Future<Process> Function(Map<String, String> environment,);-/// Listing choices never checks out a branch or fetches from a remote.+final _branchRefreshes = <String, Future<Map<String, List<String>?>>>{};++/// Coalesce concurrent pickers, including linked worktrees of the same repo.+/// Ask for names only; downloading objects is deferred until Start.+Future<Map<String, List<String>?>> _refreshRemoteBranches(+ String source, {+ GitProcessStarter? startProcess,+}) async {+ final common = await _git(source, [+ 'rev-parse',+ '--git-common-dir',+ ], startProcess: startProcess);+ if (common.code != 0) {+ throw const RepositoryCloneException('Git is unavailable.');+ }+ final key = await _realPath(+ p.isAbsolute(common.output) ? common.output : p.join(source, common.output),+ );+ if (_branchRefreshes[key] case final pending?) return pending;+ final refresh = () async {+ final remotes = await _git(source, ['remote'], startProcess: startProcess);+ if (remotes.code != 0) {+ throw const RepositoryCloneException('Git is unavailable.');+ }+ final results = await Future.wait([+ for (final remote+ in remotes.output.split('\n').where((s) => s.isNotEmpty))+ () async {+ try {+ final result = await _git(+ source,+ ['ls-remote', '--heads', '--', remote],+ timeout: const Duration(seconds: 8),+ startProcess: startProcess,+ );+ return MapEntry(+ remote,+ result.code == 0+ ? [+ for (final line in result.output.split('\n'))+ if (line.split('\t') case [_, final ref]+ when ref.startsWith('refs/heads/'))+ ref.substring('refs/heads/'.length),+ ]+ : null,+ );+ } on RepositoryCloneException {+ return MapEntry<String, List<String>?>(remote, null);+ }+ }(),+ ]);+ return Map<String, List<String>?>.fromEntries(results);+ }();+ _branchRefreshes[key] = refresh;+ try {+ return await refresh;+ } finally {+ _branchRefreshes.remove(key);+ }+}++/// Read cached choices, or explicitly refresh remote branches first. Refresh+/// failures retain usable local results and are reported separately.Future<Map<String, dynamic>> readLocalGitProject(String source, {+ bool refresh = false,GitProcessStarter? startProcess,}) async {Future<({int code, String output})> git(List<String> arguments) =>@@ -245,6 +308,17 @@ Future<Map<String, dynamic>> readLocalGitProject(if (root.code != 0) {return root.code == 128 ? {'isGit': false} : {'error': 'GIT_UNAVAILABLE'};}+ Map<String, List<String>?>? discovered;+ if (refresh) {+ try {+ discovered = await _refreshRemoteBranches(+ source,+ startProcess: startProcess,+ );+ } on RepositoryCloneException {+ /* Keep saved choices available offline. */+ }+ }final results = await Future.wait([git(['symbolic-ref', '--quiet', 'HEAD']),git([@@ -265,10 +339,25 @@ Future<Map<String, dynamic>> readLocalGitProject(key.substring(7, key.length - kHarnessBranchKey.length - 1),};if (results[1].code != 0) return {'error': 'GIT_UNAVAILABLE'};- final refs = {+ final branches = <Map<String, dynamic>>[for (final line in results[1].output.split('\n'))- if (line.split('\t') case [final ref, _, '']) ref,- };+ if (line.split('\t') case [final ref, final name, ''])+ {'ref': ref, 'name': name, 'remote': ref.startsWith('refs/remotes/')},+ ];+ for (final entry+ in discovered?.entries ?? const <MapEntry<String, List<String>?>>[]) {+ final names = entry.value;+ if (names == null) continue;+ final prefix = 'refs/remotes/${entry.key}/';+ branches.removeWhere(+ (branch) => (branch['ref'] as String).startsWith(prefix),+ );+ branches.addAll([+ for (final name in names)+ {'ref': '$prefix$name', 'name': '${entry.key}/$name', 'remote': true},+ ]);+ }+ final refs = {for (final branch in branches) branch['ref']};// Where new work starts by default: the remote's default branch, as a// clone names it, else its main or master.final defaultRef = [@@ -299,6 +388,10 @@ Future<Map<String, dynamic>> readLocalGitProject(}return {'isGit': true,+ if (refresh)+ 'refreshed':+ discovered != null &&+ discovered.values.every((names) => names != null),'root': root.output,'branch': results[0].code == 0? results[0].output.replaceFirst('refs/heads/', '')@@ -307,17 +400,15 @@ Future<Map<String, dynamic>> readLocalGitProject('mainBranch': ?mainBranch,'defaultRef': ?defaultRef,'branches': [- for (final line in results[1].output.split('\n'))- if (line.split('\t') case [final ref, final name, ''])- {- 'ref': ref,- 'name': name,- 'remote': ref.startsWith('refs/remotes/'),- 'worktree': ?checkedOut[ref],- if (ref.startsWith('refs/heads/') &&- (marked.contains(name) || name.startsWith('harness/')))- 'harness': true,- },+ for (final branch in branches)+ {+ ...branch,+ 'worktree': ?checkedOut[branch['ref']],+ if (branch['remote'] == false &&+ (marked.contains(branch['name']) ||+ (branch['name'] as String).startsWith('harness/')))+ 'harness': true,+ },],};} on RepositoryCloneException {@@ -367,7 +458,8 @@ Future<String> prepareGitProject(}// A new branch for the folder itself: [branchRef] names it and does not exist.final creating = !worktree && branchName != null && !existingBranch;- if (branchRef != null && !creating) {+ final remote = worktree && !existingBranch ? _remoteBranch(branchRef) : null;+ if (branchRef != null && !creating && remote == null) {final ref = await git(['show-ref', '--verify', '--hash', '--', branchRef]);if (ref.code != 0) {throw const RepositoryCloneException(@@ -379,7 +471,6 @@ Future<String> prepareGitProject(// remote branch is fetched; a local one is fetched against its upstream and// the newer of the two taken, so nothing only the local one has is lost.// Offline, slow or refused, it starts from what is here.- final remote = worktree && !existingBranch ? _remoteBranch(branchRef) : null;var start = existingBranch? 'refs/heads/$branchName': creating@@ -587,6 +678,24 @@ Future<String> prepareGitProject('Could not create a worktree folder. Check folder permissions, then retry.',);}+ if (!existingBranch && remote != null && remote.branch == branch) {+ // Single-branch clones need a tracking rule for this branch. Add only+ // the selected branch, at Start, never while reading search results.+ final key = 'remote.${remote.remote}.fetch';+ final configured = await git(['config', '--get-all', key]);+ final mappings = configured.output+ .split('\n')+ .map((ref) => ref.replaceFirst(RegExp(r'^\+'), ''));+ if (!mappings.contains(remote.refspec.substring(1)) &&+ !mappings.contains('refs/heads/*:refs/remotes/${remote.remote}/*')) {+ final configured = await git(['config', '--add', key, remote.refspec]);+ if (configured.code != 0) {+ throw const RepositoryCloneException(+ 'Could not set up branch tracking. Check Git permissions, then retry.',+ );+ }+ }+ }final result = await git(existingBranch? ['worktree', 'add', '--', destination, branch]diff --git a/desktop/lib/models/models_panel.dart b/desktop/lib/models/models_panel.dartindex 0949df2d2..1959d242c 100644--- a/desktop/lib/models/models_panel.dart+++ b/desktop/lib/models/models_panel.dart@@ -10,6 +10,7 @@ import '../usage/models_menu_controller.dart';import 'local_model.dart';import 'model_manager_controller.dart';import 'model_mark.dart';+import '../widgets/onboarding_card.dart';enum ModelsTab { subscriptions, local, shared }@@ -21,12 +22,16 @@ class ModelsPanel extends StatefulWidget {required this.onClose,required this.onManage,this.newModelIds = const {},+ this.showOnboarding = false,+ this.onDismissOnboarding,this.initialTab = ModelsTab.subscriptions,});final ModelManagerController controller;final ModelsMenuController subscriptions;final VoidCallback onClose, onManage;final Set<String> newModelIds;+ final bool showOnboarding;+ final VoidCallback? onDismissOnboarding;final ModelsTab initialTab;@overrideState<ModelsPanel> createState() => _ModelsPanelState();@@ -34,6 +39,7 @@ class ModelsPanel extends StatefulWidget {class _ModelsPanelState extends State<ModelsPanel> {final _search = TextEditingController();+ bool _exploring = false;final _searchFocus = FocusNode(debugLabel: 'Search models');late ModelsTab _selectedTab = widget.initialTab;ModelManagerController get controller => widget.controller;@@ -130,6 +136,18 @@ class _ModelsPanelState extends State<ModelsPanel> {],),),+ if (widget.showOnboarding && !_exploring)+ OnboardingCard(+ title: 'Power a harness with local AI',+ description: 'Choose a model that runs on your computer. Then select it in a harness’s model picker.',+ action: 'Explore local models',+ onAction: () => setState(() {+ _exploring = true;+ _selectedTab = ModelsTab.local;+ _search.clear();+ }),+ onDismiss: widget.onDismissOnboarding ?? () {},+ ),Padding(padding: const EdgeInsets.symmetric(horizontal: 16),child: TextField(@@ -654,7 +672,9 @@ class LocalModelInvitation extends StatelessWidget {super.key,required this.controller,required this.onOpen,+ this.showIntroduction = true,});+ final bool showIntroduction;final ModelManagerController controller;final VoidCallback onOpen;@override@@ -662,7 +682,8 @@ class LocalModelInvitation extends StatelessWidget {listenable: controller,builder: (context, _) {final ready = controller.readyModel;- if (ready == null && !controller.showIntroduction) {+ if (ready == null &&+ (!showIntroduction || !controller.showIntroduction)) {return const SizedBox.shrink();}return Align(diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 8170965e6..44b35fe52 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -80,6 +80,8 @@ import '../widgets/harness_command_bar.dart';import '../orchestrator/orchestrator_launcher.dart';import '../orchestrator/orchestrator_workspace.dart';import '../state/workspace_learning.dart';+import '../state/workspace_onboarding.dart';+import '../widgets/onboarding_card.dart';import '../widgets/workspace_quick_start.dart';import '../widgets/workspace_start_guide.dart';import '../widgets/workspace_welcome.dart';@@ -99,6 +101,7 @@ class SwarmScreen extends StatefulWidget {),this.commandResolver,this.learning,+ this.onboarding,});final AppNotifier notifier;final bool? nativeTabs;@@ -107,6 +110,7 @@ class SwarmScreen extends StatefulWidget {final bool commandBarEnabled;final CommandResolver? commandResolver;final WorkspaceLearning? learning;+ final WorkspaceOnboarding? onboarding;@overrideState<SwarmScreen> createState() => _SwarmScreenState();}@@ -148,6 +152,9 @@ class _SwarmScreenState extends State<SwarmScreen>final _sessionsButton = GlobalKey();MachinesPanelHandle? _machinesPanel;final _toolbarNotices = ToolbarNotices();+ late final _onboarding =+ widget.onboarding ??+ WorkspaceOnboarding(storage: kUnderTest ? null : HarnessFileStore.shared);OverlayEntry? _sessionsOverlay;VoidCallback? _unregisterSessions;OverlayEntry? _modelsOverlay;@@ -259,6 +266,7 @@ class _SwarmScreenState extends State<SwarmScreen>_lifecycle = AppLifecycleListener(onResume: app.seeWatchedAgents);app.addListener(_syncToolbarNotices);_toolbarNotices.addListener(_toolbarNoticesChanged);+ _onboarding.addListener(_onboardingChanged);_syncToolbarNotices();unawaited(_learning.load().then((_) {@@ -332,6 +340,8 @@ class _SwarmScreenState extends State<SwarmScreen>app.removeListener(_syncToolbarNotices);_toolbarNotices.removeListener(_toolbarNoticesChanged);_toolbarNotices.dispose();+ _onboarding.removeListener(_onboardingChanged);+ if (widget.onboarding == null) _onboarding.dispose();_machinesPanel?.close(restoreFocus: false);app.modelManager.removeListener(_modelManagerChanged);app.modelManager.setPanelVisible(false);@@ -572,7 +582,69 @@ class _SwarmScreenState extends State<SwarmScreen>/// still separates the two — its "Needs input" tab is exactly [_attention].int get _unread => app.agentUnread.count;+ void _syncOnboarding() {+ final profile = app.currentUser;+ final local = app.localMachineState?.machine.machineId;+ final used = app.allPanes+ .where(+ (pane) =>+ pane.session?.acceptsInput == true &&+ pane.session?.engineId != kTerminalEngine &&+ app.stateOf(pane.machineId)?.machine.isShared == false,+ )+ .toList();+ final localModels = app.modelManager.sections+ .where((section) => section.own)+ .expand((section) => section.models)+ .map((model) => model.id)+ .toSet();+ _onboarding.sync(+ scope: app.isGuest+ ? 'local:${local ?? 'guest'}'+ : 'account:${profile?.id ?? profile?.email ?? local}',+ observed: {+ if (used.isNotEmpty) OnboardingStep.harnesses,+ if (used.any(+ (pane) => app.stateOf(pane.machineId)?.isLocalMachine == false,+ ))+ OnboardingStep.machines,+ if (used.any(+ (pane) =>+ app+ .stateOf(pane.machineId)+ ?.agents+ .any(+ (agent) =>+ agent.id == pane.agentId &&+ agent.gridModel != null &&+ localModels.contains(agent.gridModel),+ ) ==+ true,+ ))+ OnboardingStep.models,+ },+ otherComputer:+ !app.isGuest &&+ app.machineStates.values.any(+ (machine) => !machine.isLocalMachine && !machine.machine.isShared,+ ),+ modelsAvailable: app.modelManager.localModels.any(+ (model) => model.canStart || model.running,+ ),+ );+ }++ void _onboardingChanged() {+ if (!mounted) return;+ _sessionsOverlay?.markNeedsBuild();+ _modelsOverlay?.markNeedsBuild();+ _machinesPanel?.rebuild();+ if (_native) _syncNative();+ setState(() {});+ }+void _syncToolbarNotices() {+ _syncOnboarding();final local = app.localMachineState?.machine.machineId;final models = app.modelManager;final profile = app.currentUser;@@ -724,6 +796,10 @@ class _SwarmScreenState extends State<SwarmScreen>'machinesOpen': _machinesPanel != null,'machineNotices': _toolbarNotices.machineCount,'modelNotices': _toolbarNotices.modelCount,+ 'onboarding':+ _onboarding.next != null && _onboarding.showsDot(_onboarding.next!)+ ? _onboarding.next!.name+ : null,'modelsOpen': _modelsOverlay != null,'localModelReady': app.modelManager.readyModel != null,'runningSessions': harnessSessions(app)@@ -1433,11 +1509,13 @@ class _SwarmScreenState extends State<SwarmScreen>_closeCommandBar(restoreFocus: false);dismissTransientMenus();_preparePaneFocus();+ _onboarding.acknowledge(OnboardingStep.machines);final panel = openMachinesPanel(context,app,keymap: _keymap,initialMachineId: initialMachineId,+ onboarding: _onboarding,toolbarHeight: _native ? 0 : _tabBarHeight,);_machinesPanel = panel;@@ -2236,6 +2314,7 @@ class _SwarmScreenState extends State<SwarmScreen>_closeCommandBar(restoreFocus: false);dismissTransientMenus();_preparePaneFocus();+ _onboarding.acknowledge(OnboardingStep.models);app.modelManager.setPanelVisible(true);unawaited(app.modelManager.dismissIntroduction());unawaited(app.modelManager.refresh());@@ -2277,6 +2356,9 @@ class _SwarmScreenState extends State<SwarmScreen>),child: ModelsPanel(newModelIds: _toolbarNotices.newModelIds,+ showOnboarding: _onboarding.next == OnboardingStep.models,+ onDismissOnboarding: () =>+ _onboarding.dismiss(OnboardingStep.models),controller: app.modelManager,subscriptions: _modelsMenu!,initialTab: initialTab,@@ -2329,6 +2411,7 @@ class _SwarmScreenState extends State<SwarmScreen>_closeCommandBar(restoreFocus: false);dismissTransientMenus();_preparePaneFocus();+ _onboarding.acknowledge(OnboardingStep.harnesses);final overlay = Overlay.of(context);_sessionsOverlay = OverlayEntry(builder: (context) => LayoutBuilder(@@ -2372,6 +2455,20 @@ class _SwarmScreenState extends State<SwarmScreen>padding: const EdgeInsets.all(1),child: HarnessSessionManager(app: app,+ introduction: _onboarding.next == OnboardingStep.harnesses+ ? OnboardingCard(+ title: 'Run your first harness',+ description:+ 'Give an agent a task. Watch it get to work.',+ action: 'New harness',+ onAction: () {+ _closeSessions(restoreFocus: false);+ _runShortcut('agent.new');+ },+ onDismiss: () =>+ _onboarding.dismiss(OnboardingStep.harnesses),+ )+ : null,initialFilter: filter ?? SessionFilter.all,recent: _navigation.recent,onClose: _closeSessions,@@ -3673,6 +3770,7 @@ class _SwarmScreenState extends State<SwarmScreen>if (!_commandBarOpen && _newHarness == null)LocalModelInvitation(controller: app.modelManager,+ showIntroduction: false,onOpen: () =>_toggleModels(initialTab: ModelsTab.local),),@@ -3759,6 +3857,7 @@ class _SwarmScreenState extends State<SwarmScreen>required int count,required String label,required Widget child,+ OnboardingStep? step,}) => Badge(key: key,isLabelVisible: count > 0,@@ -3771,7 +3870,31 @@ class _SwarmScreenState extends State<SwarmScreen>semanticsLabel: label,style: const TextStyle(fontSize: 9, fontWeight: FontWeight.w600),),- child: child,+ child: step != null && _onboarding.showsDot(step)+ ? Stack(+ clipBehavior: Clip.none,+ children: [+ child,+ Positioned(+ right: -3,+ top: count > 0 ? null : -3,+ bottom: count > 0 ? -3 : null,+ child: Semantics(+ label: 'Suggested next step',+ child: Container(+ key: ValueKey('onboarding-${step.name}-dot'),+ width: 6,+ height: 6,+ decoration: const BoxDecoration(+ shape: BoxShape.circle,+ color: Color(0xff99c2ed),+ ),+ ),+ ),+ ),+ ],+ )+ : child,);Widget _tabStrip() => LayoutBuilder(@@ -3941,6 +4064,7 @@ class _SwarmScreenState extends State<SwarmScreen>style: _toolbarIconStyle(_toolbarNotices.machineCount),icon: _toolbarBadge(key: const ValueKey('swarm-machines-badge'),+ step: OnboardingStep.machines,count: _toolbarNotices.machineCount,label:'${_toolbarNotices.machineCount} new ${_toolbarNotices.machineCount == 1 ? 'computer' : 'computers'} ready to connect',@@ -3955,6 +4079,7 @@ class _SwarmScreenState extends State<SwarmScreen>style: _toolbarIconStyle(_toolbarNotices.modelCount),icon: _toolbarBadge(key: const ValueKey('swarm-models-badge'),+ step: OnboardingStep.models,count: _toolbarNotices.modelCount,label:'${_toolbarNotices.modelCount} ${_toolbarNotices.modelCount == 1 ? 'model' : 'models'} ready to use',@@ -3969,6 +4094,7 @@ class _SwarmScreenState extends State<SwarmScreen>style: _toolbarIconStyle(_unread),icon: _toolbarBadge(key: const ValueKey('swarm-unread-badge'),+ step: OnboardingStep.harnesses,count: _unread,label:'$_unread ${_unread == 1 ? 'harness has' : 'harnesses have'} news you have not seen',diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex c026d3aa6..ff24d8edd 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -6620,13 +6620,16 @@ class AppNotifier extends ChangeNotifier {/// Git choices are read on the machine that owns this project.Future<Map<String, dynamic>> readGitProject(String machineId,- String path,- ) async {+ String path, {+ bool refresh = false,+ }) async {final machine = machineStates[machineId];if (machine == null) return {'error': 'UNAVAILABLE'};final reader = gitProjectReaderForTest;if (reader != null) return reader(machineId, path);- if (machine.isLocalMachine) return readLocalGitProject(path);+ if (machine.isLocalMachine) {+ return readLocalGitProject(path, refresh: refresh);+ }if (connectionForTest == null &&(machine.nodeOnline == false ||machine.needsLink ||@@ -6636,8 +6639,8 @@ class AppNotifier extends ChangeNotifier {try {return await _conn(machineId).request('git_project_info',- payload: {'path': path},- timeout: const Duration(seconds: 6),+ payload: {'path': path, if (refresh) 'refresh': true},+ timeout: Duration(seconds: refresh ? 20 : 6),);} catch (_) {return {'error': 'UNAVAILABLE'};diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dartindex 723c251c7..abb142223 100644--- a/desktop/lib/state/new_harness.dart+++ b/desktop/lib/state/new_harness.dart@@ -501,6 +501,9 @@ class NewHarnessController extends ChangeNotifier {Future<void>? _gitFuture;int _gitRevision = 0;bool checkingGit = false;+ bool refreshingBranches = false;+ String? branchRefreshError;+ DateTime? _branchesCheckedAt;Future<void> waitForGitProject() async {while (checkingGit && !_disposed) {await _gitFuture;@@ -612,6 +615,54 @@ class NewHarnessController extends ChangeNotifier {notifyListeners();}+ /// Cached matches stay usable while Git discovers branches pushed elsewhere.+ /// Typing only filters; entering Branch refreshes at most once per ten seconds.+ Future<void> refreshBranches({bool force = true}) async {+ if (_disposed ||+ locked ||+ checkingGit ||+ refreshingBranches ||+ !isGitProject ||+ _gitKey == null) {+ return;+ }+ if (!force &&+ _branchesCheckedAt != null &&+ _now().difference(_branchesCheckedAt!) < const Duration(seconds: 10)) {+ return;+ }+ _branchesCheckedAt = _now();+ await _readGitProject(_gitKey!, refresh: true);+ }++ bool get canRefreshChoices => switch (field) {+ NewHarnessField.branch => isGitProject,+ NewHarnessField.project ||+ NewHarnessField.projectName => _visibleFolder != null,+ _ => false,+ };+ bool get refreshingChoices =>+ field == NewHarnessField.branch ? refreshingBranches : listing;+ String? get choicesStatus => field == NewHarnessField.branch+ ? refreshingBranches+ ? 'Checking remote branches…'+ : branchRefreshError+ : canRefreshChoices+ ? listing+ ? 'Checking folders…'+ : folderRefreshError+ : null;++ void refreshChoices() {+ if (locked || !canRefreshChoices) return;+ if (field == NewHarnessField.branch) {+ unawaited(refreshBranches());+ } else if (_visibleFolder case final folder?) {+ _requestListing(folder);+ notifyListeners();+ }+ }+void _syncGitProject() {final key = (_machineId, _project.folder, isTerminal);if (_gitKey == key) return;@@ -625,23 +676,48 @@ class NewHarnessController extends ChangeNotifier {_gitKey = key;_gitRevision++;checkingGit = false;+ refreshingBranches = false;+ branchRefreshError = null;+ _branchesCheckedAt = null;_gitFuture = null;if (key.$2 != null && !key.$3 && !checking) {_gitFuture = _readGitProject(key);}}- Future<void> _readGitProject((String, String?, bool) key) async {- checkingGit = true;+ Future<void> _readGitProject(+ (String, String?, bool) key, {+ bool refresh = false,+ }) async {+ if (refresh) {+ refreshingBranches = true;+ branchRefreshError = null;+ _refresh();+ } else {+ checkingGit = true;+ }final revision = ++_gitRevision;GitProjectInfo info;try {- info = GitProjectInfo.fromJson(await app.readGitProject(key.$1, key.$2!));+ final data = await app.readGitProject(key.$1, key.$2!, refresh: refresh);+ if (_disposed || _gitKey != key || revision != _gitRevision) return;+ info = GitProjectInfo.fromJson(data);+ if (refresh && data['refreshed'] != true) {+ branchRefreshError =+ 'Couldn’t refresh remote branches. Showing saved branches.';+ }} catch (_) {info = const GitProjectInfo(error: 'UNAVAILABLE');}if (_disposed || _gitKey != key || revision != _gitRevision) return;checkingGit = false;+ refreshingBranches = false;+ if (refresh && info.error != null) {+ branchRefreshError =+ 'Couldn’t refresh remote branches. Showing saved branches.';+ _refresh();+ return;+ }// A worktree is a temporary folder, so the launcher shows its repository.// With Worktree off its branch stays chosen and Start reopens that// worktree; otherwise new work starts from the repository's own branch.@@ -665,6 +741,9 @@ class NewHarnessController extends ChangeNotifier {_placeholder = null;}_refresh();+ if (!refresh && field == NewHarnessField.branch) {+ unawaited(refreshBranches(force: false));+ }}LocalCodexProfile? _profile;@@ -836,7 +915,7 @@ class NewHarnessController extends ChangeNotifier {/// A folder's listing has been asked for and has not come back: the list is/// not empty, it is not here yet, and the two must not read the same.- bool get listing => _listing != null;+ bool get listing => _visibleFolder != null && _listing == _visibleFolder;bool busy = false;String? status;String? error;@@ -844,6 +923,8 @@ class NewHarnessController extends ChangeNotifier {/// Folder listings for path completion, by the folder that was listed.final _listings = <String, List<String>>{};+ final _loadingFolders = <String>{};+ String? _visibleFolder, folderRefreshError;String? _listing;bool _known(String? id) =>@@ -933,6 +1014,7 @@ class NewHarnessController extends ChangeNotifier {// use the agent currently being previewed in the choices list.if (!previewAgent) _agentPreview = null;if (field == next || !_supportsField(next)) return;+ _visibleFolder = folderRefreshError = null;if (next == NewHarnessField.machine) {_machineOrigin = (field: field,@@ -971,6 +1053,9 @@ class NewHarnessController extends ChangeNotifier {: '';error = null;_refresh();+ if (next == NewHarnessField.branch) {+ unawaited(refreshBranches(force: false));+ }}void nextField([int step = 1]) {@@ -1398,6 +1483,8 @@ class NewHarnessController extends ChangeNotifier {_machineRevision++;_listDebounce?.cancel();_listings.clear();+ _loadingFolders.clear();+ _visibleFolder = folderRefreshError = null;_listing = null;_pathKey = null;unawaited(app.probeEngines(id, force: true));@@ -1854,7 +1941,14 @@ class NewHarnessController extends ChangeNotifier {final kept = current == null? -1: options.indexWhere((option) => option.id == current);- final now = options.indexWhere(_isCurrent);+ final selectedBranch = field == NewHarnessField.branch ? branchRef : null;+ final now = query.isNotEmpty+ ? -1+ : options.indexWhere(+ field == NewHarnessField.branch+ ? (option) => option.id == selectedBranch+ : _isCurrent,+ );final pathChoice = isPathQuery? options.indexWhere((option) => option.project?.folder != null): -1;@@ -1926,28 +2020,36 @@ class NewHarnessController extends ChangeNotifier {}/// Branches to start from (Worktree on) or to work on (off), tagged the way- /// editors tag them. Branches Harness named for worktrees that are gone are- /// left out: nobody chose them.+ /// editors tag them. The default list hides duplicate remote names and old+ /// Harness branches; typing can find every branch.List<NewHarnessOption> _branchOptions() {final info = _gitProject;+ final selectedRef = branchRef;+ final usesWorktree = worktree;+ final searching = query.trim().isNotEmpty;final defaultName = info.defaultRef?.split('/').skip(3).join('/');bool isDefault(GitBranch b) =>b.ref == info.defaultRef || !b.remote && b.name == defaultName;bool isCurrent(GitBranch b) => !b.remote && b.name == info.branch;// A remote branch with a local one of its name is that branch: Start// brings the local one up to it.- final locals = {+ final candidates = [for (final branch in info.branches)+ if (searching ||+ !((branch.harness || branch.name.startsWith('harness/')) &&+ branch.worktree == null &&+ branch.ref != selectedRef))+ branch,+ ];+ final locals = {+ for (final branch in candidates)if (!branch.remote) branch.name,};bool hasLocal(GitBranch b) =>b.remote && locals.contains(b.name.split('/').skip(1).join('/'));final shown = [- for (final branch in info.branches)- if (!((branch.harness || branch.name.startsWith('harness/')) &&- branch.worktree == null &&- branch.ref != branchRef) &&- !(hasLocal(branch) && branch.ref != branchRef))+ for (final branch in candidates)+ if (searching || !(hasLocal(branch) && branch.ref != selectedRef))branch,];int rank(GitBranch b) => isDefault(b)@@ -1968,10 +2070,11 @@ class NewHarnessController extends ChangeNotifier {detail: [if (isDefault(branch)) 'default',if (isCurrent(branch)) 'current',- if (_worktreeOf(branch.ref) != null) 'worktree',+ if (branch.worktree != null && branch.name != info.branch)+ 'worktree',if (branch.remote) 'remote',].join(' · '),- enabled: worktree || !branch.remote,+ enabled: usesWorktree || !branch.remote,why: branch.remote? 'Turn Worktree on to start from a remote branch.': null,@@ -1984,9 +2087,11 @@ class NewHarnessController extends ChangeNotifier {/// the default branch, off in the folder from the branch it is on. Spaces/// become `-`, and what Git refuses in a name is dropped.NewHarnessOption? _createBranchRow() {+ if (refreshingBranches) return null;final name = branchNameFrom(query);if (!plausibleBranchName(name) ||- newBranchHere(_gitProject, name) == null) {+ newBranchHere(_gitProject, name) == null ||+ _gitProject.branches.any((branch) => branch.name == name)) {return null;}final base = worktree@@ -2198,6 +2303,7 @@ class NewHarnessController extends ChangeNotifier {final typed = query.trim();if (field == NewHarnessField.project) {if (_isPath(typed)) return _pathOptions(typed);+ _visibleFolder = folderRefreshError = null;// Recent projects live in the project menu. This prompt only opens a// folder by path or browser, so it cannot look like a second history.total = 0;@@ -2208,8 +2314,13 @@ class NewHarnessController extends ChangeNotifier {// Resolve the owning machine's home before offering an existing name.// The daemon still reserves a fresh name atomically on submission.final root = _expand('~/harnesses');- if (slug != null && p.isAbsolute(root) && !_listings.containsKey(root)) {- _requestListing(root);+ if (slug != null && p.isAbsolute(root)) {+ if (_visibleFolder != root) {+ _visibleFolder = root;+ _requestListing(root);+ }+ } else {+ _visibleFolder = folderRefreshError = null;}final existingName = _listings[root]?.where((name) => name == slug)@@ -2275,6 +2386,7 @@ class NewHarnessController extends ChangeNotifier {List<NewHarnessOption> _pathOptions(String typed) {final full = _expand(typed);if (!p.isAbsolute(full)) {+ _visibleFolder = folderRefreshError = null;total = 0;return [_browse, _changeMachine];}@@ -2284,8 +2396,11 @@ class NewHarnessController extends ChangeNotifier {// list stays the list of the stem that was typed — a completion menu.final stem = (_cycle?.stem ?? full.substring(slash + 1)).toLowerCase();final names = _listings[parent];- if (names == null) {+ if (_visibleFolder != parent) {+ _visibleFolder = parent;_requestListing(parent);+ }+ if (names == null) {total = 0;return const [];}@@ -2366,7 +2481,9 @@ class NewHarnessController extends ChangeNotifier {void _requestListing(String folder) {if (_listing == folder) return;_listing = folder;+ folderRefreshError = null;_listDebounce?.cancel();+ if (_loadingFolders.contains(folder)) return;if (_machine?.isLocalMachine == true) {unawaited(_list(folder));} else {@@ -2378,9 +2495,11 @@ class NewHarnessController extends ChangeNotifier {}Future<void> _list(String folder) async {+ if (_disposed || !_loadingFolders.add(folder)) return;final machineId = _machineId;final revision = _machineRevision;var names = <String>[];+ var failed = false;try {if (_machine?.isLocalMachine == true) {// Five thousand entries streamed through the UI isolate's event loop@@ -2395,7 +2514,7 @@ class NewHarnessController extends ChangeNotifier {} else {final answer = await app.listRemoteFolder(_machineId, folder);final entries = answer['entries'];- if (entries is List) {+ if (answer['error'] == null && entries is List) {names = [for (final entry in entries)if (entry is Map &&@@ -2403,24 +2522,34 @@ class NewHarnessController extends ChangeNotifier {entry['name'] is String)entry['name'] as String,];+ } else {+ failed = true;}}} catch (_) {- // A folder that cannot be read lists nothing, as a shell's Tab does.+ failed = true;}if (_disposed || machineId != _machineId || revision != _machineRevision) {return;}+ _loadingFolders.remove(folder);names.sort((a, b) => compareNatural(a.toLowerCase(), b.toLowerCase()));- _listings.remove(folder);- _listings[folder] = names;+ if (!failed || !_listings.containsKey(folder)) {+ _listings.remove(folder);+ _listings[folder] = names;+ }// Recently listed folders stay; a long walk does not keep every one.while (_listings.length > _maxListings) {_listings.remove(_listings.keys.first);}// An answer for a folder the line has already left is kept, not shown.final current = _listing == folder;- if (current) _listing = null;+ if (current) {+ _listing = null;+ folderRefreshError = failed+ ? 'Couldn’t refresh folders. Try again.'+ : null;+ }if (current &&(field == NewHarnessField.project ||field == NewHarnessField.projectName)) {diff --git a/desktop/lib/state/workspace_onboarding.dart b/desktop/lib/state/workspace_onboarding.dartnew file mode 100644index 000000000..8eb42cea4--- /dev/null+++ b/desktop/lib/state/workspace_onboarding.dart@@ -0,0 +1,148 @@+import 'dart:async';+import 'dart:convert';++import 'package:flutter/foundation.dart';++import '../core/local_key_value_store.dart';++enum OnboardingStep { harnesses, machines, models }++/// Optional next steps, separate from unread work and real notification counts.+/// Observed use completes a step; opening its panel only acknowledges its dot.+class WorkspaceOnboarding extends ChangeNotifier {+ WorkspaceOnboarding({this.storage});+ final LocalKeyValueStore? storage;+ String? _scope;+ bool _loaded = false, _disposed = false;+ bool _otherComputer = false, _modelsAvailable = false;+ int _revision = 0;+ final _completed = <OnboardingStep>{};+ final _dismissed = <OnboardingStep>{};+ final _seen = <OnboardingStep>{};+ Set<OnboardingStep> _observed = {};+ Future<void> _saving = Future.value();++ bool completed(OnboardingStep step) => _completed.contains(step);+ OnboardingStep? get next {+ if (!_loaded) return null;+ if (!completed(OnboardingStep.harnesses) && !_otherComputer) {+ return _dismissed.contains(OnboardingStep.harnesses)+ ? null+ : OnboardingStep.harnesses;+ }+ if (!completed(OnboardingStep.machines) &&+ !_dismissed.contains(OnboardingStep.machines)) {+ return OnboardingStep.machines;+ }+ if (_modelsAvailable &&+ !completed(OnboardingStep.models) &&+ !_dismissed.contains(OnboardingStep.models)) {+ return OnboardingStep.models;+ }+ return null;+ }++ bool showsDot(OnboardingStep step) => next == step && !_seen.contains(step);+ static String storageKey(String scope) =>+ 'workspace.onboarding.v1.${base64Url.encode(utf8.encode(scope))}';++ void sync({+ required String scope,+ required Set<OnboardingStep> observed,+ required bool otherComputer,+ required bool modelsAvailable,+ }) {+ if (_disposed) return;+ final changedScope = _scope != scope;+ final before = next;+ _observed = Set.of(observed);+ _otherComputer = otherComputer;+ _modelsAvailable = modelsAvailable;+ if (changedScope) {+ _scope = scope;+ _loaded = false;+ _completed.clear();+ _dismissed.clear();+ _seen.clear();+ final revision = ++_revision;+ notifyListeners();+ unawaited(_load(scope, revision));+ } else if (_loaded) {+ final changed = _observe();+ if (changed) _save();+ if (changed || next != before) notifyListeners();+ }+ }++ bool _observe() {+ final before = _completed.length;+ _completed.addAll(_observed);+ if (_completed.contains(OnboardingStep.machines) ||+ _completed.contains(OnboardingStep.models)) {+ _completed.add(OnboardingStep.harnesses);+ }+ return _completed.length != before;+ }++ Future<void> _load(String scope, int revision) async {+ Map data = {};+ try {+ await _saving;+ final raw = await storage?.read(storageKey(scope));+ final decoded = raw == null ? null : jsonDecode(raw);+ if (decoded is Map) data = decoded;+ } catch (_) {+ // A missing or corrupt preference cannot block getting to work.+ }+ if (_disposed || _revision != revision) return;+ void read(String key, Set<OnboardingStep> target) {+ final values = data[key];+ if (values is List) {+ target.addAll(+ OnboardingStep.values.where((s) => values.contains(s.name)),+ );+ }+ }++ read('completed', _completed);+ read('dismissed', _dismissed);+ read('seen', _seen);+ _loaded = true;+ if (_observe()) _save();+ notifyListeners();+ }++ void acknowledge(OnboardingStep step) {+ if (_disposed || !_loaded || next != step || !_seen.add(step)) return;+ _save();+ notifyListeners();+ }++ void dismiss(OnboardingStep step) {+ if (_disposed || !_loaded || !_dismissed.add(step)) return;+ _save();+ notifyListeners();+ }++ void _save() {+ final key = storageKey(_scope!);+ final data = jsonEncode({+ 'completed': _completed.map((s) => s.name).toList(),+ 'dismissed': _dismissed.map((s) => s.name).toList(),+ 'seen': _seen.map((s) => s.name).toList(),+ });+ _saving = _saving.then((_) async {+ try {+ await storage?.write(key, data);+ } catch (_) {}+ });+ }++ Future<void> flush() => _saving;++ @override+ void dispose() {+ _disposed = true;+ super.dispose();+ }+}diff --git a/desktop/lib/widgets/harness_session_manager.dart b/desktop/lib/widgets/harness_session_manager.dartindex 0e893bd03..058c8450a 100644--- a/desktop/lib/widgets/harness_session_manager.dart+++ b/desktop/lib/widgets/harness_session_manager.dart@@ -25,12 +25,14 @@ class HarnessSessionManager extends StatefulWidget {required this.onClose,required this.onOpen,this.initialFilter = SessionFilter.all,+ this.introduction,});final AppNotifier app;final List<String> recent;final VoidCallback onClose;final Future<bool> Function(HarnessSession) onOpen;final SessionFilter initialFilter;+ final Widget? introduction;@overrideState<HarnessSessionManager> createState() => _HarnessSessionManagerState();@@ -278,10 +280,7 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {child: Row(children: [Expanded(- child: Text(- 'Harnesses',- style: AppType.heading(),- ),+ child: Text('Harnesses', style: AppType.heading()),),IconButton(tooltip: 'Close Harnesses',@@ -291,6 +290,7 @@ class _HarnessSessionManagerState extends State<HarnessSessionManager> {],),),+ if (widget.introduction != null) widget.introduction!,Padding(padding: const EdgeInsets.symmetric(horizontal: 16),child: TextField(diff --git a/desktop/lib/widgets/machines_panel.dart b/desktop/lib/widgets/machines_panel.dartindex a416a2a43..68f34d6c4 100644--- a/desktop/lib/widgets/machines_panel.dart+++ b/desktop/lib/widgets/machines_panel.dart@@ -12,6 +12,8 @@ import '../screens/login_screen.dart';import '../shared/theme/app_theme.dart' as grid;import '../shortcuts/app_keymap.dart';import '../state/app_state.dart';+import '../state/workspace_onboarding.dart';+import 'onboarding_card.dart';import '../terminal/terminal_text.dart';import 'box_chrome.dart' show ReadlineKeys;import 'link_another_machine_dialog.dart'@@ -49,6 +51,7 @@ MachinesPanelHandle openMachinesPanel(AppKeymap? keymap,String? initialMachineId,double toolbarHeight = 0,+ WorkspaceOnboarding? onboarding,}) {if (initialMachineId != null) notifier.revisitLinkPrompt(initialMachineId);final activeKeymap = keymap ?? KeymapTheme.of(context, listen: false);@@ -58,6 +61,7 @@ MachinesPanelHandle openMachinesPanel(builder: (context, constraints) {final panel = _MachinesPanel(notifier: notifier,+ onboarding: onboarding,initialMachineId: initialMachineId,onClose: () => handle.close(),onOpen: (id) => handle.close(destination: id, restoreFocus: false),@@ -146,6 +150,7 @@ class MachinesPanelHandle {class _MachinesPanel extends StatefulWidget {const _MachinesPanel({required this.notifier,+ this.onboarding,this.initialMachineId,required this.onClose,required this.onOpen,@@ -153,6 +158,7 @@ class _MachinesPanel extends StatefulWidget {required this.active,});final AppNotifier notifier;+ final WorkspaceOnboarding? onboarding;final String? initialMachineId;final VoidCallback onClose;final ValueChanged<String> onOpen;@@ -377,6 +383,97 @@ class _MachinesPanelState extends State<_MachinesPanel>}int _passwordRevision = 0;+ int _setupRequest = 0;+ bool _shareSetup = false;+ String? _onboardingConnect;++ Widget _introduction() {+ final receiving = !widget.onboarding!.completed(OnboardingStep.harnesses);+ final source = receiving+ ? _remotes.where((m) => !m.machine.isShared).firstOrNull+ : null;+ final local = app.localMachineState;+ final name = source?.machine.displayName;+ final offline = source?.nodeOnline == false;+ final linked =+ source != null &&+ !source.needsLink &&+ source.connectionStatus == ConnectionStatus.connected;+ return OnboardingCard(+ title: source == null+ ? 'Use your harnesses from another computer'+ : 'Use your harnesses here',+ description: source == null+ ? 'They keep running here. Open them on your other computer.'+ : offline+ ? 'Open Harness on $name, then check again.'+ : 'Connect to $name and open its existing harnesses.',+ action: app.isGuest+ ? 'Sign in'+ : source != null+ ? offline+ ? 'Check again'+ : linked+ ? 'Open harnesses'+ : 'Connect to $name'+ : 'Set up access',+ onAction: app.isGuest+ ? () => unawaited(_signIn())+ : offline+ ? () => unawaited(app.retryMachines())+ : source != null+ ? () {+ if (linked) {+ widget.onOpen(source.machine.machineId);+ } else {+ setState(() {+ _onboardingConnect = source.machine.machineId;+ _expandedMachine = source.machine.machineId;+ _focusMachine = source.machine.machineId;+ });+ }+ }+ : local == null+ ? null+ : () => setState(() {+ _shareSetup = true;+ _setupRequest++;+ }),+ onDismiss: () => widget.onboarding!.dismiss(OnboardingStep.machines),+ );+ }++ Widget _shareInstructions(MachineState local) {+ final name = local.machine.displayName;+ final email = app.currentUser?.email;+ return Padding(+ padding: const EdgeInsets.fromLTRB(46, 4, 16, 18),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ const Text('On your other computer'),+ const SizedBox(height: 8),+ _Detail(+ email == null+ ? '1. Open Harness and sign in with the same account.'+ : '1. Open Harness and sign in as $email.',+ ),+ const SizedBox(height: 6),+ _CopyButton('Copy download link', kHarnessDownloadUrl.toString()),+ const SizedBox(height: 8),+ _Detail(+ '2. Open Machines → Connect to $name. Enter the password you set here.',+ ),+ const SizedBox(height: 8),+ _Detail('Keep $name awake and Harness running.'),+ TextButton(+ onPressed: () => setState(() => _shareSetup = false),+ child: const Text('Hide setup steps'),+ ),+ ],+ ),+ );+ }Widget _actions(MachineState machine) => SizedBox(width: 32,@@ -530,6 +627,7 @@ class _MachinesPanelState extends State<_MachinesPanel>machine: machine,options: options,autofocus: _focusMachine == id,+ onLinked: _onboardingConnect == id ? () => widget.onOpen(id) : null,resources: _resources[id],onClose: widget.onClose,);@@ -590,6 +688,7 @@ class _MachinesPanelState extends State<_MachinesPanel>app: app,machine: machine,resources: _resources[machine.machine.machineId],+ setupRequest: _setupRequest,options: _actions(machine),onClose: widget.onClose,);@@ -647,7 +746,11 @@ class _MachinesPanelState extends State<_MachinesPanel>TerminalFontScope.watch(context);grid.AppTheme.watch(context);return ListenableBuilder(- listenable: Listenable.merge([app, terminalFontStore]),+ listenable: Listenable.merge([+ app,+ terminalFontStore,+ if (widget.onboarding != null) widget.onboarding!,+ ]),builder: (context, _) {final local = app.localMachineState;final remotes = _remotes;@@ -711,6 +814,11 @@ class _MachinesPanelState extends State<_MachinesPanel>],),),+ if (widget.onboarding?.next ==+ OnboardingStep.machines &&+ !_shareSetup &&+ _onboardingConnect == null)+ _introduction(),Divider(height: 1,color: grid.AppPalette.textPrimary.withValues(@@ -724,6 +832,8 @@ class _MachinesPanelState extends State<_MachinesPanel>crossAxisAlignment: CrossAxisAlignment.stretch,children: [_local(local),+ if (_shareSetup && local != null)+ _shareInstructions(local),if (!app.isGuest) ...[for (final machine in remotes)_remote(machine),@@ -971,6 +1081,8 @@ class _MachinePassword extends StatefulWidget {this.options,this.resources,this.autofocus = false,+ this.setupRequest = 0,+ this.onLinked,});final AppNotifier app;final MachineState machine;@@ -980,6 +1092,8 @@ class _MachinePassword extends StatefulWidget {String? get machineId =>machine.isLocalMachine ? null : machine.machine.machineId;final bool autofocus;+ final int setupRequest;+ final VoidCallback? onLinked;@overrideState<_MachinePassword> createState() => _MachinePasswordState();}@@ -1027,6 +1141,16 @@ class _MachinePasswordState extends State<_MachinePassword> {super.dispose();}+ @override+ void didUpdateWidget(covariant _MachinePassword oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (widget.setupRequest > oldWidget.setupRequest &&+ _status?.hasPassword == false &&+ !_busy) {+ _editPassword();+ }+ }+Future<void> _load() async {setState(() {_loading = true;@@ -1039,9 +1163,10 @@ class _MachinePasswordState extends State<_MachinePassword> {_error = status.error;if (status.error == null) {_status = status;- _editing = false;+ _editing = widget.setupRequest > 0 && !status.hasPassword;}});+ if (_editing) _editPassword();}Future<void> _finishPassword(Future<RemotePasswordStatus> request) async {@@ -1080,6 +1205,7 @@ class _MachinePasswordState extends State<_MachinePassword> {});if (error == null) {_password.clear();+ widget.onLinked?.call();} else {_input.requestFocus();}diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dartindex 806f41a91..c47588069 100644--- a/desktop/lib/widgets/new_harness_form.dart+++ b/desktop/lib/widgets/new_harness_form.dart@@ -452,6 +452,13 @@ class _NewHarnessFormState extends State<NewHarnessForm> {// Candidate navigation and confirmation belong to the input method. Keep// these keys out of both the picker and ancestor focus-traversal shortcuts.if (_isComposing()) return KeyEventResult.skipRemainingHandlers;+ if (event.logicalKey == LogicalKeyboardKey.keyR &&+ (HardwareKeyboard.instance.isMetaPressed ||+ HardwareKeyboard.instance.isControlPressed) &&+ box.canRefreshChoices) {+ if (event is KeyDownEvent) box.refreshChoices();+ return KeyEventResult.handled;+ }if (event.logicalKey == LogicalKeyboardKey.keyV &&(HardwareKeyboard.instance.isMetaPressed ||HardwareKeyboard.instance.isControlPressed)) {@@ -742,6 +749,14 @@ class _NewHarnessFormState extends State<NewHarnessForm> {),if (_hasChoices) ...[_searchBar(),+ if (box.choicesStatus case final status?)+ Padding(+ padding: const EdgeInsets.only(top: 12),+ child: Semantics(+ liveRegion: true,+ child: Text(status, style: _ink(kBoxFaint)),+ ),+ ),const SizedBox(height: 24),Flexible(child: SingleChildScrollView(child: _matchPane())),],@@ -778,7 +793,9 @@ class _NewHarnessFormState extends State<NewHarnessForm> {mainAxisSize: MainAxisSize.min,crossAxisAlignment: CrossAxisAlignment.stretch,children: [- if (shown.isEmpty && !_prompts.contains(box.field))+ if (shown.isEmpty &&+ !_prompts.contains(box.field) &&+ !box.refreshingChoices)Text('No matches', style: _ink(kBoxFaint)),for (var i = 0; i < shown.length; i++) ...[_matchRow(shown[i]),@@ -864,6 +881,17 @@ class _NewHarnessFormState extends State<NewHarnessForm> {),),),+ if (box.canRefreshChoices)+ IconButton(+ key: const ValueKey('new-harness-refresh'),+ tooltip: 'Refresh results',+ onPressed: box.refreshingChoices ? null : box.refreshChoices,+ icon: Icon(+ LucideIcons.refreshCw300,+ size: terminalFontStore.size,+ color: kBoxFaint,+ ),+ ),],),);diff --git a/desktop/lib/widgets/onboarding_card.dart b/desktop/lib/widgets/onboarding_card.dartnew file mode 100644index 000000000..0cf704951--- /dev/null+++ b/desktop/lib/widgets/onboarding_card.dart@@ -0,0 +1,64 @@+import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart';++/// One optional action inside a toolbar panel, never a modal or focus trap.+class OnboardingCard extends StatelessWidget {+ const OnboardingCard({+ super.key,+ required this.title,+ required this.description,+ required this.action,+ required this.onAction,+ required this.onDismiss,+ });+ final String title, description, action;+ final VoidCallback? onAction;+ final VoidCallback onDismiss;++ @override+ Widget build(BuildContext context) => Padding(+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 12),+ child: Container(+ width: double.infinity,+ padding: const EdgeInsets.fromLTRB(14, 10, 6, 12),+ decoration: BoxDecoration(+ color: AppPalette.textPrimary.withValues(alpha: .04),+ borderRadius: BorderRadius.circular(10),+ border: Border.all(+ color: AppPalette.textPrimary.withValues(alpha: .09),+ ),+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Expanded(+ child: Padding(+ padding: const EdgeInsets.only(top: 6),+ child: Text(title, style: AppType.label()),+ ),+ ),+ IconButton(+ tooltip: 'Dismiss suggestion',+ onPressed: onDismiss,+ visualDensity: VisualDensity.compact,+ icon: const Icon(Icons.close, size: 14),+ ),+ ],+ ),+ Padding(+ padding: const EdgeInsets.only(right: 8, bottom: 12),+ child: Text(+ description,+ style: AppType.body(color: AppPalette.textSecondary),+ ),+ ),+ FilledButton.tonal(onPressed: onAction, child: Text(action)),+ ],+ ),+ ),+ );+}diff --git a/desktop/lib/widgets/remote_folder_picker.dart b/desktop/lib/widgets/remote_folder_picker.dartindex adc60d5b8..126c99010 100644--- a/desktop/lib/widgets/remote_folder_picker.dart+++ b/desktop/lib/widgets/remote_folder_picker.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:math' as math;import '../terminal/terminal_text.dart';@@ -74,11 +75,12 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {String? _path, _requestedPath, _error;List<String> _entries = [];bool _loading = true, _truncated = false;+ bool get _blocking => _loading && (_path == null || _requestedPath != _path);int _request = 0, _edit = 0, _selected = -1;double _rowHeight = 36;bool get _canSelect =>- !_loading &&+ !_blocking &&_error == null &&_path != null &&_location.text.trim() == _path;@@ -116,7 +118,11 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {super.dispose();}- Future<void> _load(String? path, {String? highlight}) async {+ Future<void> _load(+ String? path, {+ String? highlight,+ bool refreshing = false,+ }) async {if (_loading && _request > 0 && path == _requestedPath) return;final request = ++_request;final edit = _edit;@@ -124,7 +130,7 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {_loading = true;_error = null;_requestedPath = path;- if (_location.text != (path ?? '')) {+ if (!refreshing && _location.text != (path ?? '')) {_location.text = path ?? '';_location.selection = TextSelection.collapsed(offset: _location.text.length,@@ -151,6 +157,9 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {});return;}+ final keep = refreshing && _selected >= 0 && _selected < _entries.length+ ? _entries[_selected]+ : highlight;setState(() {_loading = false;_path = resolved;@@ -165,10 +174,10 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {_truncated = result['truncated'] == true;_selected = _entries.isEmpty? -1- : math.max(0, _entries.indexOf(highlight ?? ''));+ : math.max(0, _entries.indexOf(keep ?? ''));// A reply may canonicalize a path, but must not replace a newer draft or// disturb a selection/caret when the field already contains that path.- if (edit == _edit && _location.text != resolved) {+ if (!refreshing && edit == _edit && _location.text != resolved) {_location.value = TextEditingValue(text: resolved,selection: TextSelection(@@ -183,6 +192,14 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {});}+ void _refresh() {+ if (_loading) return;+ final highlighted = _selected >= 0 && _selected < _entries.length+ ? _entries[_selected]+ : null;+ unawaited(_load(_path, highlight: highlighted, refreshing: true));+ }+void _openPath() {final path = _location.text.trim();if (path.isEmpty || (_loading && path == _requestedPath)) return;@@ -190,7 +207,7 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {}void _up() {- if (_loading) return;+ if (_blocking) return;final parent = _parentPath;if (parent != null) _load(parent, highlight: _paths.basename(_path!));}@@ -200,7 +217,7 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {}void _openSelected() {- if (!_loading && _selected >= 0 && _selected < _entries.length) {+ if (!_blocking && _selected >= 0 && _selected < _entries.length) {_load(_paths.join(_path!, _entries[_selected]));}}@@ -240,7 +257,7 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {key == LogicalKeyboardKey.arrowUp ||key == LogicalKeyboardKey.home ||key == LogicalKeyboardKey.end) {- if (!_loading && _entries.isNotEmpty) {+ if (!_blocking && _entries.isNotEmpty) {setState(() {_selected = switch (key) {LogicalKeyboardKey.home => 0,@@ -339,6 +356,8 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {includeRepeats: false,): _select,const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): _up,+ SingleActivator(LogicalKeyboardKey.keyR, meta: mac, control: !mac):+ _refresh,},child: AlertDialog(title: const Text('Choose a folder'),@@ -376,7 +395,7 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {!HardwareKeyboard.instance.isMetaPressed &&!HardwareKeyboard.instance.isShiftPressed &&_location.value.composing.isCollapsed &&- !_loading &&+ !_blocking &&_entries.isNotEmpty) {_foldersFocus.requestFocus();_revealSelection();@@ -433,11 +452,16 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {onPressed: () => _load(null),icon: const Icon(Icons.home_outlined, size: 18),),+ IconButton(+ tooltip: 'Refresh folders',+ onPressed: _loading ? null : _refresh,+ icon: const Icon(Icons.refresh, size: 18),+ ),IconButton(tooltip: mac? 'Up one folder (⌥↑)': 'Up one folder (Alt+↑)',- onPressed: _loading || _parentPath == null ? null : _up,+ onPressed: _blocking || _parentPath == null ? null : _up,icon: const Icon(Icons.arrow_upward, size: 18),),],@@ -461,7 +485,7 @@ class _RemoteFolderPickerDialogState extends State<_RemoteFolderPickerDialog> {),),clipBehavior: Clip.antiAlias,- child: _loading+ child: _blocking? const _FolderRowsSkeleton(): _entries.isEmpty? Center(diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex efd83805b..f8eef2acb 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -1282,6 +1282,7 @@ private final class SwarmStoreButton: SwarmIconButton {}private class SwarmNoticeButton: SwarmIconButton {+ var onboarding = false { didSet { needsDisplay = true } }var attention = 0 { didSet { contentTintColor = iconTint; needsDisplay = true } }var expanded = false { didSet { contentTintColor = iconTint; needsDisplay = true } }@@ -1320,6 +1321,14 @@ private class SwarmNoticeButton: SwarmIconButton {text.draw(at: NSPoint(x: badge.midX - size.width / 2, y: badge.midY - size.height / 2),withAttributes: attributes)}+ if onboarding {+ // A quiet next-step dot never replaces a red unread count.+ let offset: CGFloat = attention > 0 ? 19 : 3+ let y = isFlipped ? bounds.minY + offset : bounds.maxY - offset - 6+ NSColor(calibratedRed: 0.60, green: 0.76, blue: 0.93,+ alpha: isEnabled ? 1 : 0.45).setFill()+ NSBezierPath(ovalIn: NSRect(x: bounds.maxX - 7, y: y, width: 6, height: 6)).fill()+ }}}@@ -1560,6 +1569,17 @@ private final class SwarmTabStrip: NSView {? "Harnesses · \(unreadState) · \(attentionState)": "Harnesses · \(unreadState)"}+ let onboarding = state["onboarding"] as? String+ for (button, step, action) in [+ (machinesButton as SwarmNoticeButton, "machines", "Use your harnesses from another computer"),+ (modelsButton as SwarmNoticeButton, "models", "Power a harness with local AI"),+ (sessionsButton as SwarmNoticeButton, "harnesses", "Run your first harness"),+ ] {+ button.onboarding = onboarding == step+ if button.onboarding {+ button.setAccessibilityValue("\(button.accessibilityValue() as? String ?? ""), Suggested next step: \(action)")+ }+ }needsLayout = truelayoutSubtreeIfNeeded()if ids != previousOrder {diff --git a/desktop/test/git_worktree_failures_test.dart b/desktop/test/git_worktree_failures_test.dartindex 996f38ff5..0c8072bd4 100644--- a/desktop/test/git_worktree_failures_test.dart+++ b/desktop/test/git_worktree_failures_test.dart@@ -138,6 +138,34 @@ void main() {expect(process.signals, [ProcessSignal.sigkill]);});+ test('a stalled remote lookup times out and keeps saved branch choices', () async {+ final stalled = _GitProcess(code: null);+ final result = await readLocalGitProject(+ '/repo',+ refresh: true,+ startProcess: (arguments, environment) async {+ final command = arguments.skip(3).join(' ');+ if (command.startsWith('ls-remote')) return stalled;+ return _GitProcess(+ output: switch (command) {+ 'rev-parse --show-toplevel' => '/repo\n',+ 'rev-parse --git-common-dir' => '.git\n',+ 'remote' => 'origin\n',+ 'symbolic-ref --quiet HEAD' => 'refs/heads/main\n',+ 'for-each-ref --format=%(refname)%09%(refname:short)%09%(symref) refs/heads refs/remotes' => 'refs/heads/main\tmain\t\nrefs/remotes/origin/main\torigin/main\t\n',+ _ => '',+ },+ );+ },+ );+ expect(result['refreshed'], false);+ expect(+ GitProjectInfo.fromJson(result).branches.map((branch) => branch.name),+ ['main', 'origin/main'],+ );+ expect(stalled.signals, [ProcessSignal.sigkill]);+ });+test('failed worktree creation leaves its allocated folder for recovery',() async {diff --git a/desktop/test/git_worktree_test.dart b/desktop/test/git_worktree_test.dartindex be7f74f17..61dffda15 100644--- a/desktop/test/git_worktree_test.dart+++ b/desktop/test/git_worktree_test.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:io';import 'dart:math';@@ -73,6 +74,126 @@ void main() {},);+ test(+ 'discovers newly pushed branches without fetching until Start',+ () async {+ final remote = p.join(root.path, 'remote.git');+ final clone = p.join(root.path, 'other computer');+ await git(['clone', '--bare', repo, remote]);+ await git([+ 'clone',+ '--no-local',+ '--single-branch',+ '--branch',+ 'main',+ remote,+ clone,+ ]);+ await git(['remote', 'add', 'origin', remote]);+ await git(['switch', '-c', 'feat/toolbar-onboarding']);+ await File(p.join(repo, 'src/value')).writeAsString('new remote work');+ await git(['commit', '-am', 'new work']);+ await git(['push', 'origin', 'feat/toolbar-onboarding']);+ await File(p.join(clone, 'src/value'))+ .writeAsString('unsaved local work');+ final refs = await git(['show-ref'], clone);+ final saved = GitProjectInfo.fromJson(await readLocalGitProject(clone));+ expect(+ saved.branches.map((b) => b.name),+ isNot(contains('origin/feat/toolbar-onboarding')),+ );+ final data = await readLocalGitProject(clone, refresh: true);+ final fresh = GitProjectInfo.fromJson(data);+ expect(data['refreshed'], true);+ expect(+ fresh.branches.map((b) => b.name),+ contains('origin/feat/toolbar-onboarding'),+ );+ expect(+ await git(['show-ref'], clone),+ refs,+ reason: 'Looking up names must not download objects or write refs.',+ );+ expect(+ await File(p.join(clone, 'src/value')).readAsString(),+ 'unsaved local work',+ );+ final path = await worktree(+ folder: clone,+ ref: 'refs/remotes/origin/feat/toolbar-onboarding',+ name: 'feat/toolbar-onboarding',+ );+ expect(+ await File(p.join(path, 'src/value')).readAsString(),+ 'new remote work',+ );+ expect(await git(['branch', '--show-current'], clone), 'main');+ },+ );++ test('refresh coalesces requests for one repository and preserves offline choices', () async {+ final remote = p.join(root.path, 'remote.git');+ await git(['clone', '--bare', repo, remote]);+ await git(['remote', 'add', 'origin', remote]);+ final entered = Completer<void>();+ final release = Completer<void>();+ var lookups = 0;+ Future<Process> start(List<String> args, Map<String, String> env) async {+ if (args.contains('ls-remote')) {+ lookups++;+ if (!entered.isCompleted) entered.complete();+ await release.future;+ }+ return Process.start(+ 'git',+ args,+ environment: env,+ includeParentEnvironment: false,+ );+ }++ final first = readLocalGitProject(repo, refresh: true, startProcess: start);+ await entered.future;+ final second = readLocalGitProject(+ repo,+ refresh: true,+ startProcess: start,+ );+ await Future<void>.delayed(const Duration(milliseconds: 100));+ expect(lookups, 1);+ release.complete();+ final answers = await Future.wait([first, second]);+ expect(answers.every((answer) => answer['refreshed'] == true), true);+ await git([+ 'remote',+ 'set-url',+ 'origin',+ p.join(root.path, 'missing.git'),+ ]);+ final offline = await readLocalGitProject(repo, refresh: true);+ expect(offline['refreshed'], false);+ expect(+ GitProjectInfo.fromJson(offline).branches.map((b) => b.name),+ contains('origin/feature'),+ );+ });++ test('successful refresh removes deleted remote choices and keeps local branches', () async {+ final remote = p.join(root.path, 'remote.git');+ await git(['clone', '--bare', repo, remote]);+ await git(['remote', 'add', 'origin', remote]);+ await git(['branch', '-D', 'feature'], remote);+ final info = GitProjectInfo.fromJson(+ await readLocalGitProject(repo, refresh: true),+ );+ expect(info.branches.map((b) => b.name), contains('feature'));+ expect(info.branches.map((b) => b.name), isNot(contains('origin/feature')));+ expect(+ await git(['show-ref', '--verify', 'refs/remotes/origin/feature']),+ isNotEmpty,+ );+ });+test('concurrent worktrees use the selected ref, new branches, and preserve dirty source files', () async {await File(p.join(repo, 'src', 'value')).writeAsString('keep my work');final paths = await Future.wait([diff --git a/desktop/test/machines_manager_test.dart b/desktop/test/machines_manager_test.dartindex f6d2d0241..20c95b946 100644--- a/desktop/test/machines_manager_test.dart+++ b/desktop/test/machines_manager_test.dart@@ -112,6 +112,8 @@ void main() {expect(badge('models').isLabelVisible, isFalse);await tester.tap(find.byKey(const ValueKey('swarm-models-button')));await tester.pumpAndSettle();+ await tester.tap(find.textContaining('Local').first);+ await tester.pumpAndSettle();expect(find.text('New'), findsOneWidget);await tester.pumpWidget(const SizedBox());app.dispose();diff --git a/desktop/test/models_panel_test.dart b/desktop/test/models_panel_test.dartindex 1a43ec4b6..1c7d0eb56 100644--- a/desktop/test/models_panel_test.dart+++ b/desktop/test/models_panel_test.dart@@ -680,8 +680,10 @@ void main() {app.modelManager.start();await app.modelManager.refresh();await tester.pump();- expect(find.text('Explore models'), findsOneWidget);- await tester.tap(find.text('Explore models'));+ expect(find.text('Explore models'), findsNothing);+ await tester.tap(button);+ await tester.pump();+ await tester.tap(find.textContaining('Local').first);await tester.pump();expect(find.text('Qwen3.8-27B'), findsOneWidget);expect(find.text('Search models…'), findsOneWidget);diff --git a/desktop/test/new_harness_git_test.dart b/desktop/test/new_harness_git_test.dartindex 929eb569a..71ba7bd94 100644--- a/desktop/test/new_harness_git_test.dart+++ b/desktop/test/new_harness_git_test.dart@@ -44,6 +44,8 @@ class _Connection extends WsConn {);final starts = <Map<String, dynamic>>[];final reads = <String>[];+ final refreshes = <String>[];+ Completer<Map<String, dynamic>>? refreshing;final pending = <String, Completer<Map<String, dynamic>>>{};final answers = <String, Map<String, dynamic>>{};Map<String, dynamic>? failure;@@ -57,6 +59,11 @@ class _Connection extends WsConn {}) async {if (type == 'git_project_info') {final path = payload['path'] as String;+ if (payload['refresh'] == true) {+ refreshes.add(path);+ return refreshing?.future ??+ Future.value({..._git, ...?answers[path], 'refreshed': true});+ }reads.add(path);if (gitFailures > 0) {gitFailures--;@@ -115,6 +122,221 @@ void main() {Future<void> settle() => Future<void>.delayed(Duration.zero);+ test('Branch opens immediately, discovers remote matches, and never queries on typing', () async {+ final connection = _Connection()..refreshing = Completer();+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ box.focusField(NewHarnessField.branch);+ expect(box.refreshingBranches, true);+ expect(box.checkingGit, false);+ expect(box.options.any((row) => row.title == 'feature'), true);+ for (final query in ['t', 'to', 'toolbar']) {+ box.setQuery(query);+ }+ expect(connection.refreshes, ['/repo']);+ expect(+ box.options.any(+ (row) => row.id.startsWith(NewHarnessController.createBranchId),+ ),+ false,+ );+ connection.refreshing!.complete({+ ..._git,+ 'refreshed': true,+ 'branches': [+ ..._git['branches'] as List,+ {+ 'ref': 'refs/remotes/origin/feat/toolbar-onboarding',+ 'name': 'origin/feat/toolbar-onboarding',+ 'remote': true,+ },+ ],+ });+ await settle();+ expect(box.query, 'toolbar');+ expect(box.selected!.title, 'origin/feat/toolbar-onboarding');+ expect(box.refreshingBranches, false);+ expect(box.branchRefreshError, isNull);+ box.accept();+ expect(+ box.projectFolderRequest!.payload['branchRef'],+ 'refs/remotes/origin/feat/toolbar-onboarding',+ );+ expect(connection.starts, isEmpty);+ });++ test('failed branch refresh preserves usable choices and manual retry keeps the query', () async {+ final connection = _Connection()..refreshing = Completer();+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ box.focusField(NewHarnessField.branch);+ box.setQuery('feature');+ connection.refreshing!.completeError(StateError('offline'));+ await settle();+ expect(box.selected!.title, 'feature');+ expect(box.branchRefreshError, contains('Showing saved branches'));+ expect(box.gitError, isNull);+ connection.refreshing = Completer();+ box.refreshChoices();+ box.refreshChoices();+ expect(connection.refreshes, ['/repo', '/repo']);+ connection.refreshing!.complete({..._git, 'refreshed': true});+ await settle();+ expect(box.query, 'feature');+ expect(box.selected!.title, 'feature');+ expect(box.branchRefreshError, isNull);+ });++ test('filtering 2000 branches stays local during a slow refresh', () async {+ final connection = _Connection()+ ..refreshing = Completer()+ ..answers['/repo'] = {+ ..._git,+ 'branches': [+ for (var i = 0; i < 2000; i++)+ {+ 'ref': 'refs/remotes/origin/feature/$i',+ 'name': 'origin/feature/$i',+ 'remote': true,+ },+ ],+ };+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ box.focusField(NewHarnessField.branch);+ final timings = <int>[];+ for (var i = 0; i < 100; i++) {+ final watch = Stopwatch()..start();+ box.setQuery('feature/$i');+ timings.add(watch.elapsedMicroseconds);+ }+ timings.sort();+ // A diagnostic, not a flaky wall-clock threshold on a shared build machine.+ debugPrint(+ 'Branch search / 2000 refs / 100 queries: p50=${timings[50]}us p95=${timings[95]}us',+ );+ expect(connection.reads, ['/repo']);+ expect(connection.refreshes, ['/repo']);+ connection.refreshing!.complete({+ ...connection.answers['/repo']!,+ 'refreshed': true,+ });+ await settle();+ });++ test('a late refresh from another project is discarded', () async {+ final connection = _Connection()..refreshing = Completer();+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ box.focusField(NewHarnessField.branch);+ box.setFolder('/plain');+ await settle();+ connection.refreshing!.complete({..._git, 'refreshed': true});+ await settle();+ expect(box.project.folder, '/plain');+ expect(box.isGitProject, false);+ expect(box.refreshingBranches, false);+ });++ testWidgets(+ 'Branch shows refresh progress and manual refresh keeps the typed query',+ (tester) async {+ final connection = _Connection()..refreshing = Completer();+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await tester.binding.setSurfaceSize(const Size(1200, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: NewHarnessForm(+ controller: box,+ onClose: () {},+ onCreated: () {},+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('new-harness-field-branch')));+ await tester.pump();+ await tester.enterText(+ find.byKey(const ValueKey('new-harness-query')),+ 'toolbar',+ );+ await tester.pump();+ expect(find.text('Checking remote branches…'), findsOneWidget);+ expect(find.text('No matches'), findsNothing);+ connection.refreshing!.complete({..._git, 'refreshed': false});+ await tester.pumpAndSettle();+ expect(find.textContaining('Showing saved branches'), findsOneWidget);+ connection.refreshing = Completer();+ await tester.tap(find.byTooltip('Refresh results'));+ await tester.pump();+ expect(box.query, 'toolbar');+ expect(connection.refreshes, ['/repo', '/repo']);+ connection.refreshing!.complete({..._git, 'refreshed': true});+ await tester.pumpAndSettle();+ expect(find.textContaining('Showing saved branches'), findsNothing);+ for (final modifier in [+ LogicalKeyboardKey.metaLeft,+ LogicalKeyboardKey.controlLeft,+ ]) {+ final previous = connection.refreshes.length;+ connection.refreshing = Completer();+ await tester.tap(find.byKey(const ValueKey('new-harness-query')));+ await tester.sendKeyDownEvent(modifier);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyR);+ await tester.sendKeyUpEvent(modifier);+ await tester.pump();+ expect(connection.refreshes.length, previous + 1);+ expect(box.query, 'toolbar');+ connection.refreshing!.complete({..._git, 'refreshed': true});+ await tester.pumpAndSettle();+ }+ await tester.pumpWidget(const SizedBox());+ },+ );+test('failed Git discovery blocks launch and the next Start retries it',() async {@@ -463,6 +685,60 @@ void main() {],};+ test('search finds remote-qualified and older Harness branches', () async {+ final connection = _Connection()..answers['/repo'] = rich;+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ box.focusField(NewHarnessField.branch);+ await settle();+ for (final name in ['origin/main', 'harness/old']) {+ box.setQuery(name);+ expect(box.options.first.title, name);+ expect(box.options.first.enabled, true);+ expect(box.options.where((row) => row.synthetic), isEmpty);+ }+ box.setQuery('');+ expect(+ box.options.map((row) => row.title),+ isNot(anyOf(contains('origin/main'), contains('harness/old'))),+ );+ });++ test('a hidden local branch does not hide its remote counterpart', () async {+ final connection = _Connection()+ ..answers['/repo'] = {+ ...rich,+ 'branches': [+ ...rich['branches'] as List,+ {+ 'ref': 'refs/remotes/origin/harness/old',+ 'name': 'origin/harness/old',+ 'remote': true,+ },+ ],+ };+ final app = createApp(connectionForTest: (_) => connection);+ final box = NewHarnessController(+ app,+ machineId: 'm',+ engine: 'codex',+ folder: '/repo',+ );+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ await settle();+ box.focusField(NewHarnessField.branch);+ expect(box.options.map((row) => row.title), contains('origin/harness/old'));+ });+test('From is where new work starts; Branch is the branch it is on',() async {@@ -552,6 +828,7 @@ void main() {// A name no branch has: a new branch in a new worktree, from the default.box.focusField(NewHarnessField.branch);box.setQuery('my work');+ await settle();expect(box.options.last.title, 'Create branch my-work');expect(box.options.last.detail, 'New branch from main');box.accept(box.options.last);@@ -613,6 +890,7 @@ void main() {reason: 'It exists: pick it instead.',);box.setQuery('login fix');+ await settle();expect(box.options.last.title, 'Create branch login-fix');expect(box.options.last.detail, 'New branch from main');box.accept(box.options.last);@@ -652,6 +930,7 @@ void main() {await settle();box.focusField(NewHarnessField.branch);box.setQuery('john smith');+ await settle();expect(box.options.last.title, 'Create branch john-smith');box.setQuery('fix: it');box.accept(box.options.last);diff --git a/desktop/test/new_harness_project_context_test.dart b/desktop/test/new_harness_project_context_test.dartindex bb2e3d10a..9374ef1e5 100644--- a/desktop/test/new_harness_project_context_test.dart+++ b/desktop/test/new_harness_project_context_test.dart@@ -28,6 +28,7 @@ class _Folders extends WsConn {final paths = <String?>[];Completer<Map<String, dynamic>>? pendingHome;+ final pending = <String, Completer<Map<String, dynamic>>>{};@overrideFuture<Map<String, dynamic>> request(@@ -40,6 +41,7 @@ class _Folders extends WsConn {if (type != 'fs_list_dir') throw StateError('Unexpected request: $type');final path = payload['path'] as String?;paths.add(path);+ if (pending[path] case final reply?) return reply.future;if (path == null && pendingHome != null) return pendingHome!.future;return {'path': path ?? '/home/$machineId',@@ -56,6 +58,102 @@ class _Folders extends WsConn {void main() {final input = find.byKey(const ValueKey('new-harness-input'));+ testWidgets(+ 'remote folders refresh on revisit, retain matches, and never read on each keystroke',+ (tester) async {+ final folders = _Folders('m');+ final app = createApp(connectionForTest: (_) => folders);+ final box = NewHarnessController(app, machineId: 'm', engine: 'codex');+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ box.focusField(NewHarnessField.project);+ box.setQuery('/home/m/work/pa');+ await tester.pump(const Duration(milliseconds: 100));+ await tester.pump();+ expect(box.options.any((row) => row.title == 'payments'), true);+ final firstReads = folders.paths+ .where((path) => path == '/home/m/work')+ .length;+ for (final query in ['pay', 'paym', 'payments']) {+ box.setQuery('/home/m/work/$query');+ }+ await tester.pump(const Duration(milliseconds: 100));+ expect(+ folders.paths.where((path) => path == '/home/m/work').length,+ firstReads,+ );+ final reply = folders.pending['/home/m/work'] = Completer();+ box.focusField(NewHarnessField.projectMenu);+ box.focusField(NewHarnessField.project);+ box.setQuery('/home/m/work/pay');+ expect(box.options.any((row) => row.title == 'payments'), true);+ await tester.pump(const Duration(milliseconds: 100));+ expect(+ folders.paths.where((path) => path == '/home/m/work').length,+ firstReads + 1,+ );+ reply.complete({+ 'path': '/home/m/work',+ 'entries': [+ {'name': 'payments', 'isDir': true},+ {'name': 'payments-api', 'isDir': true},+ ],+ });+ await tester.pump();+ expect(box.query, '/home/m/work/pay');+ expect(box.selected!.title, 'payments');+ expect(box.options.any((row) => row.title == 'payments-api'), true);+ final failed = folders.pending['/home/m/work'] = Completer();+ box.refreshChoices();+ await tester.pump(const Duration(milliseconds: 100));+ failed.complete({'error': 'UNREACHABLE'});+ await tester.pump();+ expect(box.options.any((row) => row.title == 'payments-api'), true);+ expect(box.choicesStatus, contains('Couldn’t refresh folders'));+ box.setQuery('');+ expect(box.canRefreshChoices, false);+ expect(box.choicesStatus, isNull);+ },+ );++ testWidgets('new project names refresh their parent folder on revisit', (+ tester,+ ) async {+ final folders = _Folders('m');+ final app = createApp(connectionForTest: (_) => folders);+ final box = NewHarnessController(app, machineId: 'm', engine: 'codex');+ addTearDown(app.dispose);+ addTearDown(box.dispose);+ box.focusField(NewHarnessField.projectName);+ box.setQuery('toolbar');+ await tester.pump(const Duration(milliseconds: 100));+ await tester.pump(const Duration(milliseconds: 100));+ expect(box.options.single.title, 'Create toolbar');+ final firstReads = folders.paths+ .where((path) => path == '/home/m/harnesses')+ .length;+ final reply = folders.pending['/home/m/harnesses'] = Completer();+ box.focusField(NewHarnessField.projectMenu);+ box.focusField(NewHarnessField.projectName);+ for (final name in ['tool', 'toolba', 'toolbar']) {+ box.setQuery(name);+ }+ await tester.pump(const Duration(milliseconds: 100));+ expect(+ folders.paths.where((path) => path == '/home/m/harnesses').length,+ firstReads + 1,+ );+ reply.complete({+ 'path': '/home/m/harnesses',+ 'entries': [+ {'name': 'toolbar', 'isDir': true},+ ],+ });+ await tester.pump();+ expect(box.query, 'toolbar');+ expect(box.options.single.title, 'Open existing toolbar');+ });+Future<void> mount(WidgetTester tester, NewHarnessController box) async {await tester.pumpWidget(MaterialApp(diff --git a/desktop/test/remote_folder_picker_test.dart b/desktop/test/remote_folder_picker_test.dartindex c388f218e..c6b10126f 100644--- a/desktop/test/remote_folder_picker_test.dart+++ b/desktop/test/remote_folder_picker_test.dart@@ -123,6 +123,45 @@ Future<void> _open(}void main() {+ testWidgets(+ 'refresh keeps current folders usable and preserves a newer path draft',+ (tester) async {+ final app = _Folders();+ await _open(tester, app);+ app.requests.single.reply.complete(_listing('/home/dev', ['code']));+ await tester.pumpAndSettle();+ final field = find.byType(TextField);+ await tester.enterText(field, '/home/dev/new-project');+ await tester.tap(find.byTooltip('Refresh folders'));+ await tester.pump();+ expect(app.requests.last.path, '/home/dev');+ expect(find.text('code'), findsOneWidget);+ expect(+ tester.widget<TextField>(field).controller!.text,+ '/home/dev/new-project',+ );+ app.requests.last.reply.complete(+ _listing('/home/dev', ['code', 'new-project']),+ );+ await tester.pumpAndSettle();+ expect(find.text('new-project'), findsOneWidget);+ expect(+ tester.widget<TextField>(field).controller!.text,+ '/home/dev/new-project',+ );+ final previous = app.requests.length;+ await tester.tap(field);+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyR);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.pump();+ expect(app.requests.length, previous + 1);+ expect(app.requests.last.path, '/home/dev');+ app.requests.last.reply.complete(_listing('/home/dev', ['code']));+ await tester.pumpAndSettle();+ },+ );+testWidgets('cannot select the old folder while opening another folder', (tester,) async {diff --git a/desktop/test/swarm_search_identity_test.dart b/desktop/test/swarm_search_identity_test.dartindex c5729a995..586557461 100644--- a/desktop/test/swarm_search_identity_test.dart+++ b/desktop/test/swarm_search_identity_test.dart@@ -14,6 +14,49 @@ import 'swarm_screen_test.dart' show mount, terminal;import 'swarm_state_test.dart' show createApp;void main() {+ test('Open Harness picks up changed branch metadata without fetching Git', () {+ final app = createApp();+ var gitReads = 0;+ app.gitProjectReaderForTest = (_, _) async {+ gitReads++;+ return {'isGit': false};+ };+ final machine = app.machineStates['m']!;+ machine.agents = const [+ Agent(+ id: 'work',+ name: 'Review work',+ engine: 'codex',+ terminalAvailable: true,+ project: AgentProject(name: 'app', cwd: '/work/app', branch: 'main'),+ ),+ ];+ final search = SwarmSearchController(app, []);+ addTearDown(app.dispose);+ addTearDown(search.dispose);+ search.setQuery('toolbar');+ expect(search.rows.where((row) => row.agentId == 'work'), isEmpty);+ machine.agents = const [+ Agent(+ id: 'work',+ name: 'Review work',+ engine: 'codex',+ terminalAvailable: true,+ project: AgentProject(+ name: 'app',+ cwd: '/work/app',+ branch: 'feat/toolbar-onboarding',+ ),+ ),+ ];+ // Simulate the same inventory notification delivered by the remote machine.+ // ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member+ app.notifyListeners();+ expect(search.query, 'toolbar');+ expect(search.rows.where((row) => row.agentId == 'work'), hasLength(1));+ expect(gitReads, 0);+ });+test('single-harness tabs collapse by identity and keep their names searchable',() async {diff --git a/desktop/test/toolbar_onboarding_test.dart b/desktop/test/toolbar_onboarding_test.dartnew file mode 100644index 000000000..f26e87787--- /dev/null+++ b/desktop/test/toolbar_onboarding_test.dart@@ -0,0 +1,268 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/cli_link.dart';+import 'package:harness/core/models.dart';+import 'package:harness/models/models_panel.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/state/new_harness.dart';+import 'package:harness/state/workspace_onboarding.dart';+import 'package:harness/widgets/new_harness_form.dart';+import 'package:harness/widgets/onboarding_card.dart';++import 'keymap_host_test.dart' show key;+import 'support/model_manager.dart';+import 'swarm_screen_test.dart' show terminal;++class _App extends ModelManagerTestApp {+ _App() : super(ModelManagerConnection()) {+ currentUser = const CurrentUserProfile(email: '[email protected]');+ machineStates.remove('other');+ machines = [stateOf('m')!.machine];+ stateOf('m')!.nodeOnline = true;+ }+ String? password;+ int refreshes = 0;+ final connections = <String>[];+ @override+ Future<void> retryMachines() async {+ refreshes++;+ }++ @override+ Future<RemotePasswordStatus> remotePasswordStatus() async =>+ RemotePasswordStatus(hasPassword: password != null);+ @override+ Future<RemotePasswordSetResult> setRemotePassword(String value) async {+ password = value;+ return const RemotePasswordSetResult();+ }++ @override+ Future<String?> connectWithPassword(+ String id,+ String value, {+ void Function(String stage)? onProgress,+ }) async {+ if (value != '123456') return 'Incorrect password. Try again.';+ connections.add(id);+ stateOf(id)!+ ..needsLink = false+ ..connectionStatus = ConnectionStatus.connected;+ notifyListeners();+ return null;+ }+}++void main() {+ late _App app;+ late WorkspaceOnboarding journey;+ setUp(() {+ final previous = newHarnessOpensInBox;+ newHarnessOpensInBox = true;+ addTearDown(() => newHarnessOpensInBox = previous);+ app = _App();+ });+ tearDown(() {+ app.dispose();+ journey.dispose();+ });+ Future<void> mount(WidgetTester tester) async {+ journey = WorkspaceOnboarding();+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1280, 800);+ addTearDown(tester.view.reset);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: SwarmScreen(+ notifier: app,+ nativeTabs: false,+ onboarding: journey,+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ Future<void> tap(WidgetTester tester, Finder finder) async {+ await tester.tap(finder);+ await tester.pumpAndSettle();+ }++ void localHarness() {+ app.stateOf('m')!.agents = const [+ Agent(+ id: 'work',+ name: 'My project',+ engine: 'codex',+ terminalAvailable: true,+ ),+ ];+ app.adoptSessionForTest(terminal('work', []));+ }++ testWidgets(+ 'first invitation opens real creation and survives merely viewing',+ (tester) async {+ await mount(tester);+ expect(+ find.byKey(const ValueKey('onboarding-harnesses-dot')),+ findsOneWidget,+ );+ await tap(tester, find.byTooltip('Harnesses'));+ expect(find.text('Run your first harness'), findsOneWidget);+ expect(journey.completed(OnboardingStep.harnesses), isFalse);+ expect(+ find.byKey(const ValueKey('onboarding-harnesses-dot')),+ findsNothing,+ );+ await key(tester, LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ await tap(tester, find.byTooltip('Harnesses'));+ await tap(tester, find.text('New harness'));+ expect(find.byKey(const ValueKey('session-manager')), findsNothing);+ expect(find.byType(NewHarnessForm), findsOneWidget);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ },+ );++ for (final hasPassword in [false, true]) {+ testWidgets(+ 'Machines guides access to existing work (password=$hasPassword)',+ (tester) async {+ localHarness();+ if (hasPassword) app.password = '123456';+ await mount(tester);+ expect(journey.next, OnboardingStep.machines);+ await tap(tester, find.byKey(const ValueKey('swarm-machines-button')));+ await tap(tester, find.text('Set up access'));+ expect(find.text('On your other computer'), findsOneWidget);+ expect(find.textContaining('Connect to This Mac.'), findsOneWidget);+ if (!hasPassword) {+ final field = find.byType(TextField);+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);+ await tester.enterText(field, '123456');+ await tap(tester, find.text('Save'));+ }+ expect(app.password, '123456');+ expect(find.text('Change password'), findsOneWidget);+ expect(journey.completed(OnboardingStep.machines), isFalse);+ await tester.pumpWidget(const SizedBox());+ },+ );+ }++ testWidgets('second computer connects then opens only the source harnesses', (+ tester,+ ) async {+ const source = Machine(+ machineId: 'source',+ name: 'M2',+ authMode: MachineAuthMode.remote,+ );+ app.machineStates['source'] = MachineState(source)+ ..nodeOnline = true+ ..needsLink = true+ ..agents = const [+ Agent(+ id: 'existing',+ name: 'Existing work',+ engine: 'codex',+ terminalAvailable: true,+ ),+ ];+ app.machines = [...app.machines, source];+ app.stateOf('m')!.agents = const [+ Agent(id: 'unrelated', name: 'Work on this computer', engine: 'codex'),+ ];+ await mount(tester);+ expect(journey.next, OnboardingStep.machines);+ await tap(tester, find.byKey(const ValueKey('swarm-machines-button')));+ await tap(tester, find.text('Connect to M2'));+ final field = find.descendant(+ of: find.byKey(const ValueKey('machines-panel')),+ matching: find.byType(TextField),+ );+ await tester.enterText(field, 'wrong');+ await tap(tester, find.text('Connect'));+ expect(find.text('Incorrect password. Try again.'), findsOneWidget);+ await tester.enterText(field, '123456');+ await tap(tester, find.text('Connect'));+ expect(app.connections, ['source']);+ expect(find.byKey(const ValueKey('machines-panel')), findsNothing);+ expect(find.text('Harnesses · M2'), findsOneWidget);+ expect(find.text('Existing work'), findsWidgets);+ expect(find.text('Work on this computer'), findsNothing);+ expect(journey.completed(OnboardingStep.machines), isFalse);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets(+ 'an offline source offers recovery before asking for its password',+ (tester) async {+ const source = Machine(+ machineId: 'source',+ name: 'M2',+ authMode: MachineAuthMode.remote,+ );+ app.machineStates['source'] = MachineState(source)+ ..nodeOnline = false+ ..needsLink = true;+ app.machines = [...app.machines, source];+ await mount(tester);+ expect(journey.next, OnboardingStep.machines);+ await tap(tester, find.byKey(const ValueKey('swarm-machines-button')));+ expect(+ find.text('Open Harness on M2, then check again.'),+ findsOneWidget,+ );+ expect(find.text('Set up access'), findsNothing);+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('machines-panel')),+ matching: find.byType(TextField),+ ),+ findsNothing,+ );+ await tap(tester, find.text('Check again'));+ expect(app.refreshes, 1);+ app.stateOf('source')!.nodeOnline = true;+ app.notifyListeners();+ await tester.pumpAndSettle();+ expect(find.text('Connect to M2'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets(+ 'skipping Machines offers Models; explore selects Local without starting a download',+ (tester) async {+ localHarness();+ await app.modelManager.refresh();+ await mount(tester);+ await tap(tester, find.byKey(const ValueKey('swarm-machines-button')));+ await tap(tester, find.byTooltip('Dismiss suggestion'));+ expect(journey.next, OnboardingStep.models);+ expect(+ find.byKey(const ValueKey('onboarding-models-dot')),+ findsOneWidget,+ );+ await tap(tester, find.byKey(const ValueKey('swarm-models-button')));+ expect(find.byType(ModelsPanel), findsOneWidget);+ expect(find.byType(OnboardingCard), findsOneWidget);+ expect(find.text('Power a harness with local AI'), findsOneWidget);+ await tap(tester, find.text('Explore local models'));+ expect(find.text('Qwen3.8-27B'), findsOneWidget);+ expect(app.actions, isEmpty);+ expect(journey.completed(OnboardingStep.models), isFalse);+ expect(app.panes.single.agentId, 'work');+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ },+ );+}diff --git a/desktop/test/workspace_onboarding_test.dart b/desktop/test/workspace_onboarding_test.dartnew file mode 100644index 000000000..2884f0265--- /dev/null+++ b/desktop/test/workspace_onboarding_test.dart@@ -0,0 +1,183 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/state/workspace_onboarding.dart';++import 'swarm_state_test.dart' show MemoryStore;++class _HeldStore extends MemoryStore {+ final reads = <String, Completer<String?>>{};+ @override+ Future<String?> read(String key) =>+ (reads[key] = Completer<String?>()).future;+}++class _BrokenStore implements LocalKeyValueStore {+ @override+ Future<String?> read(String key) async => throw StateError('unavailable');+ @override+ Future<void> write(String key, String value) async =>+ throw StateError('full');+ @override+ Future<void> delete(String key) async {}+}++void main() {+ const first = OnboardingStep.harnesses;+ const second = OnboardingStep.machines;+ const third = OnboardingStep.models;+ Future<void> sync(+ WorkspaceOnboarding journey, {+ String scope = 'a',+ Set<OnboardingStep> observed = const {},+ bool other = false,+ bool models = true,+ }) async {+ journey.sync(+ scope: scope,+ observed: observed,+ otherComputer: other,+ modelsAvailable: models,+ );+ await Future<void>.delayed(Duration.zero);+ }++ test('one next step; viewing a panel does not complete it', () async {+ final store = MemoryStore();+ final journey = WorkspaceOnboarding(storage: store);+ addTearDown(journey.dispose);+ await sync(journey);+ expect(journey.next, first);+ expect(journey.showsDot(first), isTrue);+ journey.acknowledge(second);+ expect(journey.showsDot(first), isTrue);+ journey.acknowledge(first);+ expect(journey.next, first);+ expect(journey.showsDot(first), isFalse);+ await journey.flush();+ final reopened = WorkspaceOnboarding(storage: store);+ addTearDown(reopened.dispose);+ await sync(reopened);+ expect(reopened.next, first);+ expect(reopened.showsDot(first), isFalse);+ await sync(journey, observed: {first});+ expect(journey.next, second);+ expect(journey.showsDot(second), isTrue);+ await sync(journey); // Closing work never undoes the first success.+ expect(journey.next, second);+ await sync(journey, observed: {second});+ expect(journey.next, third);+ journey.acknowledge(third);+ expect(journey.completed(third), isFalse);+ await sync(journey, observed: {third});+ expect(journey.next, isNull);+ await journey.flush();+ final finished = WorkspaceOnboarding(storage: store);+ addTearDown(finished.dispose);+ await sync(finished);+ expect(finished.next, isNull);+ });++ test('the second computer leads with existing work, not new setup', () async {+ final journey = WorkspaceOnboarding();+ addTearDown(journey.dispose);+ await sync(journey, other: true);+ expect(journey.next, second);+ expect(journey.completed(first), isFalse);+ // Discovery is not access. A usable remote harness is the milestone.+ expect(journey.completed(second), isFalse);+ await sync(journey, observed: {second}, other: true);+ expect(journey.completed(first), isTrue);+ expect(journey.next, third);+ });++ test(+ 'skip another computer and try local AI without a false completion',+ () async {+ final journey = WorkspaceOnboarding(storage: MemoryStore());+ addTearDown(journey.dispose);+ await sync(journey, observed: {first}, models: false);+ journey.dismiss(second);+ expect(journey.next, isNull);+ expect(journey.completed(second), isFalse);+ await sync(journey, models: true);+ expect(journey.next, third);+ journey.dismiss(third);+ expect(journey.next, isNull);+ await sync(journey);+ expect(journey.next, isNull);+ },+ );++ test(+ 'dismissing first-use waits for actual work before offering next step',+ () async {+ final journey = WorkspaceOnboarding();+ addTearDown(journey.dispose);+ await sync(journey);+ journey.dismiss(first);+ expect(journey.next, isNull);+ await sync(journey, observed: {first});+ expect(journey.next, second);+ },+ );++ test('preferences and milestones stay isolated across accounts', () async {+ final journey = WorkspaceOnboarding(storage: MemoryStore());+ addTearDown(journey.dispose);+ await sync(journey, observed: {first});+ journey.dismiss(second);+ await sync(journey, scope: 'b');+ expect(journey.next, first);+ expect(journey.completed(first), isFalse);+ await sync(journey, scope: 'a');+ expect(journey.next, third);+ });++ test('late preferences cannot overwrite the new account', () async {+ final store = _HeldStore();+ final journey = WorkspaceOnboarding(storage: store);+ addTearDown(journey.dispose);+ await sync(journey);+ await sync(journey, scope: 'b');+ store.reads[WorkspaceOnboarding.storageKey('a')]!.complete(+ '{"completed":["harnesses","machines","models"]}',+ );+ store.reads[WorkspaceOnboarding.storageKey('b')]!.complete(null);+ await Future<void>.delayed(Duration.zero);+ expect(journey.next, first);+ });++ test('unavailable and corrupt preferences do not block onboarding', () async {+ for (final store in <LocalKeyValueStore>[+ _BrokenStore(),+ MemoryStore()..values[WorkspaceOnboarding.storageKey('a')] = 'invalid',+ MemoryStore()+ ..values[WorkspaceOnboarding.storageKey('a')] =+ '{"completed":["unknown"],"seen":123}',+ ]) {+ final journey = WorkspaceOnboarding(storage: store);+ await sync(journey);+ expect(journey.next, first);+ journey.dismiss(first);+ await journey.flush();+ journey.dispose();+ }+ });++ test('disposing while preferences load is safe', () async {+ final store = _HeldStore();+ final journey = WorkspaceOnboarding(storage: store);+ await sync(journey);+ journey.dispose();+ store.reads.values.single.complete(null);+ await Future<void>.delayed(Duration.zero);+ journey.sync(+ scope: 'b',+ observed: {},+ otherComputer: false,+ modelsAvailable: false,+ );+ });+}diff --git a/desktop/tool/machines_preview.dart b/desktop/tool/machines_preview.dartindex de79d698e..7d15e28ca 100644--- a/desktop/tool/machines_preview.dart+++ b/desktop/tool/machines_preview.dart@@ -202,6 +202,9 @@ class _App extends AppNotifier {}}+/// Shared disposable fixture for toolbar/onboarding reviews.+AppNotifier createMachinesReviewApp() => _App(_Cli());+Future<void> main() async {if (!kUnderTest) throw StateError('Preview requires FLUTTER_TEST=1.');WidgetsFlutterBinding.ensureInitialized();diff --git a/desktop/tool/onboarding_preview.dart b/desktop/tool/onboarding_preview.dartnew file mode 100644index 000000000..9f8099fb5--- /dev/null+++ b/desktop/tool/onboarding_preview.dart@@ -0,0 +1,194 @@+/// Disposable review of all three production onboarding panels.+/// Launch with FLUTTER_TEST=1. The bottom controls simulate progress in memory.+library;++import 'package:flutter/material.dart';+import 'package:harness/core/desktop_window.dart';+import 'package:harness/core/models.dart';+import 'package:harness/core/test_run.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/state/new_harness.dart';+import 'package:harness/state/workspace_onboarding.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:window_manager/window_manager.dart';++import 'machines_preview.dart' show createMachinesReviewApp;++Future<void> main() async {+ if (!kUnderTest) throw StateError('Preview requires FLUTTER_TEST=1.');+ WidgetsFlutterBinding.ensureInitialized();+ newHarnessOpensInBox = true;+ await configureDesktopWindow();+ await windowManager.setTitle('Onboarding review');+ runApp(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: const _Review(),+ ),+ );+}++class _Review extends StatefulWidget {+ const _Review();+ @override+ State<_Review> createState() => _ReviewState();+}++class _ReviewState extends State<_Review> {+ late AppNotifier app;+ late WorkspaceOnboarding onboarding;+ int scene = 0, revision = 0;+ bool _switching = false;+ @override+ void initState() {+ super.initState();+ _prepare(0);+ }++ void _prepare(int step) {+ scene = step;+ revision++;+ app = createMachinesReviewApp();+ app.machineStates.removeWhere((id, _) => id != 'm');+ app.stateOf('m')!.agents = [];+ onboarding = WorkspaceOnboarding();+ if (step == 1 || step == 2) {+ app.stateOf('m')!.agents = const [+ Agent(+ id: 'work',+ name: 'Build my website',+ engine: 'codex',+ terminalAvailable: true,+ ),+ ];+ final session =+ TerminalSession(+ machineId: 'm',+ agentId: 'work',+ agentName: 'Build my website',+ engineId: 'codex',+ send: (_, _) async => true,+ sendBinary: (_) async => true,+ )+ ..status = TerminalSessionStatus.controlling+ ..streamId = 'review';+ session.terminal.write(+ 'Your website is ready to review.\r\n\r\nWhat would you like to change?\r\n',+ );+ // This entrypoint is guarded by kUnderTest and never opens a real session.+ // ignore: invalid_use_of_visible_for_testing_member+ app.adoptSessionForTest(session);+ }+ if (step == 2) {+ onboarding.sync(+ scope: 'account:[email protected]',+ observed: {OnboardingStep.machines},+ otherComputer: false,+ modelsAvailable: true,+ );+ }+ if (step == 3) {+ const local = Machine(+ machineId: 'm',+ name: 'Mac mini',+ authMode: MachineAuthMode.remote,+ );+ app.machineStates['m'] = MachineState(local)+ ..localOnly = true+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded;+ const source = Machine(+ machineId: 'source',+ name: 'M2',+ authMode: MachineAuthMode.remote,+ );+ app.machineStates['source'] = MachineState(source)+ ..nodeOnline = true+ ..needsLink = true+ ..agents = const [+ Agent(+ id: 'work',+ name: 'Build my website',+ engine: 'codex',+ terminalAvailable: true,+ ),+ ];+ }+ app.machines = app.machineStates.values.map((m) => m.machine).toList();+ }++ void _scene(int next) {+ if (_switching) return;+ final oldApp = app;+ final oldOnboarding = onboarding;+ // Let the old workspace release its native method-channel handler before+ // mounting another one. These controls only exist in the review fixture.+ setState(() => _switching = true);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ oldApp.dispose();+ oldOnboarding.dispose();+ setState(() {+ _prepare(next);+ _switching = false;+ });+ });+ }++ @override+ void dispose() {+ app.dispose();+ onboarding.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => Scaffold(+ body: Column(+ children: [+ Expanded(+ child: _switching+ ? const SizedBox()+ : SwarmScreen(+ key: ValueKey(revision),+ notifier: app,+ nativeTabs: true,+ onboarding: onboarding,+ ),+ ),+ Container(+ color: const Color(0xff202020),+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),+ child: Row(+ children: [+ const Text(+ 'Review',+ style: TextStyle(color: Colors.grey, fontSize: 12),+ ),+ const SizedBox(width: 12),+ for (final (index, label) in [+ (0, '1 · First harness'),+ (1, '2 · Another computer'),+ (2, '3 · Local AI'),+ (3, 'Receiving computer'),+ ])+ TextButton(+ onPressed: () => _scene(index),+ style: TextButton.styleFrom(+ foregroundColor: scene == index+ ? Colors.white+ : Colors.grey,+ ),+ child: Text(label),+ ),+ ],+ ),+ ),+ ],+ ),+ );+}diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex f0591dd5c..1a2451d60 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -813,7 +813,25 @@ private extension SwarmTitlebar {try checkTitlebar((strip.machinesButton.accessibilityValue() as? String)?.contains("2 new computers") == true &&(strip.modelsButton.accessibilityValue() as? String)?.contains("101 models ready") == true,"Machine and model notifications are available to assistive technology")+ for (step, button) in [("harnesses", strip.sessionsButton as SwarmNoticeButton),+ ("machines", strip.machinesButton as SwarmNoticeButton),+ ("models", strip.modelsButton as SwarmNoticeButton)] {+ _ = try messenger.receive("update", arguments: [+ "enabled": true, "onboarding": step, "machineNotices": 2,+ "modelNotices": 101, "unread": 3,+ ])+ try checkTitlebar(button.onboarding &&+ [strip.machinesButton, strip.modelsButton, strip.sessionsButton].filter { $0.onboarding }.count == 1,+ "Only the current onboarding step gets a dot")+ try checkTitlebar((button.accessibilityValue() as? String)?.contains("Suggested next step") == true,+ "The onboarding dot has an accessible purpose")+ try checkTitlebar(strip.machinesButton.attentionLabel == "2" &&+ strip.modelsButton.attentionLabel == "99+" && strip.sessionsButton.attentionLabel == "3",+ "Onboarding never inflates or replaces notification counts")+ }_ = try messenger.receive("update", arguments: ["enabled": true])+ try checkTitlebar([strip.machinesButton, strip.modelsButton, strip.sessionsButton].allSatisfy { !$0.onboarding },+ "Acknowledging onboarding removes the dot")try checkTitlebar(strip.machinesButton.attentionLabel == nil && strip.modelsButton.attentionLabel == nil,"Acknowledged machine and model news removes the badge")try checkTitlebar(strip.machinesButton.iconTint == NSColor(white: 0.60, alpha: 1) &&