Skip to content

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.

fix(store): retry a dropped fetch, and say why an install failed (#109) (#176)

0xken15e6d48b9e25af
diff --git a/cli/src/dsh/install.spec.ts b/cli/src/dsh/install.spec.ts
index 8c0fff526..03a7e31b4 100644
--- a/cli/src/dsh/install.spec.ts
+++ b/cli/src/dsh/install.spec.ts
@@ -6,7 +6,7 @@ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync,
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { env } from '../config/env.js'
-import { DOCTOR_TIMEOUT_MS, installDsh, removeDsh, resolveInstallSource, runDshDoctor, type DshInstallProgress } from './install.js'
+import { DOCTOR_TIMEOUT_MS, installDsh, isTransientGitFailure, removeDsh, resolveInstallSource, runDshDoctor, type DshInstallProgress } from './install.js'
import { dshInstallDir, installedDsh, invalidateInstalledDsh, listInstalledDsh, readInstalledIndex, type InstalledDsh } from './installed.js'
import { HARNESS_MONOREPO, type DshRegistryEntry } from './registry.js'
@@ -268,7 +268,7 @@ describe('installDsh, every way it can go', () => {
const frames: DshInstallProgress[] = []
expect(await installDsh({ source: 'relative/thing', link: true, onProgress: (p) => frames.push(p) }))
.toEqual({ ok: false, error: 'INVALID_SOURCE', detail: '--link needs an absolute path to a checkout' })
- expect(frames.at(-1)).toEqual({ id: null, phase: 'failed', detail: '--link needs an absolute path to a checkout' })
+ expect(frames.at(-1)).toEqual({ id: null, phase: 'failed', detail: '--link needs an absolute path to a checkout', error: 'INVALID_SOURCE' })
expect(await installDsh({ source: join(root, 'nope'), link: true })).toEqual({ ok: false, error: 'SOURCE_NOT_FOUND', detail: `${join(root, 'nope')} does not exist` })
mkdirSync(join(root, 'empty'))
expect(await installDsh({ source: join(root, 'empty'), link: true })).toMatchObject({ ok: false, error: 'INVALID_MANIFEST' })
@@ -380,6 +380,78 @@ describe('installDsh, every way it can go', () => {
expect(await pending).toEqual({ ok: false, error: 'CLONE_FAILED', detail: 'git clone was still running after 10 min: Cloning into x...' })
})
+ it('a fetch that failed the way a bad connection fails is tried again, from nothing, and the retry is narrated', async () => {
+ const repo = thing()
+ const marker = join(root, 'attempts')
+ // The first clone stalls out the way curl reports it; every later call is the real git.
+ stubGit(`if [ "$1" = clone ] && [ ! -e '${marker}' ]; then touch '${marker}'; printf 'Cloning into x...\\nerror: RPC failed; curl 28 Operation too slow. Less than 1024 bytes/sec transferred the last 60 seconds\\nfatal: early EOF\\n' >&2; exit 128; fi\nexec "$REAL_GIT" "$@"`)
+ const lines: string[] = []
+ const frames: DshInstallProgress[] = []
+ const result = await installDsh({ source: repo, cloneRetryDelaysMs: [0, 0], onLine: (line) => lines.push(line), onProgress: (p) => frames.push(p) })
+ expect(result.ok, JSON.stringify(result)).toBe(true)
+ expect(lines.find((line) => line.startsWith('fetch failed'))).toBe('fetch failed · git clone exited 128: Cloning into x... · error: RPC failed; curl 28 Operation too slow. Less than 1024 bytes/sec transferred the last 60 seconds · fatal: early EOF · retrying (2/3)')
+ expect(frames.map((f) => f.phase)).toEqual(['clone', 'doctor', 'done'])
+ expect(leftovers()).toEqual([])
+ })
+
+ it('a connection that never recovers is given up after three attempts, and said to have been', async () => {
+ stubGit(`printf 'fatal: unable to access https://example.com/thing.git/: Could not resolve host: example.com\\n' >&2\nexit 128`)
+ const lines: string[] = []
+ const frames: DshInstallProgress[] = []
+ const result = await installDsh({ source: 'https://example.com/thing.git', cloneRetryDelaysMs: [0, 0], onLine: (line) => lines.push(line), onProgress: (p) => frames.push(p) })
+ expect(result).toEqual({ ok: false, error: 'CLONE_FAILED', detail: 'git clone exited 128: fatal: unable to access https://example.com/thing.git/: Could not resolve host: example.com · gave up after 3 attempts' })
+ expect(lines.filter((line) => line.startsWith('fetch failed')).map((line) => line.slice(-'retrying (2/3)'.length))).toEqual(['retrying (2/3)', 'retrying (3/3)'])
+ expect(frames.at(-1)).toMatchObject({ phase: 'failed', error: 'CLONE_FAILED', detail: expect.stringContaining('gave up after 3 attempts') })
+ expect(leftovers()).toEqual([])
+ })
+
+ it('a repository that is not there is not tried again', async () => {
+ const marker = join(root, 'attempts')
+ stubGit(`echo x >> '${marker}'\nprintf 'remote: Repository not found.\\nfatal: repository https://example.com/thing.git/ not found\\n' >&2\nexit 128`)
+ const lines: string[] = []
+ const result = await installDsh({ source: 'https://example.com/thing.git', cloneRetryDelaysMs: [0, 0], onLine: (line) => lines.push(line) })
+ expect(result).toEqual({ ok: false, error: 'CLONE_FAILED', detail: 'git clone exited 128: fatal: repository https://example.com/thing.git/ not found' })
+ expect(readFileSync(marker, 'utf8')).toBe('x\n')
+ expect(lines.some((line) => line.startsWith('fetch failed'))).toBe(false)
+ })
+
+ it('git is run with a stall limit and no credential prompt, on top of the daemon\'s environment', async () => {
+ stubGit(`printf 'env %s %s %s %s\\n' "$GIT_HTTP_LOW_SPEED_LIMIT" "$GIT_HTTP_LOW_SPEED_TIME" "$GIT_TERMINAL_PROMPT" "$DSH_SPEC_MARK" >&2\nexit 1`)
+ process.env.DSH_SPEC_MARK = 'still-here'
+ try {
+ const lines: string[] = []
+ await installDsh({ source: 'https://example.com/thing.git', onLine: (line) => lines.push(line) })
+ expect(lines).toContain('env 1024 60 0 still-here')
+ } finally {
+ delete process.env.DSH_SPEC_MARK
+ }
+ })
+
+ it('isTransientGitFailure: the network is, the repository and our own stop are not', () => {
+ for (const said of [
+ 'git clone exited 128: error: RPC failed; curl 28 Operation too slow',
+ 'git clone exited 128: fatal: early EOF',
+ 'git fetch exited 128: fatal: the remote end hung up unexpectedly',
+ 'git clone exited 128: fatal: unable to access https://x/: Could not resolve host: x',
+ 'git clone exited 128: fatal: unable to access https://x/: Failed to connect to x port 443: Connection refused',
+ 'git clone exited 128: error: The requested URL returned error: 502',
+ 'git clone exited 128: fatal: unable to access https://x/: GnuTLS recv error (-110)',
+ 'git clone exited 128: fatal: unable to access https://x/: OpenSSL SSL_read: Connection reset by peer, errno 104',
+ ]) expect(isTransientGitFailure(said), said).toBe(true)
+ for (const said of [
+ 'git clone was still running after 10 min: Receiving objects: 40%',
+ 'git clone exited 128: fatal: repository https://x/ not found',
+ 'git clone exited 128: error: RPC failed; curl 22 The requested URL returned error: 404',
+ 'git clone exited 128: error: RPC failed; HTTP 401 curl 22 The requested URL returned error: 401',
+ 'git clone exited 128: fatal: Authentication failed for https://x/',
+ 'git clone exited 128: git@x: Permission denied (publickey). · fatal: Could not read from remote repository.',
+ 'git clone exited 128: fatal: could not read Username for https://x: terminal prompts disabled',
+ 'git clone exited 128: fatal: Remote branch nope not found in upstream origin',
+ 'https://x at main has no folder store/agents/nope',
+ 'git clone exited 2',
+ ]) expect(isTransientGitFailure(said), said).toBe(false)
+ })
+
it('a git that fails without a word is reported by how it ended alone, a code or a signal', async () => {
stubGit('exit 2')
expect(await installDsh({ source: 'https://example.com/thing.git' })).toEqual({ ok: false, error: 'CLONE_FAILED', detail: 'git clone exited 2' })
@@ -428,7 +500,7 @@ describe('installDsh, every way it can go', () => {
const result = await installDsh({ source: repo, registry, onProgress: (p) => frames.push(p), onLine: (line) => lines.push(line) })
expect(result).toMatchObject({ ok: false, error: 'CLONE_FAILED' })
expect(!result.ok && result.detail).toMatch(/^viewer acme\/viewer · git clone exited 128: /)
- expect(frames.filter((f) => f.phase === 'failed')).toEqual([{ id: 'acme/thing', phase: 'failed', detail: !result.ok && result.detail }])
+ expect(frames.filter((f) => f.phase === 'failed')).toEqual([{ id: 'acme/thing', phase: 'failed', detail: !result.ok && result.detail, error: 'CLONE_FAILED' }])
expect(frames.every((f) => f.id === null || f.id === 'acme/thing')).toBe(true)
expect(lines).toContain('viewer acme/viewer · installing')
expect(readInstalledIndex()).toEqual([])
@@ -446,7 +518,7 @@ describe('installDsh, every way it can go', () => {
const frames: DshInstallProgress[] = []
const result = await installDsh({ source: repo, onProgress: (p) => frames.push(p) })
expect(result).toEqual({ ok: false, error: 'DOCTOR_FAILED', detail: 'doctor failed · miss typst on PATH · miss fonts' })
- expect(frames.at(-1)).toEqual({ id: 'acme/thing', phase: 'failed', detail: 'doctor failed · miss typst on PATH · miss fonts' })
+ expect(frames.at(-1)).toEqual({ id: 'acme/thing', phase: 'failed', detail: 'doctor failed · miss typst on PATH · miss fonts', error: 'DOCTOR_FAILED' })
expect(readInstalledIndex().map((row) => row.id)).toEqual(['acme/thing'])
})
diff --git a/cli/src/dsh/install.ts b/cli/src/dsh/install.ts
index 7f58e4408..392c86a38 100644
--- a/cli/src/dsh/install.ts
+++ b/cli/src/dsh/install.ts
@@ -39,6 +39,8 @@ export interface DshInstallProgress {
* installDsh itself (which reports lines through `onLine`), throttled to a few a second.
*/
line?: string
+ /** On `failed`: the code the reply carries (`CLONE_FAILED`, `SETUP_FAILED`…), so a client can say what kind of failure it was. */
+ error?: string
}
export interface DshInstallOptions {
@@ -60,6 +62,8 @@ export interface DshInstallOptions {
setupTimeoutMs?: number
/** Where a `viewer.use` id resolves to a repo; the bundled registry by default. Test seam. */
registry?: (id: string) => DshRegistryEntry | undefined
+ /** Waits between fetch attempts; [[CLONE_RETRY_DELAYS_MS]] by default. Test seam. */
+ cloneRetryDelaysMs?: readonly number[]
}
export interface DshDoctorResult {
@@ -115,12 +119,60 @@ function linkInstall(source: string): { ok: true; realDir: string; manifest: Dsh
return { ok: true, realDir, manifest: manifest.manifest }
}
+/**
+ * Between fetch attempts, in order; the length is how many retries a transient failure gets. A stalled
+ * transfer already cost the low-speed window, so these are short — the point is a second connection,
+ * not a long wait.
+ */
+export const CLONE_RETRY_DELAYS_MS: readonly number[] = [2_000, 5_000]
+
+/**
+ * Whether what git said is the network, not the repository: the wording curl and git's transport use
+ * for a stall, a reset, a resolver miss or a 5xx. A repo that is not there, a ref that does not exist,
+ * a refused credential and our own ten-minute stop are not — a second try answers the same.
+ */
+export function isTransientGitFailure(detail: string): boolean {
+ if (/was still running after \d+ min/.test(detail)) return false
+ // A 4xx rides the same `RPC failed; curl 22` prefix as a stall; a repo that is not there or a
+ // credential that was refused answers the same on every try.
+ if (/returned error: 4\d\d|HTTP 4\d\d|Authentication failed|could not read Username|Repository not found|Permission denied/i.test(detail)) return false
+ return /\bcurl \d+\b|RPC failed|early EOF|unexpected disconnect|remote end hung up|Could not resolve host|Connection (?:reset|refused|timed out)|Operation too slow|Timeout was reached|Failed to connect to|The requested URL returned error: 5\d\d|GnuTLS recv error|SSL_read|Connection closed|TLS connect error|Empty reply from server/i.test(detail)
+}
+
+export type CloneInstallResult = { ok: true; tmpDir: string; manifest: DshManifest; commit: string | null; revision: string | null } | { ok: false; error: string; detail: string }
+
+/**
+ * Fetch the package into a fresh temporary directory. A fetch that failed the way a bad connection
+ * fails is tried again, a bounded number of times, each from nothing (the failed attempt's directories
+ * are gone): a clone is idempotent, and a Store install that stalled once on a WSL link and worked the
+ * next time should not have needed a person to click.
+ */
export async function cloneInstall(
source: string,
ref: string | undefined,
path: string | undefined,
onLine: ((line: string) => void) | undefined,
-): Promise<{ ok: true; tmpDir: string; manifest: DshManifest; commit: string | null; revision: string | null } | { ok: false; error: string; detail: string }> {
+ retryDelaysMs: readonly number[] = CLONE_RETRY_DELAYS_MS,
+): Promise<CloneInstallResult> {
+ const attempts = retryDelaysMs.length + 1
+ for (let attempt = 1; ; attempt++) {
+ const result = await cloneOnce(source, ref, path, onLine)
+ if (result.ok || result.error !== 'CLONE_FAILED' || !isTransientGitFailure(result.detail)) return result
+ if (attempt >= attempts) {
+ return { ...result, detail: `${result.detail} · gave up after ${attempts} attempts`.slice(0, 2000) }
+ }
+ const delay = retryDelaysMs[attempt - 1] ?? 0
+ onLine?.(`fetch failed · ${result.detail} · retrying (${attempt + 1}/${attempts})`)
+ await new Promise<void>((resolve) => setTimeout(resolve, delay))
+ }
+}
+
+async function cloneOnce(
+ source: string,
+ ref: string | undefined,
+ path: string | undefined,
+ onLine: ((line: string) => void) | undefined,
+): Promise<CloneInstallResult> {
const root = dshRootDir()
mkdirSync(root, { recursive: true, mode: 0o700 })
const tmpDir = join(root, `.tmp-${randomUUID()}`)
@@ -166,6 +218,18 @@ export async function cloneInstall(
/** How long one git command may take: a clone of a large repository over a slow link, not a hang. */
const GIT_TIMEOUT_MS = 10 * 60_000
+/**
+ * What git is run with, on top of the daemon's environment. A transfer under 1 KiB/s for a minute is
+ * a stalled connection, and curl gives it up then (`RPC failed; curl 28`) rather than sitting silent
+ * until the ten-minute stop — which is what "Fetching…" for a quarter of an hour on a WSL link was.
+ * No stdin here, so a credential prompt could only hang: git is told not to ask.
+ */
+const GIT_ENV: NodeJS.ProcessEnv = {
+ GIT_HTTP_LOW_SPEED_LIMIT: '1024',
+ GIT_HTTP_LOW_SPEED_TIME: '60',
+ GIT_TERMINAL_PROMPT: '0',
+}
+
/** Catalogs pin built-ins to the commit they describe; `git clone --branch` cannot take a SHA. */
async function cloneRepo(source: string, ref: string | undefined, dir: string, sparse: boolean, onLine: DshInstallOptions['onLine']): Promise<{ ok: true } | { ok: false; detail: string }> {
if (!ref || !/^[a-f0-9]{40}$/i.test(ref)) {
@@ -188,7 +252,7 @@ async function cloneRepo(source: string, ref: string | undefined, dir: string, s
/** Run git, handing each stderr line (and each carriage-return progress segment) to `onLine` as it lands. */
function streamGit(args: string[], onLine: ((line: string) => void) | undefined): Promise<{ ok: true } | { ok: false; detail: string }> {
return new Promise((resolve) => {
- const child = spawn('git', args, { stdio: ['ignore', 'ignore', 'pipe'] })
+ const child = spawn('git', args, { stdio: ['ignore', 'ignore', 'pipe'], env: { ...process.env, ...GIT_ENV } })
const tail: string[] = []
let rest = ''
let timedOut = false
@@ -263,7 +327,7 @@ export async function installDsh(opts: DshInstallOptions): Promise<DshInstallRes
const progress = (p: DshInstallProgress): void => opts.onProgress?.(p)
const wrongId = (actual: string): DshInstallResult => {
const detail = `Catalog requested ${opts.expectedId}, but the package declares ${actual}`
- progress({ id: opts.expectedId ?? null, phase: 'failed', detail })
+ progress({ id: opts.expectedId ?? null, phase: 'failed', detail, error: 'PACKAGE_ID_MISMATCH' })
return { ok: false, error: 'PACKAGE_ID_MISMATCH', detail }
}
let manifest: DshManifest
@@ -278,7 +342,7 @@ export async function installDsh(opts: DshInstallOptions): Promise<DshInstallRes
progress({ id: null, phase: 'clone', detail: opts.link ? `linking ${opts.source}` : `cloning ${opts.source}${opts.path ? ` · ${opts.path}` : ''}` })
if (opts.link) {
const linked = linkInstall(opts.source)
- if (!linked.ok) { progress({ id: null, phase: 'failed', detail: linked.detail }); return linked }
+ if (!linked.ok) { progress({ id: null, phase: 'failed', detail: linked.detail, error: linked.error }); return linked }
manifest = linked.manifest
if (opts.expectedId && manifest.id !== opts.expectedId) return wrongId(manifest.id)
unlock = lockDsh(manifest.id)
@@ -287,8 +351,8 @@ export async function installDsh(opts: DshInstallOptions): Promise<DshInstallRes
dir = placeAt(manifest.id, { linkTo: realDir })
commit = await gitHead(realDir)
} else {
- const cloned = await cloneInstall(opts.source, opts.ref, opts.path, opts.onLine)
- if (!cloned.ok) { progress({ id: null, phase: 'failed', detail: cloned.detail }); return cloned }
+ const cloned = await cloneInstall(opts.source, opts.ref, opts.path, opts.onLine, opts.cloneRetryDelaysMs)
+ if (!cloned.ok) { progress({ id: null, phase: 'failed', detail: cloned.detail, error: cloned.error }); return cloned }
staged = cloned.tmpDir
manifest = cloned.manifest
if (opts.expectedId && manifest.id !== opts.expectedId) {
@@ -339,7 +403,7 @@ export async function finishInstall(resolved: InstalledDsh, opts: DshInstallOpti
const detail = setup.timedOut
? 'setup timed out'
: `setup exited ${setup.code ?? setup.signal} · ${setup.lines.slice(-5).join(' · ')}`.slice(0, 2000)
- progress({ id: manifest.id, phase: 'failed', detail })
+ progress({ id: manifest.id, phase: 'failed', detail, error: 'SETUP_FAILED' })
return { ok: false, error: 'SETUP_FAILED', detail }
}
}
@@ -358,7 +422,7 @@ export async function finishInstall(resolved: InstalledDsh, opts: DshInstallOpti
// install would read as hung for the minutes OpenCascade takes to arrive. The viewer's `done`
// is not the harness's done, so it reports as the harness's setup still going.
const dep = await installDsh({
- source: entry.repo, expectedId: entry.id, ref: entry.ref, path: entry.path, registry: opts.registry, setupTimeoutMs: opts.setupTimeoutMs, onLine: opts.onLine,
+ source: entry.repo, expectedId: entry.id, ref: entry.ref, path: entry.path, registry: opts.registry, setupTimeoutMs: opts.setupTimeoutMs, cloneRetryDelaysMs: opts.cloneRetryDelaysMs, onLine: opts.onLine,
onProgress: (p) => {
if (p.phase === 'failed') return // reported below, once, with the viewer named
const phase: DshInstallPhase = p.phase === 'done' ? 'setup' : p.phase
@@ -367,7 +431,7 @@ export async function finishInstall(resolved: InstalledDsh, opts: DshInstallOpti
})
if (!dep.ok) {
const detail = `viewer ${uses} · ${dep.detail}`.slice(0, 2000)
- progress({ id: manifest.id, phase: 'failed', detail })
+ progress({ id: manifest.id, phase: 'failed', detail, error: dep.error })
return { ok: false, error: dep.error, detail }
}
progress({ id: manifest.id, phase: 'setup', detail: `viewer ${uses} · installed` })
@@ -378,7 +442,7 @@ export async function finishInstall(resolved: InstalledDsh, opts: DshInstallOpti
if (!recordDoctorFailure && uses && installedDsh(uses)?.manifest.kind !== 'viewer') {
const detail = `viewer ${uses} is not available; the previous package will be kept`
- progress({ id: manifest.id, phase: 'failed', detail })
+ progress({ id: manifest.id, phase: 'failed', detail, error: 'VIEWER_UNAVAILABLE' })
return { ok: false, error: 'VIEWER_UNAVAILABLE', detail }
}
@@ -392,7 +456,7 @@ export async function finishInstall(resolved: InstalledDsh, opts: DshInstallOpti
}
if (!doctor.ok) {
const detail = `doctor failed · ${doctor.lines.filter((line) => line.startsWith('miss')).join(' · ') || doctor.lines.slice(-3).join(' · ')}`.slice(0, 2000)
- progress({ id: manifest.id, phase: 'failed', detail })
+ progress({ id: manifest.id, phase: 'failed', detail, error: 'DOCTOR_FAILED' })
return { ok: false, error: 'DOCTOR_FAILED', detail }
}
progress({ id: manifest.id, phase: 'done' })
diff --git a/cli/src/dsh/update.ts b/cli/src/dsh/update.ts
index 064de4a8d..573f00aaf 100644
--- a/cli/src/dsh/update.ts
+++ b/cli/src/dsh/update.ts
@@ -13,12 +13,13 @@ export interface DshUpdateOptions {
onProgress?: DshInstallOptions['onProgress']
onLine?: DshInstallOptions['onLine']
setupTimeoutMs?: number
+ cloneRetryDelaysMs?: DshInstallOptions['cloneRetryDelaysMs']
}
/** Replace only the package, retaining the old files and index until the new doctor passes. */
export async function updateDsh(opts: DshUpdateOptions): Promise<DshInstallResult> {
const result = await updatePackage(opts)
- opts.onProgress?.({ id: opts.id, phase: result.ok ? 'done' : 'failed', ...(!result.ok ? { detail: result.detail } : {}) })
+ opts.onProgress?.({ id: opts.id, phase: result.ok ? 'done' : 'failed', ...(!result.ok ? { detail: result.detail, error: result.error } : {}) })
return result
}
@@ -40,7 +41,7 @@ async function updatePackage(opts: DshUpdateOptions): Promise<DshInstallResult>
const ref = entry?.ref ?? record.ref ?? undefined
const path = record.path ?? undefined
opts.onProgress?.({ id: opts.id, phase: 'clone', detail: `fetching ${record.source}` })
- const cloned = await cloneInstall(record.source, ref, path, opts.onLine)
+ const cloned = await cloneInstall(record.source, ref, path, opts.onLine, opts.cloneRetryDelaysMs)
if (!cloned.ok) return cloned
staged = cloned.tmpDir
if (cloned.manifest.id !== record.id) {
diff --git a/desktop/lib/core/dsh_catalog.dart b/desktop/lib/core/dsh_catalog.dart
index 5257bb6e8..32dad7439 100644
--- a/desktop/lib/core/dsh_catalog.dart
+++ b/desktop/lib/core/dsh_catalog.dart
@@ -230,12 +230,20 @@ class DshInstallProgress {
required this.phase,
this.detail,
this.line,
+ this.code,
});
final String id;
final String phase;
final String? detail;
+ /// On `failed`: the machine's reason as a code (`CLONE_FAILED`,
+ /// `SETUP_FAILED`, `DOCTOR_FAILED`…), or one of this app's own
+ /// (`CONNECTION`, `TIMEOUT`) when the request never came back. What lets
+ /// the Store say "the network" rather than "the package" without guessing
+ /// from the wording. Null from a daemon that predates it.
+ final String? code;
+
/// The line the phase's command is on right now, as the machine narrates it
/// (throttled there). What turns "Setting up…" for three minutes into
/// "Installed 61 packages".
@@ -264,6 +272,7 @@ class DshInstallProgress {
}
final detail = raw['detail'];
final line = raw['line'];
+ final error = raw['error'];
return DshInstallProgress(
id: id,
phase: phase,
@@ -271,9 +280,12 @@ class DshInstallProgress {
? _clean(detail, 500)
: null,
line: line is String && line.trim().isNotEmpty ? _clean(line, 200) : null,
+ code: error is String && _codeRe.hasMatch(error) ? error : null,
);
}
+ static final _codeRe = RegExp(r'^[A-Z][A-Z0-9_]{1,40}$');
+
static String _clean(String raw, int max) {
final text = raw.replaceAll(RegExp(r'[\x00-\x1f\x7f]'), ' ').trim();
return text.length > max ? text.substring(0, max) : text;
@@ -302,6 +314,7 @@ class DshInstallRun {
String? line;
String? detail;
+ String? code;
String get phase => phases.isEmpty ? 'clone' : phases.last.phase;
bool get done => phase == 'done';
@@ -333,6 +346,7 @@ class DshInstallRun {
phases.add((phase: progress.phase, at: at));
}
if (progress.detail != null) detail = progress.detail;
+ if (progress.code != null) code = progress.code;
if (progress.line != null && progress.line != line) {
line = progress.line;
log.add(progress.line!);
@@ -380,6 +394,30 @@ class MachineDsh {
run.apply(progress, now: now);
}
+ /// Close [id]'s run as failed with the reply's reason. The machine usually
+ /// pushed its own `failed` a moment earlier; that run is kept — its phases
+ /// and doctor lines are what explains the failure — and only the reason is
+ /// set, rather than a second push opening a fresh run holding nothing but
+ /// the sentence. A run that is not already closed is closed by this push.
+ void failInstall(String id, String detail, {String? code, DateTime? now}) {
+ final run = runs[id];
+ if (run != null && run.failed) {
+ run.detail = detail;
+ if (code != null) run.code = code;
+ installs[id] = DshInstallProgress(
+ id: id,
+ phase: 'failed',
+ detail: detail,
+ code: code ?? run.code,
+ );
+ return;
+ }
+ applyInstall(
+ DshInstallProgress(id: id, phase: 'failed', detail: detail, code: code),
+ now: now,
+ );
+ }
+
DshEntry? operator [](String id) => byId[id];
/// Every harness the machine named, installed or not, in the order it gave.
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index bf915f192..7599dd39b 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1844,6 +1844,12 @@ class AppNotifier extends ChangeNotifier {
// instead of leaving the user stuck on the empty "select a machine" placeholder.
unawaited(_applyNodeStatus(machine, true));
unawaited(_loadMachineData(machine, force: true));
+ // An install this socket was carrying when it dropped went on without it
+ // (the daemon never heard the socket go); its outcome is in the list, so
+ // the list is asked again now that someone is there to ask.
+ if (_dshProbeOnReconnect.remove(machineId)) {
+ unawaited(probeDsh(machineId, force: true));
+ }
_startAgentSyncTimer(machineId);
}
@@ -5031,6 +5037,11 @@ class AppNotifier extends ChangeNotifier {
/// narrates progress through `dsh_install_status` pushes, which land in
/// [MachineDsh.installs] for the dialog's status line. Null on success, else
/// a sentence for the person who clicked.
+ /// Machines whose socket dropped under a `dsh_install`/`dsh_update`: the
+ /// daemon went on without us, so the list is asked once more when the
+ /// socket is back. Consumed by [_onMachineConnected].
+ final Set<String> _dshProbeOnReconnect = {};
+
Future<String?> installDsh(String machineId, String id) =>
_installOrUpdateDsh(machineId, id, update: false);
@@ -5060,12 +5071,14 @@ class AppNotifier extends ChangeNotifier {
);
if (result['ok'] != true) {
final detail = result['detail'];
+ final error = result['error'];
return _finishInstall(
machine,
id,
detail is String && detail.isNotEmpty
? detail
: '$action failed on $machineName',
+ code: error is String ? error : null,
);
}
} on WsRequestFailure catch (failure) {
@@ -5076,15 +5089,29 @@ class AppNotifier extends ChangeNotifier {
failure.detail?.isNotEmpty == true
? failure.detail!
: '$action failed on $machineName (${failure.code})',
- });
+ }, code: failure.code);
} on WsRequestTimeout {
return _finishInstall(
machine,
id,
'$machineName is still ${update ? 'updating' : 'installing'}. Try again in a few minutes.',
+ code: 'TIMEOUT',
+ );
+ } catch (error) {
+ // The socket went away under the request — the daemon does not know, and
+ // is most likely still ${verb}ing. Said as that, not as "failed"; the
+ // list is asked again when the socket is back (`_onMachineConnected`), so an
+ // install that landed reads as installed without another click. (Issue
+ // #109: this was the bare "Install failed" whose retry "just worked".)
+ appLog.warn('app', 'dsh_$verb $id on $machineName', error: error);
+ _dshProbeOnReconnect.add(machineId);
+ return _finishInstall(
+ machine,
+ id,
+ 'Lost the connection to $machineName while ${update ? 'updating' : 'installing'} — '
+ 'it may still be finishing there. Try again in a moment.',
+ code: 'CONNECTION',
);
- } catch (_) {
- return _finishInstall(machine, id, '$action failed on $machineName');
}
machine.dsh.applyInstall(DshInstallProgress(id: id, phase: 'done'));
notifyListeners();
@@ -5093,10 +5120,13 @@ class AppNotifier extends ChangeNotifier {
return null;
}
- String _finishInstall(MachineState machine, String id, String error) {
- machine.dsh.applyInstall(
- DshInstallProgress(id: id, phase: 'failed', detail: error),
- );
+ String _finishInstall(
+ MachineState machine,
+ String id,
+ String error, {
+ String? code,
+ }) {
+ machine.dsh.failInstall(id, error, code: code);
notifyListeners();
return error;
}
diff --git a/desktop/lib/store/store_screen.dart b/desktop/lib/store/store_screen.dart
index 38aa5c05f..bc590f762 100644
--- a/desktop/lib/store/store_screen.dart
+++ b/desktop/lib/store/store_screen.dart
@@ -16,6 +16,7 @@ import '../shared/widgets/app_icon_button.dart';
import '../shortcuts/app_keymap.dart';
import '../shortcuts/keymap.dart';
import '../state/app_state.dart';
+import '../widgets/dsh_install_panel.dart' show describeInstallFailure;
import '../widgets/engine_identity.dart';
import '../widgets/new_agent_dialog.dart';
import '../widgets/open_harness_intent.dart';
@@ -989,7 +990,18 @@ class _ProductPageState extends State<_ProductPage> {
);
_busy.remove(machineId);
if (mounted) setState(() {});
- if (failure != null) _say(failure);
+ if (failure != null) _say(_failureSentence(local, failure));
+ }
+
+ /// The toast for a failed Get/Update: what kind of failure and what to do,
+ /// not the two thousand characters git printed — those stay on the page,
+ /// under the button, where they can be read at leisure.
+ String _failureSentence(MachineState local, String fallback) {
+ final run = local.dsh.runs[_operationId(local, widget.entry.id)];
+ if (run == null || !run.failed) return fallback;
+ final failure = describeInstallFailure(run, widget.entry.name);
+ final hint = failure.hint;
+ return hint == null ? failure.title : '${failure.title} $hint';
}
Future<void> _update(String machineId) async {
@@ -1007,7 +1019,7 @@ class _ProductPageState extends State<_ProductPage> {
);
_busy.remove(machineId);
if (mounted) setState(() {});
- if (failure != null) _say(failure);
+ if (failure != null) _say(_failureSentence(local, failure));
}
Future<void> _remove(String machineId, String machineName) async {
@@ -1474,6 +1486,11 @@ class _InstallLine extends StatelessWidget {
final installing = run != null && run.inProgress;
final installed = !entry.isEngine && row?.installed == true;
final String status;
+ // On a failure: what the machine said, in full, a hover away. The line
+ // itself says which kind of thing went wrong and what to do about it —
+ // a bare "Install failed" over a fetch the network dropped left nothing to
+ // tell it apart from a broken package (issue #109).
+ String? failureTooltip;
if (entry.isEngine) {
status = _engineStatus();
} else if (installing) {
@@ -1484,9 +1501,19 @@ class _InstallLine extends StatelessWidget {
_ => 'Installing…',
};
} else if (run != null && run.failed) {
- status =
- run.log.where((line) => line.startsWith('miss')).lastOrNull ??
- (installed ? 'Update failed' : 'Install failed');
+ final failure = describeInstallFailure(run, entry.name);
+ status = failure.hint == null
+ ? failure.title
+ : '${failure.title} ${failure.hint}';
+ final words = [
+ if (failure.body != null && failure.body != failure.title) failure.body,
+ if (failure.command != null) failure.command,
+ if (run.detail != null &&
+ run.detail != failure.body &&
+ run.detail != failure.title)
+ run.detail,
+ ].whereType<String>().join('\n');
+ if (words.isNotEmpty) failureTooltip = words;
} else if (installed) {
status = row?.linked == true
? 'Installed · linked to a checkout'
@@ -1530,13 +1557,17 @@ class _InstallLine extends StatelessWidget {
),
Text('${state.machine.displayName} · this computer', style: faint),
Text('·', style: faint),
- Text(
- status,
- style: TextStyle(
- fontSize: 12.5,
- color: run?.failed == true
- ? grid.AppPalette.warn
- : grid.AppPalette.textSecondary,
+ _maybeTooltip(
+ failureTooltip,
+ Text(
+ status,
+ key: const ValueKey('store-install-status'),
+ style: TextStyle(
+ fontSize: 12.5,
+ color: run?.failed == true
+ ? grid.AppPalette.warn
+ : grid.AppPalette.textSecondary,
+ ),
),
),
if (installed && row?.installedCommit != null)
@@ -1559,6 +1590,15 @@ class _InstallLine extends StatelessWidget {
}
}
+Widget _maybeTooltip(String? message, Widget child) => message == null
+ ? child
+ : Tooltip(
+ key: const ValueKey('store-install-failure-detail'),
+ message: message,
+ waitDuration: const Duration(milliseconds: 300),
+ child: child,
+ );
+
/// A link that stays out of the way: secondary text, brighter under the pointer, an arrow when it
/// leaves the app. Without a destination it is plain text (the licence).
class _QuietLink extends StatefulWidget {
diff --git a/desktop/lib/widgets/dsh_install_panel.dart b/desktop/lib/widgets/dsh_install_panel.dart
index 48f6235ba..75d6a8d85 100644
--- a/desktop/lib/widgets/dsh_install_panel.dart
+++ b/desktop/lib/widgets/dsh_install_panel.dart
@@ -212,16 +212,60 @@ class _DshInstallPanelState extends State<DshInstallPanel> {
/// What a failed install means for the person, from the machine's `miss` line.
///
+/// What kind of thing went wrong, for the one decision a person makes at a
+/// failed install: try again, or fix something first.
+enum InstallFailureKind {
+ /// The download — the connection, a resolver, a 5xx. Trying again is the fix.
+ network,
+
+ /// The package itself: no manifest, the wrong id, an unknown catalog entry.
+ /// Trying again answers the same; it needs a fix in the Store.
+ package,
+
+ /// This machine: a tool the toolchain needs, a setup that failed, a doctor
+ /// that found something missing.
+ runtime,
+
+ /// Another install of the same package is under way on the machine.
+ busy,
+
+ unknown,
+}
+
/// The doctor's lines name the missing tool and a URL; this turns the common
/// ones into a sentence and the command that fixes it. Anything it does not
/// know is shown as the machine wrote it.
class InstallFailure {
- const InstallFailure({required this.title, this.body, this.command});
+ const InstallFailure({
+ required this.title,
+ this.body,
+ this.command,
+ this.hint,
+ this.kind = InstallFailureKind.unknown,
+ });
final String title;
final String? body;
final String? command;
+
+ /// What to do about it, when [kind] settles that — "Try again", "Retrying
+ /// will not help". Null when the [title]/[body] already say.
+ final String? hint;
+ final InstallFailureKind kind;
}
+/// The wording git and curl use for the connection, as opposed to the
+/// repository: the same list the daemon retries on. Read here only for a
+/// daemon old enough to send no code.
+final _transientGit = RegExp(
+ r'\bcurl \d+\b|RPC failed|early EOF|unexpected disconnect|remote end hung up|'
+ r'Could not resolve host|Connection (?:reset|refused|timed out)|Operation too slow|'
+ r'Timeout was reached|Failed to connect to|returned error: 5\d\d|'
+ r'GnuTLS recv error|SSL_read|TLS connect error|Empty reply from server',
+ caseSensitive: false,
+);
+
+final _gaveUp = RegExp(r'gave up after (\d+) attempts');
+
InstallFailure describeInstallFailure(DshInstallRun run, String harnessName) {
final miss =
run.checks.where((c) => c.startsWith('miss')).firstOrNull ??
@@ -231,8 +275,43 @@ InstallFailure describeInstallFailure(DshInstallRun run, String harnessName) {
'',
);
final lower = text.toLowerCase();
+ final code = run.code;
+ // The code first, where there is one: it says which step failed without
+ // reading git's wording, and a `miss` line only exists once the doctor ran.
+ switch (code) {
+ case 'DSH_BUSY':
+ return InstallFailure(
+ kind: InstallFailureKind.busy,
+ title: 'Already installing $harnessName on this machine.',
+ body: text,
+ hint: 'Wait for it to finish.',
+ );
+ case 'CONNECTION':
+ case 'TIMEOUT':
+ // This app's own sentence about the request, not the machine's — a
+ // doctor line heard before the socket went must not replace it.
+ return InstallFailure(
+ kind: InstallFailureKind.network,
+ title: run.detail ?? text,
+ );
+ case 'INVALID_MANIFEST':
+ case 'PACKAGE_ID_MISMATCH':
+ case 'PACKAGE_KIND_MISMATCH':
+ case 'INVALID_DSH':
+ case 'INVALID_SOURCE':
+ case 'SOURCE_NOT_FOUND':
+ return InstallFailure(
+ kind: InstallFailureKind.package,
+ title: 'The $harnessName package is broken.',
+ body: text,
+ hint: 'Trying again will not help — this needs a fix in the Store.',
+ );
+ case 'CLONE_FAILED':
+ return _downloadFailure(text, harnessName);
+ }
if (lower.startsWith('codex')) {
return InstallFailure(
+ kind: InstallFailureKind.runtime,
title: 'Codex is not installed on this machine.',
body: '$harnessName runs on Codex. Install it, then retry.',
command: 'npm install -g @openai/codex',
@@ -240,6 +319,7 @@ InstallFailure describeInstallFailure(DshInstallRun run, String harnessName) {
}
if (lower.startsWith('claude')) {
return InstallFailure(
+ kind: InstallFailureKind.runtime,
title: 'Claude Code is not installed on this machine.',
body: '$harnessName runs on Claude Code. Install it, then retry.',
command: 'npm install -g @anthropic-ai/claude-code',
@@ -247,6 +327,7 @@ InstallFailure describeInstallFailure(DshInstallRun run, String harnessName) {
}
if (lower.startsWith('uv')) {
return const InstallFailure(
+ kind: InstallFailureKind.runtime,
title: 'uv is not installed on this machine.',
body: 'The toolchain is a Python environment that uv builds. Install it, then retry.',
command: 'curl -LsSf https://astral.sh/uv/install.sh | sh',
@@ -254,26 +335,61 @@ InstallFailure describeInstallFailure(DshInstallRun run, String harnessName) {
}
if (lower.startsWith('node')) {
return InstallFailure(
+ kind: InstallFailureKind.runtime,
title: 'Node.js is missing or too old.',
body: text,
command: 'brew install node@22',
);
}
if (lower.contains('doctor still running')) {
- return InstallFailure(
+ return const InstallFailure(
+ kind: InstallFailureKind.runtime,
title: 'The check is taking longer than five minutes.',
body: 'Usually the first load of a large toolchain. Retry runs only the check again.',
);
}
if (lower.contains('clone') || lower.contains('git ')) {
+ return _downloadFailure(text, harnessName);
+ }
+ if (miss != null) {
+ // A doctor line this does not know a command for: still what is missing,
+ // said as that rather than as the bare check line.
return InstallFailure(
- title: 'Could not download $harnessName.',
+ kind: InstallFailureKind.runtime,
+ title: 'Missing on this machine: $text',
+ hint: 'Install it, then try again.',
+ );
+ }
+ if (code == 'SETUP_FAILED' || code == 'DOCTOR_FAILED') {
+ return InstallFailure(
+ kind: InstallFailureKind.runtime,
+ title: code == 'SETUP_FAILED'
+ ? 'Setting up the $harnessName toolchain failed on this machine.'
+ : '$harnessName is installed, but the check found something missing.',
body: text,
);
}
return InstallFailure(title: text);
}
+/// A failed download: the network when git said so (or when the daemon
+/// already retried it, which it does only for the network), else whatever git
+/// said — a repository that is not there, a ref that is not.
+InstallFailure _downloadFailure(String text, String harnessName) {
+ final tries = _gaveUp.firstMatch(text)?.group(1);
+ final transient = tries != null || _transientGit.hasMatch(text);
+ return InstallFailure(
+ kind: transient ? InstallFailureKind.network : InstallFailureKind.unknown,
+ title: 'Could not download $harnessName.',
+ body: text,
+ hint: tries != null
+ ? 'Tried $tries times. Check the connection on this machine, then try again.'
+ : transient
+ ? 'Usually the network. Try again.'
+ : null,
+ );
+}
+
class _Step {
const _Step(this.phase, this.name);
final String phase;
@@ -459,17 +575,18 @@ class _FailureCard extends StatelessWidget {
color: grid.AppPalette.textPrimary,
),
),
- if (failure.body != null)
- Padding(
- padding: const EdgeInsets.only(top: 2),
- child: Text(
- failure.body!,
- style: TextStyle(
- fontSize: 12,
- color: grid.AppPalette.textSecondary,
+ for (final line in [failure.body, failure.hint])
+ if (line != null)
+ Padding(
+ padding: const EdgeInsets.only(top: 2),
+ child: Text(
+ line,
+ style: TextStyle(
+ fontSize: 12,
+ color: grid.AppPalette.textSecondary,
+ ),
),
),
- ),
if (failure.command != null)
Padding(
padding: const EdgeInsets.only(top: 6),
diff --git a/desktop/test/dsh_catalog_test.dart b/desktop/test/dsh_catalog_test.dart
index d15944e66..847ab7127 100644
--- a/desktop/test/dsh_catalog_test.dart
+++ b/desktop/test/dsh_catalog_test.dart
@@ -140,7 +140,10 @@ void main() {
const WsRequestTimeout('dsh_update'),
'Test host is still updating. Try again in a few minutes.',
),
- (StateError('disconnected'), 'Update failed on Test host'),
+ (
+ StateError('disconnected'),
+ 'Lost the connection to Test host while updating — it may still be finishing there. Try again in a moment.',
+ ),
]) {
test(
'update failure $response preserves installed versions and allows retry',
@@ -331,6 +334,81 @@ void main() {
app.stateOf('m')!.dsh.installs['autonomous/autonomous-circuit']!.failed,
isTrue,
);
+ expect(
+ app.stateOf('m')!.dsh.runs['autonomous/autonomous-circuit']!.code,
+ 'UNSUPPORTED',
+ );
+ });
+
+ test('the machine\'s own failed push and the reply close ONE run, with the code and the doctor lines kept', () async {
+ final install = Completer<Map<String, dynamic>>();
+ final connection = _Connection()
+ ..answer = (type, _) => type == 'dsh_install'
+ ? install.future
+ : Future.value({'dsh': <Object>[]});
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ final result = app.installDsh('m', 'autonomous/autonomous-circuit');
+ final catalog = app.stateOf('m')!.dsh;
+ for (final push in [
+ {'phase': 'doctor', 'line': 'ok git'},
+ {'phase': 'doctor', 'line': 'miss kicad-cli'},
+ {
+ 'phase': 'failed',
+ 'detail': 'doctor failed · miss kicad-cli',
+ 'error': 'DOCTOR_FAILED',
+ },
+ ]) {
+ await app.handleEventForTest('m', {
+ 'type': 'dsh_install_status',
+ 'payload': {'id': 'autonomous/autonomous-circuit', ...push},
+ });
+ }
+ final run = catalog.runs['autonomous/autonomous-circuit']!;
+ expect(run.code, 'DOCTOR_FAILED');
+ install.completeError(
+ const WsRequestFailure(
+ responseType: 'dsh_install',
+ code: 'DOCTOR_FAILED',
+ detail: 'doctor failed · miss kicad-cli',
+ ),
+ );
+ expect(await result, 'doctor failed · miss kicad-cli');
+ expect(catalog.runs['autonomous/autonomous-circuit'], same(run));
+ expect(run.checks, ['ok git', 'miss kicad-cli']);
+ expect(run.phases.map((p) => p.phase), ['clone', 'doctor', 'failed']);
+ expect(
+ catalog.installs['autonomous/autonomous-circuit']!.code,
+ 'DOCTOR_FAILED',
+ );
+ });
+
+ test('a socket that drops under an install says so, not "failed", and the list is asked again on reconnect', () async {
+ final connection = _Connection()
+ ..answer = (type, _) => type == 'dsh_install'
+ ? Future.error(Exception('WS disconnected'))
+ : Future.value({
+ 'dsh': [
+ {..._circuit, 'installed': true},
+ ],
+ });
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ expect(
+ await app.installDsh('m', 'autonomous/autonomous-circuit'),
+ 'Lost the connection to Test host while installing — it may still be finishing there. Try again in a moment.',
+ );
+ final catalog = app.stateOf('m')!.dsh;
+ expect(catalog.runs['autonomous/autonomous-circuit']!.code, 'CONNECTION');
+ expect(connection.calls.map((c) => c.$1), ['dsh_install']);
+ app.onMachineConnectedForTest('m');
+ await Future<void>.delayed(Duration.zero);
+ expect(connection.calls.where((c) => c.$1 == 'dsh_list'), hasLength(1));
+ expect(catalog['autonomous/autonomous-circuit']!.installed, isTrue);
+ // Once: the next reconnect has nothing new to ask about.
+ app.onMachineConnectedForTest('m');
+ await Future<void>.delayed(Duration.zero);
+ expect(connection.calls.where((c) => c.$1 == 'dsh_list'), hasLength(1));
});
}
@@ -466,6 +544,26 @@ void _installRunTests() {
.line,
isNull,
);
+ // The reason as a code: a short upper-case token or nothing.
+ expect(
+ DshInstallProgress.fromJson({
+ 'id': 'a/b',
+ 'phase': 'failed',
+ 'error': 'CLONE_FAILED',
+ })!.code,
+ 'CLONE_FAILED',
+ );
+ for (final bad in ['', 'clone failed', 'x' * 60, 7]) {
+ expect(
+ DshInstallProgress.fromJson({
+ 'id': 'a/b',
+ 'phase': 'failed',
+ 'error': bad,
+ })!.code,
+ isNull,
+ reason: '$bad',
+ );
+ }
});
test(
diff --git a/desktop/test/dsh_install_panel_test.dart b/desktop/test/dsh_install_panel_test.dart
index e0ee4abd8..6a820a4a3 100644
--- a/desktop/test/dsh_install_panel_test.dart
+++ b/desktop/test/dsh_install_panel_test.dart
@@ -291,12 +291,23 @@ void main() {
});
group('describeInstallFailure', () {
- InstallFailure describe({List<String> lines = const [], String? detail}) {
+ InstallFailure describe({
+ List<String> lines = const [],
+ String? detail,
+ String? code,
+ }) {
final run = DshInstallRun('a/b', startedAt: _t0);
for (final line in lines) {
run.apply(DshInstallProgress(id: 'a/b', phase: 'doctor', line: line));
}
- run.apply(DshInstallProgress(id: 'a/b', phase: 'failed', detail: detail));
+ run.apply(
+ DshInstallProgress(
+ id: 'a/b',
+ phase: 'failed',
+ detail: detail,
+ code: code,
+ ),
+ );
return describeInstallFailure(run, 'Typst');
}
@@ -334,7 +345,101 @@ void main() {
expect(unknown.title, 'disk full');
expect(unknown.body, isNull);
expect(unknown.command, isNull);
+ expect(unknown.kind, InstallFailureKind.unknown);
expect(describe().title, 'Install failed');
});
+
+ test('the code says which kind of failure, before any wording is read', () {
+ // The network: git's words, and the daemon's own retries, both count.
+ final stalled = describe(
+ code: 'CLONE_FAILED',
+ detail: 'git clone exited 128: error: RPC failed; curl 28 Operation too slow',
+ );
+ expect(stalled.kind, InstallFailureKind.network);
+ expect(stalled.title, 'Could not download Typst.');
+ expect(stalled.hint, 'Usually the network. Try again.');
+ final gaveUp = describe(
+ code: 'CLONE_FAILED',
+ detail:
+ 'git clone exited 128: fatal: early EOF · gave up after 3 attempts',
+ );
+ expect(gaveUp.kind, InstallFailureKind.network);
+ expect(
+ gaveUp.hint,
+ 'Tried 3 times. Check the connection on this machine, then try again.',
+ );
+ // A repository that is not there is a failed download, but not the network.
+ final gone = describe(
+ code: 'CLONE_FAILED',
+ detail: 'git clone exited 128: fatal: repository not found',
+ );
+ expect(gone.kind, InstallFailureKind.unknown);
+ expect(gone.title, 'Could not download Typst.');
+ expect(gone.hint, isNull);
+ // A daemon too old to send a code: the same words, read from git.
+ final old = describe(detail: 'git clone exited 128: fatal: early EOF');
+ expect(old.kind, InstallFailureKind.network);
+
+ final broken = describe(
+ code: 'INVALID_MANIFEST',
+ detail: 'no harness.json in /tmp/x',
+ );
+ expect(broken.kind, InstallFailureKind.package);
+ expect(broken.title, 'The Typst package is broken.');
+ expect(broken.body, 'no harness.json in /tmp/x');
+ expect(broken.hint, contains('will not help'));
+
+ final busy = describe(
+ code: 'DSH_BUSY',
+ detail: 'a/b is already being installed, updated or removed.',
+ );
+ expect(busy.kind, InstallFailureKind.busy);
+ expect(busy.title, 'Already installing Typst on this machine.');
+
+ final lost = describe(
+ code: 'CONNECTION',
+ detail: 'Lost the connection to studio while installing.',
+ );
+ expect(lost.kind, InstallFailureKind.network);
+ expect(lost.title, 'Lost the connection to studio while installing.');
+ final lostAfterDoctor = describe(
+ code: 'CONNECTION',
+ lines: ['miss uv'],
+ detail: 'Lost the connection to studio while installing.',
+ );
+ expect(
+ lostAfterDoctor.title,
+ 'Lost the connection to studio while installing.',
+ );
+
+ final setup = describe(
+ code: 'SETUP_FAILED',
+ detail: 'setup exited 1 · npm ERR! code EACCES',
+ );
+ expect(setup.kind, InstallFailureKind.runtime);
+ expect(
+ setup.title,
+ 'Setting up the Typst toolchain failed on this machine.',
+ );
+ expect(setup.body, 'setup exited 1 · npm ERR! code EACCES');
+
+ // A doctor miss the table knows still wins over the generic doctor sentence.
+ final uv = describe(
+ code: 'DOCTOR_FAILED',
+ lines: ['miss uv (https://docs.astral.sh/uv)'],
+ );
+ expect(uv.kind, InstallFailureKind.runtime);
+ expect(uv.command, 'curl -LsSf https://astral.sh/uv/install.sh | sh');
+ final other = describe(
+ code: 'DOCTOR_FAILED',
+ lines: ['miss typst-cli (cargo install typst-cli)'],
+ );
+ expect(other.kind, InstallFailureKind.runtime);
+ expect(
+ other.title,
+ 'Missing on this machine: typst-cli (cargo install typst-cli)',
+ );
+ expect(other.hint, 'Install it, then try again.');
+ });
});
}
diff --git a/desktop/test/store_page_test.dart b/desktop/test/store_page_test.dart
index c82774abf..549d49850 100644
--- a/desktop/test/store_page_test.dart
+++ b/desktop/test/store_page_test.dart
@@ -280,10 +280,7 @@ void main() {
);
expect(find.text('Your projects and files are kept.'), findsOneWidget);
expect(find.text('aaaaaaaa'), findsOneWidget);
- expect(
- find.text('Resume Harness'),
- findsNothing,
- );
+ expect(find.text('Resume Harness'), findsNothing);
expect(find.text('New Harness'), findsNothing);
app.updateGate = Completer<String?>();
await tester.tap(_key('store-primary-action'));
@@ -347,10 +344,7 @@ void main() {
);
await tester.enterText(_key('store-search'), 'Updateable');
await tester.pumpAndSettle();
- expect(
- find.text('New Harness'),
- findsNothing,
- );
+ expect(find.text('New Harness'), findsNothing);
await tester.tap(_key('store-card:${entry.id}'));
await tester.pumpAndSettle();
expect(_key('store-page:${entry.id}'), findsOneWidget);
@@ -369,7 +363,10 @@ void main() {
]);
app.changed();
await tester.pumpAndSettle();
- expect(_in('store-primary-action', find.text('New Harness')), findsOneWidget);
+ expect(
+ _in('store-primary-action', find.text('New Harness')),
+ findsOneWidget,
+ );
},
);
// Real glyph widths: the review dialog's buttons are laid out against Arial,
@@ -581,7 +578,10 @@ void main() {
(tester) async {
final (app, _) = await _open(tester, initialHarness: 'autonomous/marp');
final tabs = app.swarms.length;
- expect(_in('store-primary-action', find.text('New Harness')), findsOneWidget);
+ expect(
+ _in('store-primary-action', find.text('New Harness')),
+ findsOneWidget,
+ );
await tester.tap(_key('store-primary-action'));
await tester.pumpAndSettle();
expect(
@@ -685,11 +685,54 @@ void main() {
..apply(DshInstallProgress(id: _typst.id, phase: 'failed'));
app.changed();
await tester.pumpAndSettle();
- says('miss typst-cli (cargo install typst-cli)');
+ says(
+ 'Missing on this machine: typst-cli (cargo install typst-cli) Install it, then try again.',
+ );
await tester.tap(_key('store-primary-action'));
await tester.pumpAndSettle();
expect(app.installs, [('machine-1', _typst.id)]);
+ // A fetch the network dropped (issue #109): the line says so, says what
+ // to do, and keeps git's own words a hover away. A broken package says
+ // that retrying is not the fix.
+ local.dsh.runs[_typst.id] = DshInstallRun(_typst.id)
+ ..apply(DshInstallProgress(id: _typst.id, phase: 'clone'))
+ ..apply(
+ DshInstallProgress(
+ id: _typst.id,
+ phase: 'failed',
+ code: 'CLONE_FAILED',
+ detail: 'git clone exited 128: error: RPC failed; curl 28 Operation too slow · gave up after 3 attempts',
+ ),
+ );
+ app.changed();
+ await tester.pumpAndSettle();
+ says(
+ 'Could not download Typst. Tried 3 times. Check the connection on this machine, then try again.',
+ );
+ expect(
+ tester.widget<Tooltip>(_key('store-install-failure-detail')).message,
+ contains('curl 28 Operation too slow'),
+ );
+ expect(
+ _in('store-primary-action', find.text('Try again')),
+ findsOneWidget,
+ );
+ local.dsh.runs[_typst.id] = DshInstallRun(_typst.id)
+ ..apply(
+ DshInstallProgress(
+ id: _typst.id,
+ phase: 'failed',
+ code: 'INVALID_MANIFEST',
+ detail: 'no harness.json in /tmp/x',
+ ),
+ );
+ app.changed();
+ await tester.pumpAndSettle();
+ says(
+ 'The Typst package is broken. Trying again will not help — this needs a fix in the Store.',
+ );
+
local.dsh.runs.clear();
local.dsh.loaded = false;
for (final (error, label) in <(String?, String)>[
@@ -724,7 +767,10 @@ void main() {
app.changed();
await tester.pumpAndSettle();
says('Installed · linked to a checkout');
- expect(_in('store-primary-action', find.text('New Harness')), findsOneWidget);
+ expect(
+ _in('store-primary-action', find.text('New Harness')),
+ findsOneWidget,
+ );
expect(_key('store-remove:machine-1'), findsOneWidget);
},
);
@@ -833,7 +879,10 @@ void main() {
]);
app.changed();
await tester.pumpAndSettle();
- expect(_in('store-primary-action', find.text('New Harness')), findsOneWidget);
+ expect(
+ _in('store-primary-action', find.text('New Harness')),
+ findsOneWidget,
+ );
},
);
@@ -1245,10 +1294,7 @@ void main() {
await tester.pumpAndSettle();
final tabs = app.swarms.length;
- expect(
- find.text('Get'),
- findsNothing,
- );
+ expect(find.text('Get'), findsNothing);
await tester.ensureVisible(_key('store-card:autonomous/typst'));
await tester.tap(_key('store-card:autonomous/typst'));
await tester.pumpAndSettle();
@@ -1273,15 +1319,15 @@ void main() {
);
app.changed();
await tester.pumpAndSettle();
- expect(
- find.text('New Harness'),
- findsNothing,
- );
+ expect(find.text('New Harness'), findsNothing);
await tester.ensureVisible(_key('store-card:autonomous/typst'));
await tester.tap(_key('store-card:autonomous/typst'));
await tester.pumpAndSettle();
expect(_key('store-page:autonomous/typst'), findsOneWidget);
- expect(_in('store-primary-action', find.text('New Harness')), findsOneWidget);
+ expect(
+ _in('store-primary-action', find.text('New Harness')),
+ findsOneWidget,
+ );
await tester.tap(_key('store-primary-action'));
await tester.pumpAndSettle();
expect(
@@ -1339,6 +1385,7 @@ void main() {
expect(find.text('New Harness'), findsNothing);
expect(find.text('Get'), findsNothing);
}
+
expectBrowseOnly(); // Discover.
await tester.tap(_key('store-shelf-category:$category'));
await tester.pumpAndSettle();
diff --git a/desktop/test/store_tab_state_test.dart b/desktop/test/store_tab_state_test.dart
index 9caead562..cd110d7a1 100644
--- a/desktop/test/store_tab_state_test.dart
+++ b/desktop/test/store_tab_state_test.dart
@@ -311,7 +311,7 @@ void main() {
);
expect(
await answered(() => Future.error(StateError('socket closed'))),
- 'Install failed on Test host',
+ 'Lost the connection to Test host while installing — it may still be finishing there. Try again in a moment.',
);
expect(catalog.installs['autonomous/typst']!.failed, isTrue);
expect(