Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Anchor the update-install suppression to the previous session's death (PRD-8415) (#3943)

serafin-garciae26f10382f55
diff --git a/.changeset/home-path-username-scrub.md b/.changeset/home-path-username-scrub.md
new file mode 100644
index 000000000..4e9848922
--- /dev/null
+++ b/.changeset/home-path-username-scrub.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Bug reports no longer carry your account name when a path stops at your home folder. Diagnostic bundles replace the path to your user folder with `~`, and until now that only worked when something followed the folder in the text. A log line or a note ending at the folder itself, which is the most common way it appears, went out with the account name intact on Windows, macOS and Linux alike. Those are now replaced too, and a line carrying two such paths now has both replaced where before the second one survived.
diff --git a/.changeset/install-kill-late-reopen.md b/.changeset/install-kill-late-reopen.md
new file mode 100644
index 000000000..e62cb94ac
--- /dev/null
+++ b/.changeset/install-kill-late-reopen.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+After an update installs, the next launch no longer asks you to report a crash, even if that launch is days later. Installing an update shuts the running app down so its files can be replaced, and the app used to recognize that shutdown as the installer's doing only if you reopened within half an hour. It now judges the previous session by when it actually ended rather than by how soon you came back, so reopening the next morning reads the same as reopening straight away. That holds whether or not the install landed.
+
+A small number of update shutdowns can still produce the prompt. A real crash still prompts, and you can report one at any time from Help → Report a bug…
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index 745c10230..214d1e208 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -45,7 +45,7 @@ On every platform the app writes app-level state and logs on launch. The table b
| `~/Library/Caches/@inkeepopen-knowledge-desktop-updater/` | Staged auto-update downloads (electron-updater) | Outside-project (home dir) |
| `~/Library/Caches/com.inkeep.open-knowledge.ShipIt/` | Install log of the macOS update helper (Squirrel's ShipIt), which swaps the app bundle after the app has quit. The only record of why an update failed to install, so a bug report you send collects it — only this app's, never those of other applications that use the same update mechanism | Outside-project (home dir) |
| `~/Library/Application Support/OpenKnowledge/Crashpad/` | Native crash minidumps, written by the OS crash handler (Electron's Crashpad) if the app ever crashes. Local-only: the crash reporter runs with `uploadToServer: false`, so no dump is ever uploaded automatically | Outside-project (home dir) |
-| `~/Library/Application Support/OpenKnowledge/bug-report-dirty-shutdown.json` | Dirty-shutdown sentinel — written on **every** launch, refreshed as it runs, and removed on a clean quit. The next launch reads it to tell an app crash (prompts you) from the machine ending the session — a reboot, an OS shutdown, or dying asleep (suppressed and logged instead) | Outside-project (home dir) |
+| `~/Library/Application Support/OpenKnowledge/bug-report-dirty-shutdown.json` | Dirty-shutdown sentinel — written on **every** launch, refreshed as it runs, and removed on a clean quit. The next launch reads it to tell an app crash (prompts you) from the endings that are not a crash: a reboot, an OS shutdown, or dying asleep (all suppressed and logged instead), and an update install shutting the app down to replace its files (logged either way, and suppressed in almost every case: a shutdown the app had no chance to record, or one it cannot date because the previous session left no heartbeat, can still prompt so you are able to report it) | Outside-project (home dir) |
| `~/Library/Application Support/OpenKnowledge/bug-report-crash-acks.json` | Records which crash-report invitations you already answered or dismissed, so the same crash never re-prompts | Outside-project (home dir) |
The app registers the `openknowledge://` URL scheme (for deep links) and checks for updates — on launch and periodically while it runs — against the OpenKnowledge update service at `openknowledge.ai/updates`, which redirects to the GitHub release asset and counts the update per version and channel (falling back to GitHub directly if it's unreachable). On macOS and Windows an update on your channel downloads in the background and installs on the next quit; on Linux — where there is no apt/rpm repository — the app downloads the new deb/rpm from the release feed and asks you to authorize the install (a `pkexec` password prompt) each time. You can also check on demand from **Check for updates…** in the app and Help menus. The channel (stable or beta) is fixed by the build you installed. Reinstall a stable build for any supported platform from `openknowledge.ai/download`. The `/download/beta` shortcut serves the latest Apple Silicon macOS beta; Windows and Linux beta installers are available from [GitHub Releases](https://github.com/inkeep/open-knowledge/releases). Override the feed with `OK_UPDATER_FEED_URL`.
diff --git a/knip.config.ts b/knip.config.ts
index 49222af47..0bd60f15f 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -125,7 +125,9 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index d7a845280..dfd95ef49 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,3 +1,4 @@
+
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 005627195..8bfdb40cd 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,3 +1,4 @@
+
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/divergence-locate.ts b/packages/core/src/bridge/divergence-locate.ts
index 6b505314d..d979f4b39 100644
--- a/packages/core/src/bridge/divergence-locate.ts
+++ b/packages/core/src/bridge/divergence-locate.ts
@@ -1,3 +1,4 @@
+
import { findFirstDivergenceIndex } from './tolerance-telemetry.ts';
export const BRIDGE_LINE_KINDS = [
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 8fb428b90..01ef76a9f 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 9d9c244b0..463e89595 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,3 +1,4 @@
+
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.ts
index c43fdd7e7..0939885bb 100644
--- a/packages/core/src/bridge/intraline-predicate.ts
+++ b/packages/core/src/bridge/intraline-predicate.ts
@@ -1,3 +1,4 @@
+
export function rawLineCounts(doc: string): Map<string, number> {
const counts = new Map<string, number>();
for (const line of doc.split('\n')) {
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index 251560a35..c0dc65705 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -65,6 +65,7 @@ export function tryLineLevelCombine(
return { clean: true, merged };
}
+
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index 01ac80099..dcc5b0690 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,3 +1,4 @@
+
import { stripFrontmatter } from '../extensions/frontmatter.ts';
import { bodyEdgeEmpties } from './doc-boundary-space.ts';
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index bb53e7c7c..4f7b79587 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,6 +32,7 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
+
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -128,6 +129,7 @@ export interface ComparePmStructuralOptions {
rawSourceSide?: 'expected';
}
+
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -253,6 +255,7 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
+
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index af20de1e2..dca644141 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,3 +1,4 @@
+
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/logging/qa-secret-pattern-canary.test.ts b/packages/core/src/logging/qa-secret-pattern-canary.test.ts
index 77e57304e..cb63d2511 100644
--- a/packages/core/src/logging/qa-secret-pattern-canary.test.ts
+++ b/packages/core/src/logging/qa-secret-pattern-canary.test.ts
@@ -26,6 +26,13 @@ const PLANTED: Record<string, { input: string; secret: string; marker: string }>
secret: '/home/alice/',
marker: '~/',
},
+ 'windows-home-path': {
+ // JSON-escaped, which is the form the NDJSON log sinks actually write and
+ // the one a single-backslash rule would miss.
+ input: String.raw`{"path":"C:\\Users\\alice\\AppData\\Roaming\\OpenKnowledge\\state.json"}`,
+ secret: String.raw`C:\\Users\\alice`,
+ marker: '~',
+ },
'github-pat': {
input: 'token was ghp_0123456789abcdefghijklmnopqrstuvwxyz sent',
secret: 'ghp_0123456789abcdefghijklmnopqrstuvwxyz',
diff --git a/packages/core/src/logging/secret-scrub.test.ts b/packages/core/src/logging/secret-scrub.test.ts
index 34a8f2295..d17efd62d 100644
--- a/packages/core/src/logging/secret-scrub.test.ts
+++ b/packages/core/src/logging/secret-scrub.test.ts
@@ -16,6 +16,9 @@ describe('scrubbing a serialized JSON payload', () => {
{ event: 'ok-x', detail: 'authorization: Bearer abc123', docName: 'notes/b' },
{ event: 'ok-x', authorization: 'Bearer abc123', docName: 'notes/c' },
{ a: '/home/alice', b: { c: 'x/y' } },
+ // An escaped quote inside the value: a body that stops on the backslash
+ // takes it, and the content quote left behind closes the string early.
+ { msg: 'content dir /Users/alice missing entry "plan"' },
{ token: 'ghp_0123456789abcdefghijklmnopqrstuvwxyz', docName: 'notes/d' },
];
for (const payload of payloads) {
@@ -169,6 +172,179 @@ describe('redactSecrets', () => {
expect(SECRET_PATTERN_NAMES).toContain('github-pat');
});
+ it('leaves a scrubbed Windows path in a JSON log line still parseable', () => {
+ // The bug-bundle stages NDJSON log files and triage reads them back as
+ // JSON, so a rule that swaps a doubled separator for a single one turns
+ // every affected line into an invalid escape. The account name still has
+ // to go, on both the raw and the JSON-escaped form of the same path.
+ const winPath = String.raw`C:\Users\alice\AppData\Roaming\OpenKnowledge\state.json`;
+ const line = JSON.stringify({ err: { code: 'EACCES', path: winPath } });
+
+ const result = redactSecrets(line);
+ expect(result.patterns).toContain('windows-home-path');
+ expect(result.redacted).not.toContain('alice');
+ expect(() => JSON.parse(result.redacted) as unknown).not.toThrow();
+ expect((JSON.parse(result.redacted) as { err: { path: string } }).err.path).toBe(
+ String.raw`~\AppData\Roaming\OpenKnowledge\state.json`,
+ );
+
+ const raw = redactSecrets(`could not read ${winPath}`);
+ expect(raw.patterns).toContain('windows-home-path');
+ expect(raw.redacted).not.toContain('alice');
+ });
+
+ it('scrubs a Windows profile root that ends at the account name', () => {
+ // `os.homedir()` and `USERPROFILE` both stop at the account name, so this
+ // is the form the value most often takes. A rule that only terminates on a
+ // trailing separator matches none of these and leaks the account name from
+ // the two places it is most likely to appear: a serialised path field, and
+ // a bug note the reporter typed by hand.
+ const root = String.raw`C:\Users\alice`;
+
+ const quoted = redactSecrets(JSON.stringify({ homedir: root }));
+ expect(quoted.patterns).toContain('windows-home-path');
+ expect(quoted.redacted).not.toContain('alice');
+ expect((JSON.parse(quoted.redacted) as { homedir: string }).homedir).toBe('~');
+
+ const mixed = redactSecrets(JSON.stringify({ homedir: root, userData: `${root}\\AppData` }));
+ expect(mixed.redacted).not.toContain('alice');
+ expect(JSON.parse(mixed.redacted)).toEqual({ homedir: '~', userData: String.raw`~\AppData` });
+
+ const bare = redactSecrets(`I saved it in ${root}`);
+ expect(bare.patterns).toContain('windows-home-path');
+ expect(bare.redacted).toBe('I saved it in ~');
+ });
+
+ it('leaves the carriage return in place on a CRLF line', () => {
+ // Content is split on `\n` alone, so a CRLF line arrives here still holding
+ // its `\r`. The run has to stop before it rather than consume it, or the
+ // one redacted line silently converts to LF while the rest of the file
+ // keeps CRLF. The carriage return is also why the run excludes it and the
+ // alternation admits it together: exclude it alone and there is nowhere for
+ // the run to stop, so the match fails and the account name survives.
+ const prose = redactSecrets('open C:\\Users\\alice failed\r');
+ expect(prose.redacted).not.toContain('alice');
+ expect(prose.redacted).toBe('open ~\r');
+
+ const bare = redactSecrets('C:\\Users\\alice\r');
+ expect(bare.redacted).toBe('~\r');
+
+ const multi = redactSecrets('a C:\\Users\\alice\r\nb C:\\Users\\bob\\AppData\r\n');
+ expect(multi.redacted).not.toContain('alice');
+ expect(multi.redacted).not.toContain('bob');
+ expect(multi.redacted).toBe('a ~\r\nb ~\\AppData\r\n');
+ });
+
+ it('scrubs a POSIX home root that ends at the account name', () => {
+ // Same shape as the Windows root above, and the same reason: `os.homedir()`
+ // stops at the account name on every platform. A rule that only terminates
+ // on a trailing separator leaks it from exactly the two places it is most
+ // likely to appear.
+ const mac = redactSecrets('crashed while reading /Users/alice');
+ expect(mac.patterns).toContain('macos-home-path');
+ expect(mac.redacted).toBe('crashed while reading ~');
+
+ const linux = redactSecrets('crashed while reading /home/alice');
+ expect(linux.patterns).toContain('linux-home-path');
+ expect(linux.redacted).toBe('crashed while reading ~');
+
+ const sep = redactSecrets('/Users/alice/notes and /home/bob/notes');
+ expect(sep.redacted).toBe('~/notes and ~/notes');
+ });
+
+ it('keeps a POSIX match inside its JSON string value', () => {
+ // Without the quote terminator the run crosses the closing quote and eats
+ // every field after it, which both destroys the structure triage reads and
+ // leaves the account name sitting in what survives. The two-field case is
+ // the one that shows it, since a single field hides the damage.
+ const line = JSON.stringify({ a: '/Users/alice', b: '/Users/alice/x' });
+
+ const result = redactSecrets(line);
+ expect(result.redacted).not.toContain('alice');
+ expect(() => JSON.parse(result.redacted) as unknown).not.toThrow();
+ expect(JSON.parse(result.redacted)).toEqual({ a: '~', b: '~/x' });
+
+ // And with the value ending ON a backslash, which is the form a path
+ // actually carries once stringified. This is where the two halves meet:
+ // the run stops at the closing quote AND hands its trailing backslashes
+ // back, so the escape pair survives and the string still closes. Pinned
+ // apart from the bare-prose give-back because a future edit that branches
+ // on the terminator could break the conjunction while both halves pass.
+ const trailing = redactSecrets(JSON.stringify({ p: '/home/alice\\' }));
+ expect(trailing.redacted).not.toContain('alice');
+ expect(() => JSON.parse(trailing.redacted) as unknown).not.toThrow();
+ expect(JSON.parse(trailing.redacted)).toEqual({ p: '~\\' });
+ });
+
+ it('does not redact a lowercase REST path segment as a POSIX home root', () => {
+ // The counterweight to the Windows rule's case-insensitivity, and the
+ // reason the two POSIX rules cannot copy it: `/users/<id>/` is a routine
+ // API route, and matching it would re-root live request logs at `~`.
+ const result = redactSecrets('GET https://api.example.com/users/12345/profile 200');
+
+ expect(result.patterns).toEqual([]);
+ expect(result.redacted).toBe('GET https://api.example.com/users/12345/profile 200');
+ });
+
+ it('scrubs a lowercase Windows profile root', () => {
+ // Windows paths are case-insensitive and reach the logs in whatever case
+ // the producer used, so the canonical capitalisation cannot be assumed.
+ // The drive letter is what makes this safe to match loosely here.
+ const result = redactSecrets(String.raw`opening c:\users\alice\AppData`);
+
+ expect(result.patterns).toContain('windows-home-path');
+ expect(result.redacted).not.toContain('alice');
+ expect(result.redacted).toBe(String.raw`opening ~\AppData`);
+ });
+
+ it('over-redacts prose after a terminal Windows profile root rather than leaking it', () => {
+ // Spaces are admitted so a profile folder containing one still matches, and
+ // the cost is that trailing prose goes with it. Pinned because it is a
+ // deliberate trade, not a defect: the alternative is leaving the account
+ // name in place.
+ const result = redactSecrets(String.raw`profile C:\Users\alice failed, retry`);
+
+ expect(result.redacted).not.toContain('alice');
+ expect(result.redacted).toBe('profile ~');
+ });
+
+ it('over-redacts prose after a terminal POSIX home root rather than leaking it', () => {
+ // The same deliberate trade as the Windows case above, pinned separately
+ // because the POSIX rules reach it differently: their body admits a
+ // backslash and gives one back at the end, and that give-back must not
+ // shorten the match on a line that ends in prose instead.
+ const result = redactSecrets('profile /home/alice failed, retry');
+
+ expect(result.redacted).not.toContain('alice');
+ expect(result.redacted).toBe('profile ~');
+
+ // The give-back itself, which the line above never reaches, having no
+ // backslash in it. A run ending on one hands it back rather than consuming
+ // it, which is what keeps a `\"` escape pair intact. A rule that consumed
+ // its terminator took the backslash too, so this pins the shape and not
+ // only the trade.
+ // Written with escapes rather than `String.raw` because a raw template
+ // cannot end on a backslash: it escapes the closing backtick even there.
+ expect(redactSecrets('profile /home/alice failed, retry\\').redacted).toBe('profile ~\\');
+
+ // And at two, which is the form NDJSON actually carries: one logical
+ // trailing backslash is two literal ones once stringified. Generalizes the
+ // give-back rather than pinning a single instance of it, so a post-hoc
+ // strip of one trailing backslash would not pass for the same behaviour.
+ expect(redactSecrets('profile /home/alice failed, retry\\\\').redacted).toBe('profile ~\\\\');
+ });
+
+ it('masks both account names when one line carries two home paths', () => {
+ // A rule that consumed its terminator ate the separator that opened the
+ // second path, and the second name then shipped. Windows is the sharp case:
+ // both separators are backslashes, so nothing but the lookahead ends the
+ // first run before the next drive letter.
+ expect(scrubSecrets('home=/Users/alice contentDir=/Users/bob/notes')).not.toContain('alice');
+ expect(scrubSecrets('home=/Users/alice contentDir=/Users/bob/notes')).not.toContain('bob');
+ expect(scrubSecrets(String.raw`a=C:\Users\alice b=C:\Users\bob`)).not.toContain('alice');
+ expect(scrubSecrets(String.raw`a=C:\Users\alice b=C:\Users\bob`)).not.toContain('bob');
+ });
+
it('counts a line carrying two secrets once, not once per matching pattern', () => {
// `lineCount` is a distinct-modified-line count surfaced to users as
// "N line(s) scrubbed" — a single line with a token and a home path is one
diff --git a/packages/core/src/logging/secret-scrub.ts b/packages/core/src/logging/secret-scrub.ts
index 8416a3753..4e10ad918 100644
--- a/packages/core/src/logging/secret-scrub.ts
+++ b/packages/core/src/logging/secret-scrub.ts
@@ -133,24 +133,104 @@ const SECRET_PATTERNS: readonly SecretPattern[] = [
regex: /("[Aa]uthorization"\s*:\s*"[Bb]earer\s+)(?:\\"[^"\\]+\\"|[^"\\]+)/g,
replacement: '$1[REDACTED]',
},
- // Cosmetic, and LAST on purpose. These collapse a home directory to `~/`,
+ // Cosmetic, and LAST on purpose. These collapse a home directory to `~`,
// which is lossy in a way a credential pattern is not: the match consumes the
// segment it replaces. Run ahead of the credential patterns, they could eat
- // text one of those still needs to recognise its own match — a `/Users/<name>/`
- // run reaching across a `://` leaves no `://` for the URL-credential pattern to
- // anchor on, and the credential then ships verbatim.
+ // text one of those still needs to recognise its own match. A `/Users/<name>/`
+ // run reaching across a `://` leaves no `://` for the URL-credential pattern
+ // to anchor on, and the credential then ships verbatim.
//
- // The bodies exclude the quote and NOTHING else. A space or a backslash is a
- // legal part of an account name — `/Users/Jane Doe/` is the macOS shape this
- // repo's own fixtures use — and excluding either silently stopped those from
- // being masked at all, which on the file's only two privacy patterns is the
- // wrong direction to be wrong in.
+ // All three match the root plus the account name, and none of them consume
+ // what ends the name. Whatever that is, a path separator, a closing quote, a
+ // carriage return or the end of the line, stays in the text, so a quote still
+ // closes its JSON string, a CRLF line keeps its ending, and `/Users/x/y` still
+ // reads `~/y` after.
+ // Requiring a trailing separator instead would miss the most common form of
+ // the value, since `os.homedir()` and `USERPROFILE` both end at the account
+ // name, and that bare root is also what a reporter pastes into a bug note.
//
- // A home path at the very end of a JSON string value is left alone, having no
- // trailing slash inside its own value to match: reaching it would mean running
- // through the closing quote, which is what deleted the following field.
- { name: 'macos-home-path', regex: /\/Users\/[^/"]+\//g, replacement: '~/' },
- { name: 'linux-home-path', regex: /\/home\/[^/"]+\//g, replacement: '~/' },
+ // Consuming a terminator is what makes this family dangerous, which is why
+ // none of them do it. A rule that ate its separator also ate the `\` of a `\"`
+ // escape, promoting a content quote into a structural one and leaving the line
+ // unparseable, and it ate the leading `/` of a second home path on the same
+ // line, so that second account name shipped. `renderer-log.ts` states the
+ // first of those as a hard precondition on this file.
+ //
+ // The carriage return still has to be excluded from the run. `redactSecrets`
+ // splits on `\n` alone, so a CRLF line reaches these rules still holding its
+ // `\r`, and a run allowed to cross it would mask well past the account name.
+ //
+ // Past the quote and that carriage return, the bodies exclude only each rule's
+ // own separator. A space is a legal part of an account name, and
+ // `/Users/Jane Doe/` is the macOS shape this repo's own fixtures use, so
+ // excluding it silently stopped those from being masked at all, which on the
+ // file's only privacy patterns is the wrong direction to be wrong in.
+ //
+ // Admitting the space costs reach: on a line ending at the account name, the
+ // prose after it is redacted too, up to the next separator or the end of the
+ // line, which can re-root an unrelated absolute path at `~`. It errs toward
+ // redaction, which is the direction this list favours. Capping the run instead
+ // would trade that for a leak, since a profile component longer than the cap
+ // would stop matching at all.
+ //
+ // Each run stays linear. A body cannot cross a terminator, so there is one
+ // viable start position per root, and each give-back fails in O(1): the first
+ // against the terminator, the rest against a backslash the terminal class
+ // excludes even though the run admits it, one per trailing backslash.
+ //
+ // Greedy is load-bearing, unlike the shape this replaced. Nothing follows the
+ // quantifier to force a run out to a terminator, so a lazy one would stop one
+ // character past the root and ship the rest of the name while still reporting
+ // the pattern as fired, which is this list's worst outcome.
+ {
+ // Both POSIX rules are case-sensitive, unlike the Windows rule below, and
+ // deliberately so: `/users/` is an extremely common REST path segment, and
+ // matching it would re-root live API routes at `~`. The capital is the only
+ // thing separating the two, since neither has a drive letter in front of it.
+ //
+ // `/home/` gets no such separation and never has: a URL path under `/home/`
+ // is redacted by the rule below it, and admitting a terminal account name
+ // widens that from `/home/x/y` to a bare `/home/x` as well. Same trade as
+ // everywhere else in this list, and in the same direction.
+ //
+ // The body admits a backslash but may not end on one, which is what the
+ // `[^…]*[^…\\]` shape buys. A backslash is legal in a POSIX account name, so
+ // excluding it outright would mask `/Users/al\ice` only as far as `al`,
+ // while letting a run stop on one is what ate the escape of a `\"`.
+ // Requiring one more non-backslash avoids both, at one give-back per
+ // trailing backslash on top of the terminator give-back every run pays.
+ name: 'macos-home-path',
+ regex: /\/Users\/[^/"\r]*[^/"\r\\]/g,
+ replacement: '~',
+ },
+ { name: 'linux-home-path', regex: /\/home\/[^/"\r]*[^/"\r\\]/g, replacement: '~' },
+ {
+ // `\\{1,2}` because the biggest consumer is NDJSON: the desktop and server
+ // log sinks write through `JSON.stringify`, which doubles every separator,
+ // so a rule written against single backslashes silently matches nothing on
+ // the files that carry the most of these. The two rules above need no
+ // equivalent, since forward slashes survive that encoding unchanged. A
+ // separator doubled twice by a second round of stringification is out of
+ // scope, as is a UNC or redirected root (`\\\\server\\share\\Users\\...`), since
+ // the drive letter is unanchored but still required.
+ //
+ // No trailing-backslash guard here, unlike the two above, because a
+ // backslash cannot occur in a Windows account name at all: the body excludes
+ // it outright and a run can never end on one.
+ //
+ // The lookahead stops the run before a second drive-rooted profile path
+ // rather than eating it. Both separators here are backslashes, so nothing
+ // else would end the first run before the `C:` of the next path, and that
+ // second account name would ship. The two rules above get this for free,
+ // their separator being the same `/` the next path opens with.
+ //
+ // Matched case-insensitively, which the two rules above cannot afford. The
+ // required drive-letter prefix means `c:\users\` cannot collide with a URL
+ // path, so the redaction-favouring reading is free here.
+ name: 'windows-home-path',
+ regex: /[A-Za-z]:\\{1,2}Users\\{1,2}(?:(?![A-Za-z]:\\)[^\\"\r])+/gi,
+ replacement: '~',
+ },
];
/** Names of the redaction patterns, for a bundle's privacy summary. */
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index 83d47404a..a363dfd54 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,3 +1,4 @@
+
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/code-fence.ts b/packages/core/src/markdown/code-fence.ts
index 9807a7e82..4499dbc92 100644
--- a/packages/core/src/markdown/code-fence.ts
+++ b/packages/core/src/markdown/code-fence.ts
@@ -1,3 +1,4 @@
+
export function selectFenceChar(info: string): '`' | '~' {
return info.includes('`') ? '~' : '`';
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index e3a4af858..6e3c6d088 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index ece5c02a1..b6299a948 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,3 +1,4 @@
+
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index 54774764a..acd398aa6 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.ts
index 43ecdc709..ba9b56384 100644
--- a/packages/core/src/markdown/div-align-promoter.ts
+++ b/packages/core/src/markdown/div-align-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index 6d3f3643e..4513da9bb 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,3 +1,4 @@
+
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 00f5771ee..6931623c7 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -8,6 +9,7 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
+
interface GfmExample {
section: string;
markdown: string;
@@ -17,6 +19,7 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
+
interface MdxCrashEntry {
id: string;
input: string;
@@ -68,6 +71,7 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
+
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -76,6 +80,7 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
+
export interface NgPinnedCase {
id: string;
name: string;
@@ -92,6 +97,7 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
+
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index 8b1eb8519..daa3ef82b 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -10,6 +11,7 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
+
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -36,6 +38,7 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
+
const WORDS = [
'lorem',
'ipsum',
@@ -153,6 +156,7 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
+
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -191,6 +195,7 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
+
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 420dc0fe5..32c055c5b 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,6 +7,7 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
+
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 2653473da..283913255 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,3 +1,4 @@
+
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index ee6d25fda..e56707b48 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 787315157..9681c0056 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,3 +1,4 @@
+
import type { Element as HastElement, Root as HastRoot } from 'hast';
import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -128,7 +129,8 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified().use(rehypeParse, { fragment: true });
+ const processor = unified()
+ .use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 706fa9afb..994eb6917 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index 779e27500..ec1ac1b7e 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -206,6 +207,7 @@ export class MarkdownManager {
}
}
+
const registry = createRegistry();
function destructureAttrs(
@@ -254,6 +256,7 @@ function destructureAttrs(
return result;
}
+
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -276,6 +279,7 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
+
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -344,6 +348,7 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
+
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -596,6 +601,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -676,6 +682,7 @@ function buildMdastToPmHandlers(
}));
}
+
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -973,6 +980,7 @@ function buildMdastToPmHandlers(
};
}
+
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1098,6 +1106,7 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
+
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.ts
index fa0be9e86..b79e9aef7 100644
--- a/packages/core/src/markdown/lint/applies-to.ts
+++ b/packages/core/src/markdown/lint/applies-to.ts
@@ -1,3 +1,4 @@
+
import picomatch from 'picomatch';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.ts
index 312c9c74b..94b34dee1 100644
--- a/packages/core/src/markdown/lint/config-files.ts
+++ b/packages/core/src/markdown/lint/config-files.ts
@@ -1,3 +1,4 @@
+
const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([
'.markdownlint.json',
'.markdownlint.jsonc',
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index cc667b93e..7c54c0a73 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -52,6 +52,7 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
+
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index d48eea5e4..a51f2ffb0 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,6 +6,7 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
+
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
index ef478e268..9c9542661 100644
--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
@@ -1,3 +1,4 @@
+
import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';
export interface FrontmatterFieldConstraint {
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index 1943ac84f..a19b298ce 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -1,3 +1,4 @@
+
import Ajv, { type ValidateFunction } from 'ajv';
import Ajv2019 from 'ajv/dist/2019.js';
import Ajv2020 from 'ajv/dist/2020.js';
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index 781226a5d..26fbc2b22 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,3 +1,4 @@
+
import type { LintPluginFailureReporter } from './plugin-failure.ts';
import { isLintPluginSelected, LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
@@ -79,7 +80,8 @@ function renderErrorMessage(error: unknown, depth = 0): string {
try {
const json = JSON.stringify(error);
if (json !== undefined) return json;
- } catch {}
+ } catch {
+ }
}
return String(error);
}
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
index 7a5af097e..f438f1b16 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
@@ -1,3 +1,4 @@
+
import type { OkfRuleId } from '../okf-rule-meta.ts';
import { fileNameFor, OKF_SCHEMA_DIR, okfSchemaPathFor } from './paths.ts';
import { OKF_FRONTMATTER_REGISTRY } from './registry.ts';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
index 1ee913527..c290b6878 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
@@ -1,3 +1,4 @@
+
import type { OkfRuleId } from '../okf-rule-meta.ts';
export const OKF_SCHEMA_DIR = '.ok/okf';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
index f325fbbb4..53ecb619d 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
@@ -1,3 +1,4 @@
+
import { compileAppliesTo } from '../applies-to.ts';
import { validateFrontmatterSource } from '../frontmatter-validate.ts';
import {
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
index ed9e2efcf..f700795d2 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
@@ -1,3 +1,4 @@
+
// file-level form is deliberate: the sibling `biome-ignore` must sit on the line
// oxlint-disable unicorn/no-thenable
diff --git a/packages/core/src/markdown/lint/okf-project/rules.ts b/packages/core/src/markdown/lint/okf-project/rules.ts
index 6d691ae2b..8b476332e 100644
--- a/packages/core/src/markdown/lint/okf-project/rules.ts
+++ b/packages/core/src/markdown/lint/okf-project/rules.ts
@@ -1,3 +1,4 @@
+
import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';
import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from '../okf-rule-meta.ts';
diff --git a/packages/core/src/markdown/lint/okf-rule-meta.ts b/packages/core/src/markdown/lint/okf-rule-meta.ts
index 4de50d79f..44913a9dc 100644
--- a/packages/core/src/markdown/lint/okf-rule-meta.ts
+++ b/packages/core/src/markdown/lint/okf-rule-meta.ts
@@ -1,3 +1,4 @@
+
export const OKF_RULE_IDS = [
'no-wiki-links',
'log-shape',
diff --git a/packages/core/src/markdown/lint/okf-rules.ts b/packages/core/src/markdown/lint/okf-rules.ts
index 1d5538421..d0999b62e 100644
--- a/packages/core/src/markdown/lint/okf-rules.ts
+++ b/packages/core/src/markdown/lint/okf-rules.ts
@@ -1,3 +1,4 @@
+
import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from './okf-rule-meta.ts';
import type { OkfRule } from './okf-runner.ts';
import { indexShape } from './rules/index-shape.ts';
diff --git a/packages/core/src/markdown/lint/okf-runner.ts b/packages/core/src/markdown/lint/okf-runner.ts
index de130e3f4..fabb08d6e 100644
--- a/packages/core/src/markdown/lint/okf-runner.ts
+++ b/packages/core/src/markdown/lint/okf-runner.ts
@@ -1,3 +1,4 @@
+
import type { Root } from 'mdast';
import remarkFrontmatter from 'remark-frontmatter';
import remarkGfm from 'remark-gfm';
diff --git a/packages/core/src/markdown/lint/plugin-failure.ts b/packages/core/src/markdown/lint/plugin-failure.ts
index e7d694890..1cd0d2543 100644
--- a/packages/core/src/markdown/lint/plugin-failure.ts
+++ b/packages/core/src/markdown/lint/plugin-failure.ts
@@ -1,3 +1,4 @@
+
import type { LintPluginId } from './types.ts';
export interface LintPluginFailure {
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index e7455ccf7..1dae8316d 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,3 +1,4 @@
+
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import {
@@ -23,6 +24,7 @@ import {
type OkfSlice,
} from './types.ts';
+
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/rules/index-shape.ts b/packages/core/src/markdown/lint/rules/index-shape.ts
index 59fe9b87d..fcbb1b56c 100644
--- a/packages/core/src/markdown/lint/rules/index-shape.ts
+++ b/packages/core/src/markdown/lint/rules/index-shape.ts
@@ -1,3 +1,4 @@
+
import type { List, ListItem } from 'mdast';
import { EXIT, visit } from 'unist-util-visit';
import { defineScopedOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/rules/log-shape.ts b/packages/core/src/markdown/lint/rules/log-shape.ts
index e0159519f..431e4e9c8 100644
--- a/packages/core/src/markdown/lint/rules/log-shape.ts
+++ b/packages/core/src/markdown/lint/rules/log-shape.ts
@@ -1,3 +1,4 @@
+
import type { Heading } from 'mdast';
import { toString as headingText } from 'mdast-util-to-string';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/lint/rules/no-wiki-links.ts b/packages/core/src/markdown/lint/rules/no-wiki-links.ts
index 2123e977f..f75a04d15 100644
--- a/packages/core/src/markdown/lint/rules/no-wiki-links.ts
+++ b/packages/core/src/markdown/lint/rules/no-wiki-links.ts
@@ -1,3 +1,4 @@
+
import type { Point } from 'unist';
import { visit } from 'unist-util-visit';
import { defineOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/rules/reserved-casing.ts b/packages/core/src/markdown/lint/rules/reserved-casing.ts
index 89ef3e4a9..c8b4d8f28 100644
--- a/packages/core/src/markdown/lint/rules/reserved-casing.ts
+++ b/packages/core/src/markdown/lint/rules/reserved-casing.ts
@@ -1,3 +1,4 @@
+
import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';
import { defineOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 2cffecae6..594830b88 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,3 +1,4 @@
+
import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';
import type { OkfRuleId } from './okf-rule-meta.ts';
@@ -112,6 +113,7 @@ export interface OkfSlice {
generate?: { index?: boolean };
}
+
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.ts
index 98238656e..437cc539a 100644
--- a/packages/core/src/markdown/lint/validation-counts.ts
+++ b/packages/core/src/markdown/lint/validation-counts.ts
@@ -1,3 +1,4 @@
+
export interface ValidationSourceCounts {
errorCount: number;
warningCount: number;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index a5b511f25..bd79424c7 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index ed89371d0..00fbc0035 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index 8ce2b2492..df788a80d 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 1a897fca8..17ed2b829 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index d988f4b8b..4aa0490c4 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,6 +168,7 @@ export function parseRecursive(
}
}
+
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -186,6 +187,7 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
+
interface Region {
start: number;
end: number;
@@ -209,6 +211,7 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
+
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -355,6 +358,7 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
+
interface SourceBlock {
src: string;
start: number;
@@ -452,6 +456,7 @@ function tryPerBlockFallback(
};
}
+
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index e6ab4fd57..43d420187 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,3 +1,4 @@
+
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index 0e3224206..55736041c 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,3 +1,4 @@
+
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index 91cdf658f..ccf06e94d 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,3 +1,4 @@
+
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
import { isBlankLineParagraph } from './zero-emission-blocks.ts';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index 0f399d34c..e5b4c9eba 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -476,7 +477,8 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- } else if (first === '[') {
+ }
+ else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index db10fa54b..ca225ce9b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 34068d103..3a2524a9a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 93151d43b..2279a0189 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index 188f02d83..a0f467c42 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4ba2c3418..4e8542a21 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index 1a74b1272..a3c96b24a 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index de35e7b79..e95cf43d6 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,3 +1,4 @@
+
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index b4be1b2ea..ffdb4d5b5 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,3 +1,4 @@
+
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index 3c8d88b7c..e2a96d1a7 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,3 +1,4 @@
+
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index cf2c9da8e..0389575ac 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,3 +1,4 @@
+
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 0dd54070e..96304e7a5 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,3 +1,4 @@
+
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { expect } from 'vitest';
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 7cac5b042..93798cf83 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,3 +1,4 @@
+
import type { Node as PmNode } from '@tiptap/pm/model';
import type {
MdxJsxAttribute,
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index b012a5aff..8c08b7a04 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,3 +1,4 @@
+
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index b50bea5ec..83d4af672 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.ts
index 0f1b0f27d..6e6d73400 100644
--- a/packages/core/src/markdown/underline-promoter.ts
+++ b/packages/core/src/markdown/underline-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index 1a082bda7..932d7d2a8 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,3 +1,4 @@
+
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index d578476a7..ac9f5239b 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,3 +1,4 @@
+
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index 6dad26200..afd9936fe 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,6 +17,7 @@ declare module 'micromark-util-types' {
}
}
+
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -260,6 +261,7 @@ export function wikiLinkSyntax(): Extension {
};
}
+
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -385,6 +387,7 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
+
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {
diff --git a/packages/desktop/src/main/auto-updater.ts b/packages/desktop/src/main/auto-updater.ts
index d8cde42c8..23aa74c05 100644
--- a/packages/desktop/src/main/auto-updater.ts
+++ b/packages/desktop/src/main/auto-updater.ts
@@ -525,12 +525,20 @@ export const INSTALL_FAILURE_MAX_SURFACES = 3;
* evidence needed to move it.
*
* The window is measured from the handoff both install paths record — the
- * "Relaunch now" click, or the quit install-on-quit commits on. The boot
- * reconciliation reaches this window only with a stamp on record: an attempt
- * with none never began, so it is re-offered rather than timed. The staging
- * fallback in `installMayStillBeRunning` therefore matters only to that
- * function's other caller, crash detection, which asks before the
- * reconciliation has run.
+ * "Relaunch now" click, or the quit install-on-quit commits on. Neither caller
+ * requires that stamp to reach the window. The boot reconciliation asks the
+ * in-flight question ahead of its own never-committed check, so a stampless
+ * attempt whose artifact was staged recently defers here on the staging
+ * fallback rather than being re-offered, and `installWasInFlightDuring` reaches
+ * the window the same way on crash detection's behalf. Removing or gating that
+ * fallback would therefore move the failed-install notice too, not just the
+ * crash prompt.
+ *
+ * This is the bound both questions apply at every handoff, stamped or not.
+ * Widening or narrowing it moves the reconciliation's verdict every time, and
+ * moves crash detection's for a handoff that predates the previous session's
+ * death. What bounds a handoff sitting inside that span is set out in
+ * `installWasInFlightDuring`, which is where that frame is reasoned about.
*/
const INSTALL_IN_FLIGHT_GRACE_MS = 30 * 60 * 1000;
@@ -549,6 +557,26 @@ const INSTALL_IN_FLIGHT_GRACE_MS = 30 * 60 * 1000;
* the tolerance, and the notice would never arrive. The count is the part of the
* hold that survives that re-arm, which is what makes it the termination
* guarantee; three mirrors the surfacing budget's shape.
+ *
+ * Crash detection is the second consumer, and only where the span it asks over
+ * collapsed onto the detecting instant, which is the frame this count was
+ * calibrated in. There the number decides how many boots may go on suppressing
+ * the prompt for a death nothing can date, before that death reads as a crash
+ * and the user is invited to report it. Raising it delays the failed-install
+ * notice by a boot and widens that suppression by one, and lowering it does the
+ * reverse.
+ *
+ * What that gates is a residual, not the ordinary install kill. The ordinary
+ * one is stamped, since install-on-quit is armed everywhere except Linux and
+ * `before-quit` runs the stamp, and its sentinel seeds a last-alive moment at
+ * arm time rather than at its first heartbeat (the arm-time seed in
+ * `detectBootCrash` carries why), so its span widens rather than collapsing
+ * and this count never sees it. A retried failing install is that same shape
+ * and is likewise out of reach. What arrives here instead is a span the
+ * reduction collapsed onto this boot's own clock. `installWasInFlightDuring`
+ * enumerates the routes to one and is the authority on them, and
+ * `bundle-forensics.md` names the same population from the triage side. Do not
+ * calibrate this against the common case.
*/
const INSTALL_DEFER_MAX_BOOTS = 3;
@@ -814,11 +842,16 @@ export function installReached(running: string, attempted: string): boolean {
* record crosses a process quit, so an NTP correction or a VM resume can
* leave the recorded handoff in the future. Same coercion the write side
* makes on the staging age.
+ * - non-finite elapsed: an unusable moment has to read as "no claim" rather
+ * than slip past the staleness bound by failing every comparison against
+ * it. Rejected at this one point every verdict path funnels through, not at
+ * each caller. The state loader coerces these fields today, so it is the
+ * contract holding rather than a live path.
*/
function installHandoffAgeMs(handoffAt: number | null, nowMs: number): number | null {
if (handoffAt === null) return null;
const elapsed = nowMs - handoffAt;
- return elapsed < 0 ? null : elapsed;
+ return Number.isFinite(elapsed) && elapsed >= 0 ? elapsed : null;
}
/**
@@ -835,48 +868,55 @@ function resolveInstallHandoffMoment(state: AppState, stagedAt: number | null):
return state.attemptedInstallHandoffAt ?? stagedAt;
}
+/**
+ * What an in-flight verdict carries: which version an installer was launched
+ * for, the moment it was handed off, and whether that moment is a stamp a live
+ * process wrote or the staging fallback.
+ *
+ * Named rather than inferred from either function's body, because both return
+ * it and a field added to one literal would otherwise widen the other's
+ * declared type silently. Crash detection re-declares the same shape as its own
+ * dep contract instead of importing this one: that module is deliberately
+ * updater-agnostic, and the structural match at the injection seam is what
+ * keeps it so.
+ */
+interface InstallInFlightVerdict {
+ attemptedVersion: string;
+ handoffAt: number;
+ recordedHandoff: boolean;
+}
+
+/**
+ * Whether a live process stamped the handoff, as opposed to the moment being
+ * the staging fallback.
+ */
+function hasRecordedHandoff(state: AppState): boolean {
+ return state.attemptedInstallHandoffAt !== null;
+}
+
/**
* Whether an install this app committed to may still have been running at
- * `nowMs` — and, when it may, which version and from what moment.
+ * `nowMs`.
*
- * Two callers ask the same question for different reasons, which is why it is
- * a function rather than an inline condition. The boot reconciliation below
- * asks it to decide whether to condemn an install as failed. Crash detection
- * asks it to decide whether a session that ended without a clean quit was
- * killed by the installer rather than by a fault — the installer terminates the
- * running process to replace its files, which bypasses the quit sequence and
- * leaves the dirty-shutdown sentinel behind. Both need the claim
- * bounded the same way; two copies of the bound would drift, and the pair that
+ * Two frames ask this, one present tense and one about a death already past,
+ * and they answer the boot-count question differently — which is why that gate
+ * is a parameter here rather than part of the arithmetic. What must not diverge
+ * is the grace window itself: two copies of it would drift, and the pair that
* drifted would tell the user an install failed while telling them nothing
* about the crash it caused, or the reverse.
*
- * The bound is the interesting part, and neither half of it is optional. The
- * grace window keeps a stale record from claiming an install is in flight
- * forever; the boot count is what survives electron-updater re-arming
- * `update-downloaded` from its on-disk cache and clearing the handoff stamp,
- * which would otherwise make an install that never lands look perpetually
- * fresh. See both constants' own docs for the calibration.
+ * `enforceDeferBudget` is what separates them. See `installMayStillBeRunning`
+ * and `installWasInFlightDuring` for each frame's reasoning about it.
*
* Returned as a value rather than a boolean so a caller can name the version in
* a log line without re-reading state that the next moment may have cleared.
- *
- * `stagedAt` is a required parameter rather than a read of
- * `state.versionPendingInstallStagedAt`, and the difference is load-bearing.
- * The boot reconciliation runs the stale-pending clear BEFORE it reaches this
- * question, and that clear nulls the staging stamp — so by the time the verdict
- * is due, the field on `state` no longer holds the moment the artifact was
- * actually staged. On the shape where nothing else recorded the commit (an
- * unobserved quit, so no `attemptedInstallHandoffAt`) that field is the only
- * lower bound left, and reading the cleared one silently condemns an install
- * that is still running. Passing it in forces each caller to say which snapshot
- * it means: the reconciliation passes the value it captured before its own
- * mutation, and a caller reading fresh from disk passes the field as-is.
*/
-export function installMayStillBeRunning(
+function installInFlightAt(
state: AppState,
nowMs: number,
stagedAt: number | null,
-): { attemptedVersion: string; handoffAt: number; recordedHandoff: boolean } | null {
+ enforceDeferBudget: boolean,
+): InstallInFlightVerdict | null {
const attempted = state.attemptedInstall;
// Nothing was committed to, so nothing can be in flight.
if (attempted === null) return null;
@@ -886,17 +926,166 @@ export function installMayStillBeRunning(
handoffAt === null ||
handoffAgeMs === null ||
handoffAgeMs > INSTALL_IN_FLIGHT_GRACE_MS ||
- state.attemptedInstallDeferredBoots >= INSTALL_DEFER_MAX_BOOTS
+ (enforceDeferBudget && state.attemptedInstallDeferredBoots >= INSTALL_DEFER_MAX_BOOTS)
) {
return null;
}
return {
attemptedVersion: attempted,
handoffAt,
- recordedHandoff: state.attemptedInstallHandoffAt !== null,
+ recordedHandoff: hasRecordedHandoff(state),
};
}
+/**
+ * Whether an install this app committed to may still be running right now — and,
+ * when it may, which version and from what moment.
+ *
+ * The boot reconciliation's question, asked at `now()` to decide whether to
+ * condemn an install as failed. Both halves of its bound are load-bearing, and
+ * neither is derivable from the other: the grace window keeps a stale record
+ * from claiming an install is in flight forever, and the boot count is what
+ * survives a re-arm refreshing the moment the grace measures from. Both
+ * constants' own docs carry the calibration and the re-arm derivation.
+ *
+ * `stagedAt` is a required parameter rather than a read of
+ * `state.versionPendingInstallStagedAt`, and the difference is load-bearing.
+ * The boot reconciliation runs the stale-pending clear BEFORE it reaches this
+ * question, and that clear nulls the staging stamp — so by the time the verdict
+ * is due, the field on `state` no longer holds the moment the artifact was
+ * actually staged. On the shape where nothing else recorded the commit (an
+ * unobserved quit, so no `attemptedInstallHandoffAt`) that field is the only
+ * lower bound left, and reading the cleared one silently condemns an install
+ * that is still running. Passing it in forces each caller to say which snapshot
+ * it means: the reconciliation passes the value it captured before its own
+ * mutation, and a caller reading fresh from disk passes the field as-is.
+ */
+export function installMayStillBeRunning(
+ state: AppState,
+ nowMs: number,
+ stagedAt: number | null,
+): InstallInFlightVerdict | null {
+ return installInFlightAt(state, nowMs, stagedAt, true);
+}
+
+/**
+ * Whether an install this app committed to may still have been running at any
+ * point during a span of time, rather than at one instant.
+ *
+ * Crash detection knows when the previous session was last alive and when this
+ * boot noticed it was gone, and the truth it needs is whether the install
+ * window overlaps that span at all. Asking the instant-shaped predicate at the
+ * ends of the span answers a different and weaker question: the window is
+ * bounded by the grace, the span is not, so a window that opens after the last
+ * heartbeat and closes before the reopen sits strictly inside the span and
+ * touches neither end.
+ *
+ * Only a handoff a live process stamped reaches that geometry. It lands just
+ * after the dying session's final heartbeat, which is the ordinary
+ * quit-then-install path, and it is a record that some process committed to
+ * running an installer. The staging fallback records something weaker: a
+ * download finished. Widening the span for it would date the window to a
+ * moment no installer is known to have run from, so an ordinary crash within
+ * the grace of a completed download would be read as an install killing the
+ * session, whatever the user did next. The span therefore collapses to its
+ * later end when nothing was stamped.
+ *
+ * Reduced to one instant rather than reimplemented, so the grace window and the
+ * handoff resolution stay single-sourced. Clamping the handoff into the span
+ * lands inside the window if and only if the two overlap. Below the span the
+ * clamp yields its start, so the grace still bounds a handoff that predates the
+ * span. Inside it yields the handoff itself, so the measured age is zero and
+ * the grace can never bite, an install having been in flight at that instant by
+ * definition. Above it yields the span's end, which the predicate's own
+ * negative-elapsed guard then rejects.
+ *
+ * The deferred-boot cap is what `enforceDeferBudget` exists to express, and
+ * what it turns on is whether the span widened, not whether a stamp exists. The
+ * count measures how many boots the reconciliation has held its own notice
+ * back, which is a fact about a notice this app has not yet shown, not about
+ * whether an installer was running while the previous session died. Applying it
+ * to a verdict anchored in the past makes that death's classification depend on
+ * how many times the app has been opened since, and it bites on shapes that
+ * have nothing to do with a late reopen: an install that keeps failing reaches
+ * the cap after three boots, and the next "Retry" click re-stamps a fresh
+ * handoff without clearing the count on Windows or macOS, so the very next kill
+ * would be read as a crash.
+ *
+ * Where the span collapses the anchor is this boot's own clock, which is the
+ * frame the count was calibrated in, so it applies again. It has to: the grace
+ * alone cannot terminate a hold there, for the re-arm reason set out at
+ * `INSTALL_DEFER_MAX_BOOTS`. Every route to a collapsed span reaches that frame
+ * and so every one of them gets the bound: nothing stamped, a floor that is not
+ * a number, and a floor at or after the span's end. The last is the one the
+ * caller emits whenever the sentinel carried no usable heartbeat, and it is why
+ * the gate is read off the resolved bound rather than off the stamp.
+ *
+ * The Retry failure named above returns on those collapsed shapes, which is the
+ * price of putting the bound back. A spent count with a fresh stamp is reachable
+ * off Linux, and either collapse route can then meet it. It is corroborated from
+ * the preceding boots' suppression lines rather than the prompting one, which
+ * carries no span fields at all. The bug-triage bundle-forensics reference has
+ * that read, and owns the log-shape rules for this class.
+ *
+ * Dropping the cap where the span widened widens what gets suppressed, and the
+ * widening is worth naming rather than leaving to be discovered. A handoff
+ * stamped by an earlier boot, never retired, sitting within the grace of the
+ * span, suppresses the prompt for a death in that span even if the install it
+ * recorded finished long before. That is the same evidence the instant caller
+ * acts on, read in the frame the death actually happened in, and the grace
+ * keeps it to half an hour either way. The alternative trades it for the
+ * failure above, which arms a prompt for a death an installer demonstrably
+ * caused.
+ *
+ * How tightly the span brackets the death is the caller's problem, and it is
+ * what keeps that half hour from being a half hour of anything. Today's only
+ * caller bounds the span below by the previous session's last heartbeat, and
+ * where it has none it collapses onto its own clock, which is the residual
+ * limit of this whole reduction rather than a corner of it. The floor dates the
+ * death to a heartbeat interval only while the heartbeat was landing: what it
+ * records is the last SUCCESSFUL sentinel write, so an unwritable userData path
+ * or a synchronously blocked main thread freezes it early while the session
+ * runs on, and early is the direction that widens the span and suppresses. A
+ * hang during update teardown is where that bites, the hang being what stops
+ * the heartbeat. What the grace bounds there is the handoff-to-floor gap and
+ * not the distance from that floor to the real death, so a floor frozen inside
+ * the grace of the handoff suppresses however long the session went on running
+ * afterwards. The one-directional cost of a loose floor is set out on the dep
+ * contract crash detection declares, where a caller reads it.
+ *
+ * `deathToMs` is the later end by construction at every caller. A `deathFromMs`
+ * that arrives later anyway, which a clock correction across a process quit can
+ * produce, collapses the span to its end rather than inverting it. A bound that
+ * is not a number at all collapses the same way, or takes the whole question out
+ * of play when it is `deathToMs` that is unusable. Both are finite at today's
+ * only caller, which parses its sentinel dates through a guarded helper, so the
+ * guard here is against a failure that is one-directional at an exported seam:
+ * every comparison against `NaN` is false, so an unguarded bound would pass the
+ * staleness bound by failing it and suppress unconditionally.
+ */
+export function installWasInFlightDuring(
+ state: AppState,
+ span: { deathFromMs: number; deathToMs: number },
+ stagedAt: number | null,
+): InstallInFlightVerdict | null {
+ const { deathFromMs, deathToMs } = span;
+ if (!Number.isFinite(deathToMs)) return null;
+ const spanStartMs =
+ hasRecordedHandoff(state) && Number.isFinite(deathFromMs)
+ ? Math.min(deathFromMs, deathToMs)
+ : deathToMs;
+ // Whether the span reduced to the detecting instant, by any of the routes it
+ // can. The stamp is one of them and the caller's own floor is the others, so
+ // this is read off the resolved bound rather than off the stamp: gating on
+ // the stamp would drop the cap for a stamped handoff whose floor collapsed,
+ // which is the detecting instant asked without the bound that frame carries.
+ const spanCollapsed = spanStartMs === deathToMs;
+ const handoffAt = resolveInstallHandoffMoment(state, stagedAt);
+ const anchorMs =
+ handoffAt === null ? deathToMs : Math.min(Math.max(handoffAt, spanStartMs), deathToMs);
+ return installInFlightAt(state, anchorMs, stagedAt, spanCollapsed);
+}
+
// ————————————————————————————————————————————————————————
// Main entry
// ————————————————————————————————————————————————————————
@@ -2726,9 +2915,9 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
// an installer and the only open question is its age.
//
// The predicate itself lives in `installMayStillBeRunning` so crash
- // detection can ask the same question with the same bound; the locals
- // above stay for the log lines, which report the inputs the verdict was
- // reached from rather than the verdict alone.
+ // detection can ask its own span-shaped question against the same
+ // bound. The locals above stay for the log lines, which report the
+ // inputs the verdict was reached from rather than the verdict alone.
} else if (state.attemptedInstallSurfacedCount >= INSTALL_FAILURE_MAX_SURFACES) {
// Budget spent — drop `attemptedInstall` so a persistently-failing
// ShipIt or an unreachable attempted version (a yanked release, a
diff --git a/packages/desktop/src/main/crash-detection.test.ts b/packages/desktop/src/main/crash-detection.test.ts
index 6a747b712..3dd97033c 100644
--- a/packages/desktop/src/main/crash-detection.test.ts
+++ b/packages/desktop/src/main/crash-detection.test.ts
@@ -19,13 +19,16 @@ import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import type { OkBugReportCrashDetectedEvent } from '@inkeep/open-knowledge-core';
import { afterEach, describe, expect, test } from 'vitest';
+import { installWasInFlightDuring } from './auto-updater.ts';
import {
type CrashDetectionDeps,
createCrashDetection,
type InstallInFlight,
+ SENTINEL_HEARTBEAT_INTERVAL_MS,
startLocalCrashReporter,
} from './crash-detection.ts';
import { buildMinidump } from './minidump.test-helper.ts';
+import { type AppState, emptyState } from './state-store.ts';
const tmpDirs: string[] = [];
@@ -88,6 +91,13 @@ interface Rig {
tick(): Date;
/** Jump the fake clock forward, for windows measured in minutes. */
advance(ms: number): void;
+ /**
+ * Read the fake clock without moving it, to date a moment in the session
+ * under test before advancing past it. Reading it must not perturb the tick
+ * budget the surrounding assertions depend on, which is why this exists
+ * alongside `tick`.
+ */
+ nowMs(): number;
dir: string;
}
@@ -153,6 +163,9 @@ function makeRig(): Rig {
advance(ms: number) {
clockMs += ms;
},
+ nowMs() {
+ return clockMs;
+ },
deps: {
sentinelPath: join(dir, 'user-data', 'bug-report-dirty-shutdown.json'),
ackStorePath: join(dir, 'user-data', 'bug-report-crash-acks.json'),
@@ -1710,6 +1723,11 @@ describe('when a boot invitation says the dead session stopped', () => {
expect(breadcrumb?.lastAliveAt).toBe(lastAliveAt);
expect(breadcrumb?.suspendedAt).toBeNull();
expect(breadcrumb?.pendingOsShutdownAt).toBeNull();
+ // The fourth witness the suppression predicate is built from. Present as an
+ // explicit null on every dirty-shutdown prompt, which is what lets a reader
+ // tell this build from one predating the question entirely.
+ expect(breadcrumb).toHaveProperty('attemptedInstall');
+ expect(breadcrumb?.attemptedInstall).toBeNull();
});
test('a sentinel written before the liveness fields existed logs them as null', () => {
@@ -1972,6 +1990,12 @@ describe('auto-update install kill suppression', () => {
// indistinguishable in the logs from one where detection never ran.
expect(breadcrumb?.attemptedInstall).toBe('0.61.3');
expect(breadcrumb?.recordedHandoff).toBe(true);
+ // Every other moment on this line is an ISO string. A raw epoch here would
+ // read as a plausible number beside them and quietly cost the reader the
+ // comparison the field exists for. Named apart from the updater's own
+ // `handoffAt`, which stays epoch ms, so one key never carries two
+ // datatypes across the stream the two modules share.
+ expect(breadcrumb?.handoffAtIso).toBe('2026-08-23T23:10:28.727Z');
});
test('a fresh minidump still prompts through an install kill', () => {
@@ -2027,9 +2051,9 @@ describe('auto-update install kill suppression', () => {
const rig = makeRig();
createCrashDetection(rig.deps).detectBootCrash();
// No live process saw the commit (a force-quit, a power loss), so the
- // updater fell back to the staging moment. The macOS instances this ticket
- // was opened from take this path — a session killed mid-flight never
- // quits, so it never stamps a handoff of its own.
+ // updater fell back to the staging moment. A session that reached neither
+ // commit point, neither the "Relaunch now" click nor `before-quit`, takes
+ // this path. `crash-detection.ts` keeps the platform account.
rig.setInstallInFlight({ ...IN_FLIGHT, recordedHandoff: false });
expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
@@ -2046,3 +2070,581 @@ describe('auto-update install kill suppression', () => {
expect(armed?.kind).toBe('boot');
});
});
+
+/**
+ * The join between crash detection and the updater's verdict, exercised with
+ * the real predicate rather than a canned answer.
+ *
+ * Every test in the block above hands detection a fixed `InstallInFlight` and
+ * so can only observe what detection does with a verdict, never how the
+ * verdict was reached. The bound that decides the verdict is a window measured
+ * from the install handoff, which means the instant the question is asked in
+ * changes the answer. These tests therefore wire the real updater predicate and
+ * model the one variable no test at either rung models: how long the app stayed
+ * closed between the session the installer killed and the boot that detects it.
+ *
+ * The dep here answers about the span the previous session died in, which
+ * detection bounds below by the sentinel's own `lastAliveAt` and above by the
+ * moment this boot noticed the death. When the sentinel carries no usable one that
+ * lower bound collapses onto the detecting boot's own clock, the one frame in
+ * which the question decays with how long the app stayed closed, so a test
+ * that suppresses only once a usable lower bound arrives is pinning the frame
+ * rather than the plumbing.
+ */
+describe('the instant the install-kill question is asked in', () => {
+ const ATTEMPTED = '0.61.3';
+ const TWO_HOURS_MS = 2 * 60 * 60 * 1000;
+
+ /**
+ * What a boot reads after a quit committed to an install: an attempt with a
+ * handoff stamped at `handoffAt` and nothing yet observed to land. Callers
+ * place that moment before, during, or after the doomed session's life
+ * deliberately, since where it falls relative to the last heartbeat is what
+ * most of this block is about.
+ */
+ function committedInstall(handoffAt: number): AppState {
+ return {
+ ...emptyState(),
+ versionPendingInstall: ATTEMPTED,
+ attemptedInstall: ATTEMPTED,
+ attemptedInstallHandoffAt: handoffAt,
+ versionPendingInstallStagedAt: handoffAt - 60_000,
+ attemptedInstallDeferredBoots: 0,
+ };
+ }
+
+ /**
+ * What a boot reads after a download finished and nothing quit afterwards:
+ * an attempt on record with no handoff stamped, so the only moment the
+ * updater can date the commit to is when the artifact was staged. A session
+ * that reached neither commit point arrives in exactly this shape, whatever
+ * ended it. `crash-detection.ts` keeps the platform account.
+ */
+ function stagedButNeverCommitted(stagedAt: number): AppState {
+ return {
+ ...emptyState(),
+ versionPendingInstall: ATTEMPTED,
+ attemptedInstall: ATTEMPTED,
+ attemptedInstallHandoffAt: null,
+ versionPendingInstallStagedAt: stagedAt,
+ attemptedInstallDeferredBoots: 0,
+ };
+ }
+
+ function wireRealUpdater(rig: Rig, state: AppState): void {
+ // The span forwarded whole, as the dep declares it. Substituting either end
+ // would substitute the detecting boot's own clock, which is the one frame
+ // this block exists to prove the verdict is not asked in.
+ rig.deps.installInFlight = (span) =>
+ installWasInFlightDuring(state, span, state.versionPendingInstallStagedAt);
+ }
+
+ test('an install in flight when the previous session died stays suppressed however late the reopen', () => {
+ const rig = makeRig();
+ wireRealUpdater(rig, committedInstall(rig.nowMs()));
+ // The doomed session boots on the outgoing binary and is killed mid-swap,
+ // so no quit sequence runs and its sentinel survives dirty, dated by the
+ // heartbeat it wrote while alive.
+ createCrashDetection(rig.deps).detectBootCrash();
+
+ // The user does not come back until the evening. Whether an install was
+ // running when that session died is settled history by then, and no amount
+ // of the app sitting closed can unsettle it.
+ rig.advance(TWO_HOURS_MS);
+
+ const sessionB = createCrashDetection(rig.deps);
+ expect(sessionB.detectBootCrash()).toBeNull();
+ sessionB.notifyRendererReady();
+ expect(rig.emitted).toHaveLength(0);
+ });
+
+ test('the same install kill is still suppressed when the user reopens promptly', () => {
+ const rig = makeRig();
+ wireRealUpdater(rig, committedInstall(rig.nowMs()));
+ createCrashDetection(rig.deps).detectBootCrash();
+
+ // The negative control for the test above. Anchoring the question to the
+ // death must not cost the suppression that already works on a fast reopen,
+ // which is what a fix that merely widened or moved the window would do.
+ rig.advance(5 * 60_000);
+
+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
+ });
+
+ test('a dirty shutdown with nothing committed still prompts however late the reopen', () => {
+ const rig = makeRig();
+ // Nothing was ever handed off, so there is no install to attribute the
+ // death to and the prompt is the whole point. This is the guard against
+ // answering the frame question by suppressing everything.
+ wireRealUpdater(rig, emptyState());
+ createCrashDetection(rig.deps).detectBootCrash();
+
+ rig.advance(TWO_HOURS_MS);
+
+ const armed = createCrashDetection(rig.deps).detectBootCrash();
+ expect(bootInvite(armed).context.dirtyShutdown).toBe(true);
+ });
+
+ test('a clean quit inside an install window arms nothing, with no death to date', () => {
+ const rig = makeRig();
+ wireRealUpdater(rig, committedInstall(rig.nowMs()));
+ const sessionA = createCrashDetection(rig.deps);
+ sessionA.detectBootCrash();
+ sessionA.markCleanQuit();
+
+ rig.advance(TWO_HOURS_MS);
+
+ // No sentinel means no previous session to anchor to. Reaching for an
+ // anchor that is not there must stay a no-op rather than throwing or
+ // arming on a session that quit properly.
+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
+ expect(rig.emitted).toHaveLength(0);
+ });
+
+ test('a torn sentinel carries no death to anchor to, so a late reopen still prompts', () => {
+ const rig = makeRig();
+ wireRealUpdater(rig, committedInstall(rig.nowMs()));
+ mkdirSync(dirname(rig.deps.sentinelPath), { recursive: true });
+ writeFileSync(rig.deps.sentinelPath, 'torn-write-not-json');
+
+ rig.advance(TWO_HOURS_MS);
+
+ // Nothing in the file survived, so there is no lower bound on the death
+ // and the detecting clock is the only instant there is. Falling back to it
+ // is the fail-open-toward-prompting posture this module takes for any
+ // probe it cannot reason from, rather than inventing an anchor.
+ const armed = createCrashDetection(rig.deps).detectBootCrash();
+ expect(bootInvite(armed).context.dirtyShutdown).toBe(true);
+ });
+
+ test('a torn sentinel on a prompt reopen keeps the suppression it has today', () => {
+ const rig = makeRig();
+ wireRealUpdater(rig, committedInstall(rig.nowMs()));
+ mkdirSync(dirname(rig.deps.sentinelPath), { recursive: true });
+ writeFileSync(rig.deps.sentinelPath, 'torn-write-not-json');
+
+ rig.advance(5 * 60_000);
+
+ // The other half of the same fallback, and the half a fix that treated a
+ // missing anchor as "assume no install" would silently regress: the
+ // installer really did kill this session, and losing the sentinel to a
+ // torn write is not evidence that it did not.
+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
+ });
+
+ test('a sentinel written before the liveness fields existed still suppresses a prompt reopen', () => {
+ const rig = makeRig();
+ const prevBootedAt = rig.nowMs();
+ wireRealUpdater(rig, committedInstall(prevBootedAt));
+ mkdirSync(dirname(rig.deps.sentinelPath), { recursive: true });
+ // The shape an upgrade from a build predating the heartbeat field leaves
+ // behind: readable, dated only by the instant the session started, and
+ // carrying no version either, since that field is younger still. A reopen
+ // this fast is inside the window under any lower bound at or after that
+ // instant, so the suppression must not depend on `lastAliveAt` being
+ // present.
+ writeFileSync(
+ rig.deps.sentinelPath,
+ JSON.stringify({
+ bootId: String(prevBootedAt),
+ startedAt: new Date(prevBootedAt).toISOString(),
+ }),
+ );
+
+ rig.advance(5 * 60_000);
+
+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
+ });
+
+ test('a handoff stamped after the previous session stopped heartbeating still suppresses', () => {
+ const rig = makeRig();
+ // The doomed session starts with nothing committed, so its sentinel is
+ // dated by the heartbeat it last wrote rather than by any install record.
+ createCrashDetection(rig.deps).detectBootCrash();
+ const lastAliveMs = Date.parse(readSentinel(rig).lastAliveAt ?? '');
+
+ // Setup shared with the late-reopen sibling below, which differs only in
+ // how long the user stays away. This one reopens promptly, so it pins the
+ // half of the class that worked before the span reduction and must not
+ // regress.
+ rig.advance(SENTINEL_HEARTBEAT_INTERVAL_MS - 15_000);
+ const handoffAt = rig.nowMs();
+ wireRealUpdater(rig, committedInstall(handoffAt));
+ // Asserted rather than assumed: a rig whose two moments coincided would
+ // suppress under every anchoring scheme and would therefore pin nothing.
+ expect(handoffAt).toBeGreaterThan(lastAliveMs);
+
+ rig.advance(5 * 60_000);
+
+ // A question asked only at the last heartbeat reads this handoff as
+ // sitting in the future, which the updater declines to reason from and
+ // reports as no install at all. Anchoring there would arm a false prompt
+ // on a prompt reopen, which is the half of the class that has always
+ // worked. The death is an interval, and the install was in flight at its
+ // far end.
+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
+ });
+
+ test('a sentinel dated only by when its session started collapses onto this boot', () => {
+ const rig = makeRig();
+ const prevBootedAt = rig.nowMs();
+ // A commit made before the doomed session started, which is the shape an
+ // install that never lands leaves behind: the record outlives the
+ // relaunch, and the session that inherits it is the one the installer
+ // kills on the next attempt.
+ wireRealUpdater(rig, committedInstall(prevBootedAt - 5 * 60_000));
+ mkdirSync(dirname(rig.deps.sentinelPath), { recursive: true });
+ writeFileSync(
+ rig.deps.sentinelPath,
+ JSON.stringify({
+ bootId: String(prevBootedAt),
+ startedAt: new Date(prevBootedAt).toISOString(),
+ }),
+ );
+
+ rig.advance(TWO_HOURS_MS);
+
+ // A session cannot die before it started, so that stamp does bound the
+ // death from below, and it is deliberately not used anyway. It dates the
+ // boot, not the death, so a session the installer killed seconds in and
+ // one that ran for hours before genuinely crashing arrive here as the same
+ // input, and reading it would resolve that ambiguity toward silence for
+ // both. The span collapses onto this boot instead and the prompt is owed.
+ const armed = createCrashDetection(rig.deps).detectBootCrash();
+ expect(bootInvite(armed).context.dirtyShutdown).toBe(true);
+ });
+
+ test('an unreadable last-alive stamp reads as no heartbeat at all', () => {
+ const rig = makeRig();
+ const prevBootedAt = rig.nowMs();
+ wireRealUpdater(rig, committedInstall(prevBootedAt - 5 * 60_000));
+ mkdirSync(dirname(rig.deps.sentinelPath), { recursive: true });
+ // The sentinel reader admits any non-empty string, so a field mangled by a
+ // partial write, or written in some other build's format, arrives here as
+ // text no date parser will take.
+ writeFileSync(
+ rig.deps.sentinelPath,
+ JSON.stringify({
+ bootId: String(prevBootedAt),
+ startedAt: new Date(prevBootedAt).toISOString(),
+ lastAliveAt: 'not-a-date',
+ appVersion: CRASHED_VERSION,
+ }),
+ );
+
+ rig.advance(TWO_HOURS_MS);
+
+ // Present but unparseable has to land where absent lands, or the parse
+ // failure quietly buys a suppression the same sentinel would not get if
+ // the field had been left out entirely.
+ const armed = createCrashDetection(rig.deps).detectBootCrash();
+ expect(bootInvite(armed).context.dirtyShutdown).toBe(true);
+ });
+
+ test('an unreadable last-alive stamp still renders a suppression breadcrumb', () => {
+ const rig = makeRig();
+ const prevBootedAt = rig.nowMs();
+ // The two siblings above both park the handoff outside the grace, so the
+ // verdict is null and the breadcrumb is never built. Putting it inside is
+ // what carries an unparseable stamp all the way to the line that formats
+ // the span, which is the only place a raw NaN would throw rather than
+ // degrade. `detectBootCrash()` returning at all is half the assertion.
+ wireRealUpdater(rig, committedInstall(prevBootedAt));
+ mkdirSync(dirname(rig.deps.sentinelPath), { recursive: true });
+ writeFileSync(
+ rig.deps.sentinelPath,
+ JSON.stringify({
+ bootId: String(prevBootedAt),
+ startedAt: new Date(prevBootedAt).toISOString(),
+ lastAliveAt: 'not-a-date',
+ appVersion: CRASHED_VERSION,
+ }),
+ );
+
+ rig.advance(5 * 60_000);
+ const lines = captureInfo(rig);
+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
+
+ const breadcrumb = suppressionBreadcrumb(lines);
+ expect(breadcrumb.deathFromSource).toBe('detected-at');
+ expect(breadcrumb.deathFrom).toBe(new Date(rig.nowMs()).toISOString());
+ });
+
+ test('an unreadable last-alive stamp does not clear the staleness bound', () => {
+ const rig = makeRig();
+ const prevBootedAt = rig.nowMs();
+ // Handed off well outside the in-flight window before that session even
+ // booted, so the correct verdict is that nothing was still running and the
+ // prompt is owed.
+ wireRealUpdater(rig, committedInstall(prevBootedAt - 45 * 60_000));
+ mkdirSync(dirname(rig.deps.sentinelPath), { recursive: true });
+ writeFileSync(
+ rig.deps.sentinelPath,
+ JSON.stringify({
+ bootId: String(prevBootedAt),
+ startedAt: new Date(prevBootedAt).toISOString(),
+ lastAliveAt: 'not-a-date',
+ appVersion: CRASHED_VERSION,
+ }),
+ );
+
+ rig.advance(TWO_HOURS_MS);
+
+ // Every comparison against a non-number is false, so an anchor that
+ // reached the updater as one would pass the staleness bound by failing it
+ // and suppress prompts this class was never meant to touch. The stale
+ // handoff has to arrive at the window as a real number and lose.
+ const armed = createCrashDetection(rig.deps).detectBootCrash();
+ expect(bootInvite(armed).context.dirtyShutdown).toBe(true);
+ });
+
+ test('a handoff stamped after the last heartbeat still suppresses a late reopen', () => {
+ const rig = makeRig();
+ // Setup identical to the prompt-reopen sibling above, up to the reopen
+ // delay further down, which is the only thing that differs and is the whole
+ // reduction: the window lands strictly inside the span rather than touching
+ // either end.
+ createCrashDetection(rig.deps).detectBootCrash();
+ const lastAliveMs = Date.parse(readSentinel(rig).lastAliveAt ?? '');
+ rig.advance(SENTINEL_HEARTBEAT_INTERVAL_MS - 15_000);
+ const handoffAt = rig.nowMs();
+ wireRealUpdater(rig, committedInstall(handoffAt));
+ expect(handoffAt).toBeGreaterThan(lastAliveMs);
+
+ // And then the user does not come back until the evening. The install
+ // window opens after the last heartbeat and closes long before the reopen,
+ // so it lies strictly inside the span between them and touches neither
+ // end. Two questions asked at the ends of that span both come back empty
+ // and arm a prompt for a session the installer ended on purpose.
+ rig.advance(TWO_HOURS_MS);
+
+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
+ });
+
+ test('a commit no live process recorded still suppresses a prompt reopen', () => {
+ const rig = makeRig();
+ // The half of the stampless branch that must keep working. Nothing quit, so
+ // the staging moment is the only date the updater has, and the question
+ // falls back to the detecting instant. Inside the grace of that download the
+ // answer is still a suppression, exactly as it was before the span reduction
+ // existed. Without this the branch has no positive case anywhere, and a
+ // refactor that bailed out early on a null stamp would leave every other
+ // assertion in this file green.
+ wireRealUpdater(rig, stagedButNeverCommitted(rig.nowMs()));
+ createCrashDetection(rig.deps).detectBootCrash();
+
+ rig.advance(5 * 60_000);
+
+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
+ });
+
+ test('a commit no live process recorded does not widen the span', () => {
+ const rig = makeRig();
+ // Nothing ever quit, so no handoff was stamped and the staging moment is
+ // the only date the updater has. That moment records a download finishing,
+ // not a process committing to run an installer, so widening the span for
+ // it would read every dirty shutdown inside the grace of a completed
+ // download as an install kill. The span reasoning stops at the stamped
+ // shape and this path answers exactly as it did before.
+ wireRealUpdater(rig, stagedButNeverCommitted(rig.nowMs()));
+ createCrashDetection(rig.deps).detectBootCrash();
+
+ rig.advance(TWO_HOURS_MS);
+
+ const armed = createCrashDetection(rig.deps).detectBootCrash();
+ expect(bootInvite(armed).context.dirtyShutdown).toBe(true);
+ });
+
+ test('a staged install whose window closed before the death still prompts', () => {
+ const rig = makeRig();
+ // Same shape, staged well outside the window before the doomed session was
+ // last alive. The staging fallback is a loose lower bound on the commit,
+ // not a licence to suppress every death that follows a download.
+ wireRealUpdater(rig, stagedButNeverCommitted(rig.nowMs() - 45 * 60_000));
+ createCrashDetection(rig.deps).detectBootCrash();
+
+ rig.advance(TWO_HOURS_MS);
+
+ const armed = createCrashDetection(rig.deps).detectBootCrash();
+ expect(bootInvite(armed).context.dirtyShutdown).toBe(true);
+ });
+
+ /**
+ * Swap in a payload-capturing logger, as the breadcrumb test in the block
+ * above does. The tier label is a second expression of the same fallback
+ * ladder that produced the bound, so the two can disagree with every verdict
+ * still correct, and a responder who trusts a label naming the wrong tier
+ * chases a widened span that never happened.
+ */
+ function captureInfo(rig: Rig): Array<Record<string, unknown>> {
+ const lines: Array<Record<string, unknown>> = [];
+ rig.deps.logger = {
+ info: (payload: Record<string, unknown>) => {
+ lines.push(payload);
+ },
+ warn: (payload: Record<string, unknown>) => {
+ rig.warnings.push(payload);
+ },
+ };
+ return lines;
+ }
+
+ function suppressionBreadcrumb(lines: Array<Record<string, unknown>>) {
+ const line = lines.find((l) => l.event === 'crash-detection.machine-level-death');
+ expect(line).toBeDefined();
+ return line as Record<string, unknown>;
+ }
+
+ test('a suppression names the handoff it accepted and the tier that dated the span', () => {
+ const rig = makeRig();
+ const handoffAt = rig.nowMs();
+ wireRealUpdater(rig, committedInstall(handoffAt));
+ createCrashDetection(rig.deps).detectBootCrash();
+ const lastAliveMs = Date.parse(readSentinel(rig).lastAliveAt ?? '');
+
+ rig.advance(TWO_HOURS_MS);
+ const lines = captureInfo(rig);
+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
+
+ const breadcrumb = suppressionBreadcrumb(lines);
+ // ISO rather than epoch ms, so a responder can read it against deathFrom on
+ // the same line without converting one of the two by hand, and under its
+ // own key so the updater's epoch-ms `handoffAt` keeps one datatype.
+ expect(breadcrumb.handoffAtIso).toBe(new Date(handoffAt).toISOString());
+ expect(breadcrumb.deathFromSource).toBe('last-alive');
+ expect(breadcrumb.deathFrom).toBe(new Date(lastAliveMs).toISOString());
+ // The width the question was actually asked over. A non-zero value here is
+ // what marks a suppression whose span widened, which is the only shape the
+ // handoff-against-deathFrom read above is valid on.
+ expect(breadcrumb.deathSpanMs).toBe(rig.nowMs() - lastAliveMs);
+ });
+
+ test('a heartbeat postdating this boot collapses the span without inverting it', () => {
+ const rig = makeRig();
+ const handoffAt = rig.nowMs();
+ wireRealUpdater(rig, committedInstall(handoffAt));
+ mkdirSync(dirname(rig.deps.sentinelPath), { recursive: true });
+ // A clock correction across the quit leaves a heartbeat dated after the
+ // boot that reads it. The span has no width to report there, so zero is
+ // the true answer rather than a negative one, and a triage rule keyed on a
+ // non-zero width has to exclude this line rather than count it.
+ const impossibleLastAlive = rig.nowMs() + 3 * 60 * 60 * 1000;
+ writeFileSync(
+ rig.deps.sentinelPath,
+ JSON.stringify({
+ bootId: String(rig.nowMs()),
+ startedAt: new Date(rig.nowMs()).toISOString(),
+ lastAliveAt: new Date(impossibleLastAlive).toISOString(),
+ appVersion: CRASHED_VERSION,
+ }),
+ );
+
+ rig.advance(5 * 60_000);
+ const lines = captureInfo(rig);
+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
+
+ const breadcrumb = suppressionBreadcrumb(lines);
+ expect(breadcrumb.deathSpanMs).toBe(0);
+ // The inversion itself stays legible: both unclamped moments are on the
+ // line, so a reader can still see that the floor postdates the detection.
+ expect(breadcrumb.deathFrom).toBe(new Date(impossibleLastAlive).toISOString());
+ expect(Date.parse(breadcrumb.detectedAt as string)).toBeLessThan(impossibleLastAlive);
+ expect(breadcrumb.deathFromSource).toBe('last-alive');
+ });
+
+ test('a fresh dump inside an install window prompts and names the attempt', () => {
+ const rig = makeRig();
+ wireRealUpdater(rig, committedInstall(rig.nowMs()));
+ createCrashDetection(rig.deps).detectBootCrash();
+
+ rig.advance(5 * 60_000);
+ seedMinidump(rig, 'faulted.dmp', new Date(rig.nowMs()));
+ const lines = captureInfo(rig);
+
+ // The installer ended the session AND the app faulted on its own, so the
+ // dump decides: this prompts as the dump-driven variant rather than being
+ // suppressed. It is also the only route by which the boot line carries a
+ // non-null attempt, which is what makes the key readable as evidence there
+ // rather than only as an era marker.
+ const armed = createCrashDetection(rig.deps).detectBootCrash();
+ expect(bootInvite(armed).context.dirtyShutdown).toBe(false);
+ const boot = lines.find((l) => l.event === 'crash-detection.boot');
+ expect(boot?.attemptedInstall).toBe(ATTEMPTED);
+ });
+
+ test('a torn sentinel says the span collapsed onto this boot, and warns', () => {
+ const rig = makeRig();
+ wireRealUpdater(rig, committedInstall(rig.nowMs()));
+ mkdirSync(dirname(rig.deps.sentinelPath), { recursive: true });
+ writeFileSync(rig.deps.sentinelPath, 'torn-write-not-json');
+
+ rig.advance(5 * 60_000);
+ const lines = captureInfo(rig);
+ expect(createCrashDetection(rig.deps).detectBootCrash()).toBeNull();
+
+ // A file that parsed and carried no dates reaches the breadcrumb as the
+ // same nulls, so without the warn a degraded read is indistinguishable
+ // from a clean one that simply had nothing to say.
+ expect(suppressionBreadcrumb(lines).deathFromSource).toBe('detected-at');
+ expect(rig.warnings.map((w) => w.event)).toContain('crash-detection.sentinel-parse-failed');
+ });
+
+ test('a sentinel that exists but cannot be read warns rather than passing as absent', () => {
+ const rig = makeRig();
+ // A directory where the file should be stands in for the class the field
+ // actually produces: an antivirus or indexer lock, a permission the app
+ // lost. The read throws with something other than ENOENT, so the previous
+ // session still did not clean-quit, but every dated field is gone and the
+ // span collapses. That reaches the breadcrumb identically to a build from
+ // before those fields existed, and the two call for opposite responses,
+ // so the errno is the only thing that separates them.
+ mkdirSync(rig.deps.sentinelPath, { recursive: true });
+
+ const armed = createCrashDetection(rig.deps).detectBootCrash();
+
+ const warn = rig.warnings.find((w) => w.event === 'crash-detection.sentinel-read-failed');
+ expect(warn).toBeDefined();
+ // The errno is the whole point of the line, so assert it arrives rather
+ // than trusting the payload shape. Presence first: an optional chain into a
+ // negative matcher passes on `undefined`, which would let a payload that
+ // dropped `err` keep this green.
+ const errno = (warn?.err as NodeJS.ErrnoException | undefined)?.code;
+ expect(errno).toBeDefined();
+ // Asserted as "not the missing-file code" rather than as the exact one,
+ // because EISDIR is this rig's way of provoking the class and the field
+ // produces others.
+ expect(errno).not.toBe('ENOENT');
+ // The other half of the same catch: a file that exists but cannot be read
+ // is still a session that did not clean-quit, so the prompt is owed.
+ expect(bootInvite(armed).context.dirtyShutdown).toBe(true);
+ });
+
+ test('the heartbeat outranks the start of the session when the two straddle the grace', () => {
+ const rig = makeRig();
+ const prevBootedAt = rig.nowMs();
+ // Handed off a minute before the doomed session even started, so the
+ // window had closed many hours before that session actually died.
+ wireRealUpdater(rig, committedInstall(prevBootedAt - 60_000));
+ mkdirSync(dirname(rig.deps.sentinelPath), { recursive: true });
+ const diedAt = prevBootedAt + 8 * 60 * 60 * 1000;
+ writeFileSync(
+ rig.deps.sentinelPath,
+ JSON.stringify({
+ bootId: String(prevBootedAt),
+ startedAt: new Date(prevBootedAt).toISOString(),
+ lastAliveAt: new Date(diedAt).toISOString(),
+ appVersion: CRASHED_VERSION,
+ }),
+ );
+
+ rig.advance(9 * 60 * 60 * 1000);
+
+ // Both dates are sound lower bounds on the death and they disagree by a
+ // whole session, which is why the order they are tried in is a decision
+ // rather than a detail. Reaching past the heartbeat to the earlier one
+ // would carry this handoff back inside the window and silence a genuine
+ // crash eight hours into a session.
+ const armed = createCrashDetection(rig.deps).detectBootCrash();
+ expect(bootInvite(armed).context.dirtyShutdown).toBe(true);
+ });
+});
diff --git a/packages/desktop/src/main/crash-detection.ts b/packages/desktop/src/main/crash-detection.ts
index 8b0347c23..ea8b92aea 100644
--- a/packages/desktop/src/main/crash-detection.ts
+++ b/packages/desktop/src/main/crash-detection.ts
@@ -160,6 +160,7 @@ interface CrashAckStore {
*/
interface SentinelState {
bootId: string;
+ /** When this session booted. Recorded for readers of the file, not read back here. */
startedAt: string;
/** Refreshed by the heartbeat; how close to death the session was known alive. */
lastAliveAt: string;
@@ -236,19 +237,36 @@ export interface CrashDetectionDeps {
currentBootSessionUuid(): string | null;
/**
* The updater's verdict that an install it committed to may still have been
- * running when the previous session ended — the fourth thing that can end a
- * session without the app having crashed.
+ * running at some point during the previous session's death — the fourth
+ * thing that can end a session without the app having crashed.
*
- * Asked of the updater rather than decided here: the grace window and the
- * boot bound that make "may still be running" a bounded claim are the
- * updater's calibration, and a second copy of that judgment would drift from
- * the one that decides whether to tell the user an install failed.
+ * Asked of the updater rather than decided here: the bounds that make "may
+ * still be running" a bounded claim, and which of them applies to which span
+ * shape, are the updater's calibration. A second copy of that judgment would
+ * drift from the one that decides whether to tell the user an install failed.
+ * `installWasInFlightDuring` is where the pairing is set out.
*
- * Optional, and null when nothing is in flight. An absent reader skips the
- * classification entirely — fail-open toward prompting, the same posture
- * `currentBootSessionUuid` takes when the probe is unavailable.
+ * A span rather than an instant, and both ends are required parameters,
+ * because the only clock reachable from here is the detecting boot's and the
+ * question is about a moment that has already passed. `installWasInFlightDuring`
+ * holds the derivation of why an instant cannot answer it. Passing both ends
+ * forces each caller to say which span it means, the same reason `stagedAt`
+ * is a parameter of the predicate underneath rather than a field read.
+ *
+ * `deathFromMs` is a lower bound on the death, and the error in it is
+ * one-directional. Below the handoff it costs nothing: the updater clamps it
+ * forward and the window is measured from the handoff itself. Above the
+ * handoff it IS what the window is measured to, so a bound that under-shoots
+ * the death shortens the measured age and can revive a record the grace
+ * should have retired. Loosen it only with that in view: every millisecond
+ * earlier admits another handoff into the class, and the class suppresses.
+ *
+ * Optional as a dep, and null when nothing was in flight during the span. An
+ * absent reader skips the classification entirely — fail-open toward
+ * prompting, the same posture `currentBootSessionUuid` takes when the probe
+ * is unavailable.
*/
- installInFlight?(): InstallInFlight | null;
+ installInFlight?(span: { deathFromMs: number; deathToMs: number }): InstallInFlight | null;
logger: CrashLogger;
}
@@ -374,6 +392,30 @@ function isFileMissingError(err: unknown): boolean {
);
}
+/**
+ * ISO-8601 to epoch ms, or null when the field is absent or unparseable.
+ *
+ * Guarded rather than trusted because the death-span floor is read off a
+ * sentinel written across app-version boundaries, so it is only as well-formed
+ * as whichever build wrote it. An unguarded `Date.parse` yields `NaN`, and
+ * formatting that for the breadcrumb below throws a `RangeError` out of a
+ * boot-time scan, which is the consequence this helper is the sole guard
+ * against.
+ *
+ * `installWasInFlightDuring` guards its own bounds too, which is why removing
+ * either one alone still leaves the verdict correct. That seam carries why it
+ * does not lean on this one.
+ *
+ * The shutdown-marker TTL shares this helper for uniformity rather than for a
+ * live hazard, since that value is minted in-process moments before it is read
+ * back.
+ */
+function epochMsOrNull(iso: string | null): number | null {
+ if (iso === null) return null;
+ const ms = Date.parse(iso);
+ return Number.isFinite(ms) ? ms : null;
+}
+
function parseAckStore(raw: string): CrashAckStore | null {
try {
const parsed: unknown = JSON.parse(raw);
@@ -657,6 +699,19 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {
// A non-ENOENT read failure still means the file exists — the
// previous session did not clean-quit.
sentinelPresent = !isFileMissingError(err);
+ if (sentinelPresent) {
+ // Said out loud for the same reason the parse failure below is. A
+ // file this boot could not open reaches every downstream read as the
+ // same set of nulls a build predating those fields would produce, and
+ // the two point opposite ways: one is nothing to do, the other is a
+ // lock or a permission this app observed and could name. Without the
+ // errno there is no signal at all that the death span collapsed
+ // because of it.
+ deps.logger.warn(
+ { event: 'crash-detection.sentinel-read-failed', err },
+ 'dirty-shutdown sentinel exists but could not be read, so the previous session is dated by this boot alone',
+ );
+ }
}
let prevBootId: string | null = null;
let prevBootSessionUuid: string | null = null;
@@ -666,38 +721,53 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {
let prevSuspendedAt: string | null = null;
let prevAppVersion: string | null = null;
if (sentinelRaw !== null) {
+ // Only the parse is inside the catch, because its warn asserts that
+ // nothing downstream got a date. Reads left inside would make that true
+ // by accident of ordering, and a throw partway through them would null
+ // a machine-level-death disjunct while the log named another cause.
+ let parsed: Record<string, unknown> | null = null;
try {
- const parsed = JSON.parse(sentinelRaw) as Record<string, unknown> | null;
- const field = (key: string): string | null => {
- const value = parsed?.[key];
- return typeof value === 'string' && value !== '' ? value : null;
- };
- prevBootId = field('bootId');
- prevBootSessionUuid = field('bootSessionUuid');
- prevLastAliveAt = field('lastAliveAt');
- prevPendingOsShutdownAt = field('pendingOsShutdownAt');
- // Element-wise filtered rather than trusted wholesale: this file is
- // read across app-version boundaries, so the array is only as
- // well-formed as whichever build wrote it. A non-array, or one with
- // nothing usable in it, reads as "no cause named" — same as absent.
- const rawReasons = parsed?.osShutdownReasons;
- if (Array.isArray(rawReasons)) {
- const usable = rawReasons.filter(
- (value): value is string => typeof value === 'string' && value !== '',
- );
- prevOsShutdownReasons = usable.length > 0 ? usable : null;
- }
- prevSuspendedAt = field('suspendedAt');
- // Must be read here, before this boot overwrites the file below:
- // afterwards the value on disk is the RUNNING version, which is the
- // wrong answer in exactly the update-between-sessions case that
- // makes the question worth asking. Gated like the minidump's
- // annotation because it reaches the same line of the same report,
- // and this file is no more trustworthy than that one.
- prevAppVersion = asReportableAppVersion(field('appVersion'));
- } catch {
- // Torn write from the crashed session — presence alone is the signal.
+ parsed = JSON.parse(sentinelRaw) as Record<string, unknown> | null;
+ } catch (err) {
+ // Torn write from the crashed session — presence alone is the signal,
+ // so this is not fatal. Said out loud anyway: a file that parsed and
+ // simply carried no dates reaches every downstream read as the same
+ // set of nulls, and the two lead to different conclusions about why
+ // the death span collapsed onto the detecting clock. The cause rides
+ // along for the same reason the sibling write failure carries one, a
+ // truncated write and binary garbage being different findings.
+ deps.logger.warn(
+ { event: 'crash-detection.sentinel-parse-failed', err },
+ 'dirty-shutdown sentinel did not parse, so the previous session is dated by this boot alone',
+ );
}
+ const field = (key: string): string | null => {
+ const value = parsed?.[key];
+ return typeof value === 'string' && value !== '' ? value : null;
+ };
+ prevBootId = field('bootId');
+ prevBootSessionUuid = field('bootSessionUuid');
+ prevLastAliveAt = field('lastAliveAt');
+ prevPendingOsShutdownAt = field('pendingOsShutdownAt');
+ // Element-wise filtered rather than trusted wholesale: this file is
+ // read across app-version boundaries, so the array is only as
+ // well-formed as whichever build wrote it. A non-array, or one with
+ // nothing usable in it, reads as "no cause named" — same as absent.
+ const rawReasons = parsed?.osShutdownReasons;
+ if (Array.isArray(rawReasons)) {
+ const usable = rawReasons.filter(
+ (value): value is string => typeof value === 'string' && value !== '',
+ );
+ prevOsShutdownReasons = usable.length > 0 ? usable : null;
+ }
+ prevSuspendedAt = field('suspendedAt');
+ // Must be read here, before this boot overwrites the file below:
+ // afterwards the value on disk is the RUNNING version, which is the
+ // wrong answer in exactly the update-between-sessions case that
+ // makes the question worth asking. Gated like the minidump's
+ // annotation because it reaches the same line of the same report,
+ // and this file is no more trustworthy than that one.
+ prevAppVersion = asReportableAppVersion(field('appVersion'));
}
// Every fresh dump is classified before it can influence anything: the
@@ -785,10 +855,30 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {
// The fourth way a session ends without the app having crashed, and the
// only one the machine did not cause: this app committed to an update,
- // and the installer terminated the running process to replace its files.
- // That kill bypasses the quit sequence on both platforms — SIGKILL from
- // ShipIt, an outright process termination from NSIS — so `will-quit`
- // never runs, `markCleanQuit()` never clears the sentinel, and without
+ // and the session ended without its quit sequence completing.
+ //
+ // Neither installer is a plain pre-emption of a healthy app. The Windows
+ // one waits over a second for the app to go before it intervenes at all,
+ // so an app that quits promptly is never touched and this class never
+ // sees it, while one still tearing down loses that race. The macOS helper
+ // (Squirrel's ShipIt) does not terminate the app at all: it waits for the
+ // process to exit and then swaps the bundle, per the sequence documented
+ // in Squirrel.Mac and electron/electron#36130. Either way the reachable
+ // population is a session that was still quitting, which is why this
+ // class is about the quit sequence not completing rather than about a
+ // kill signal.
+ //
+ // What decides the frame this question gets asked in is not the platform
+ // but whether anything stamped the handoff. Both commit points stamp it
+ // while a live process still exists to observe them: the "Relaunch now"
+ // click on every platform, and `before-quit` wherever install-on-quit is
+ // armed, which is everywhere except Linux. A session that ended without
+ // reaching either arrives carrying only the moment the artifact was
+ // staged. That fallback keeps answering at the detecting instant rather
+ // than across the span, so where nothing was stamped this class still
+ // decays with how long the user left the app closed, and
+ // `installWasInFlightDuring` carries why a finished download cannot widen
+ // it. Either way `markCleanQuit()` never clears the sentinel, and without
// this class the next boot reports a death the app arranged on purpose.
//
// Deliberately asked of the updater rather than inferred here. A version
@@ -796,7 +886,30 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {
// test and it is unsound: when the install FAILS, the relaunched app is
// the same version as the one that was killed, so the delta is zero on
// exactly the subset this class was first reported from.
- const installInFlight = deps.installInFlight?.() ?? null;
+ //
+ // The death is a span, not an instant: the previous session was alive at
+ // `deathFromMs` and gone by `detectedAtMs`. The two tiers are not
+ // interchangeable, which is why the one that fired is logged rather than
+ // left to be re-derived. The heartbeat dates the death to within one
+ // interval, and the sentinel gets one at birth rather than at its first
+ // tick, so every sentinel a current build writes carries one. Without it
+ // the span collapses onto the detecting clock, which is no bound at all
+ // and is the frame this class must never be asked in when a date IS
+ // available.
+ //
+ // The start of the session is deliberately not the middle tier, though it
+ // is present and is a sound lower bound. It dates the boot rather than the
+ // death, so a session that ran for hours before genuinely crashing and one
+ // the installer killed seconds in reduce to the same span, and preferring
+ // it resolves that ambiguity toward silence. Collapsing resolves it toward
+ // asking, which is this subsystem's posture everywhere else for a probe it
+ // cannot reason from.
+ const detectedAtMs = detectedAt.getTime();
+ const lastAliveMs = epochMsOrNull(prevLastAliveAt);
+ const deathFromMs = lastAliveMs ?? detectedAtMs;
+ const deathFromSource = lastAliveMs !== null ? 'last-alive' : 'detected-at';
+ const installInFlight =
+ deps.installInFlight?.({ deathFromMs, deathToMs: detectedAtMs }) ?? null;
const updateInstallDeath = sentinelPresent && installInFlight !== null;
let armed: OkBugReportCrashDetectedEvent | null = null;
@@ -817,11 +930,46 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {
// a reader can tell "no install was in flight" from "this build
// predates the class".
attemptedInstall: installInFlight?.attemptedVersion ?? null,
- // False when the moment above is the staging fallback rather than a
+ // False when the moment below is the staging fallback rather than a
// handoff a live process recorded — the same distinction the
- // updater's own boot logs draw, and the one that says how tight the
- // window bounding this suppression actually was.
+ // updater's own boot logs draw. It says which commit the window was
+ // measured from, not how tight it was: a handoff a live process
+ // stamped dates the commit to the quit that preceded the death,
+ // while the staging fallback dates it to the download, which can
+ // precede the death by a whole session of ordinary use.
recordedHandoff: installInFlight?.recordedHandoff ?? null,
+ // The moment the window opened, and the span it had to overlap. A
+ // suppression here is invisible to the user by construction, so
+ // these are the only way a field report can tell a handoff that
+ // genuinely sat inside the death from one that got in because the
+ // span widened. `deathFromSource` names which tier bounded it, since
+ // the two differ by far more than the grace on a long session.
+ //
+ // Named for its encoding rather than sharing the updater's
+ // `handoffAt` key, which that module emits as raw epoch ms. Both
+ // describe the same instant and land in the same stream, so one key
+ // carrying two datatypes would break any reader keyed on the field
+ // name alone.
+ //
+ // The collision is resolved on this side because this key is new,
+ // while the updater's has shipped. Suffixing the numeric one instead
+ // would read better per line, since every other moment here is a bare
+ // `…At` holding ISO and `…Ms` is already that module's answer to the
+ // same question. It would also rename a key across released builds
+ // and cost triage another era to reconcile, on log statements this
+ // change has no other reason to touch.
+ handoffAtIso:
+ installInFlight !== null ? new Date(installInFlight.handoffAt).toISOString() : null,
+ deathFrom: new Date(deathFromMs).toISOString(),
+ deathFromSource,
+ // Clamped deliberately, unlike the updater's elapsed-time helpers,
+ // which return null on a negative. This reports the width the
+ // question was actually asked over, and a floor that postdates this
+ // boot (a clock correction across the quit) collapses the span rather
+ // than inverting it, so zero is the true answer there. The inversion
+ // itself stays visible: `deathFrom` and `detectedAt` are both on this
+ // line unclamped.
+ deathSpanMs: Math.max(0, detectedAtMs - deathFromMs),
detectedAt: detectedAt.toISOString(),
prevBootId,
prevBootSessionUuid,
@@ -931,17 +1079,29 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {
// and "hung until the relaunch" equally consistent with the
// report while pointing at different bugs.
//
- // The suspend and OS-shutdown markers are the other two
- // witnesses the suppression predicate is built from, and a
- // fresh dump routes their sessions here instead, where that
- // breadcrumb is never emitted. Carrying only some of them
- // would let their absence read as "no machine-level death"
- // when it only means "not the one we happened to log". All
- // three are logged even when null, for the same reason the
- // version below is.
+ // The suspend marker, the OS-shutdown marker and the updater's
+ // in-flight verdict are the other three witnesses the
+ // suppression predicate is built from, and a fresh dump routes
+ // their sessions here instead, where that breadcrumb is never
+ // emitted. Carrying only some of them would let their absence
+ // read as "no machine-level death" when it only means "not the
+ // one we happened to log". All four are logged even when null,
+ // for the same reason the version below is.
+ //
+ // Read the install one's PRESENCE, never its value. Reaching
+ // this line with a verdict on file requires a fresh dump, which
+ // is also what makes the event dump-driven, so a
+ // `dirtyShutdown: true` line logs null whether or not an
+ // install was on record. It is evidence on the dump-driven
+ // population and an era marker everywhere else, not a
+ // suppressed-versus-prompted ratio: that reads as this line
+ // thinning while `crash-detection.machine-level-death` thickens,
+ // and the attempt a declined verdict leaves unnamed here is on
+ // the updater's own reconciliation lines from the same boot.
lastAliveAt: prevLastAliveAt,
suspendedAt: prevSuspendedAt,
pendingOsShutdownAt: prevPendingOsShutdownAt,
+ attemptedInstall: installInFlight?.attemptedVersion ?? null,
// Logged even when null: this line is what an incident gets
// reconstructed from, and "we could not tell" is itself the
// finding when the two sources both come up empty.
@@ -989,6 +1149,11 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {
storeNeedsInit = false;
}
+ // `lastAliveAt` is seeded now, at arm time, rather than left for the first
+ // heartbeat, so a session that dies inside that first interval still gets
+ // a floor rather than none. What that buys the install-kill suppression is
+ // `INSTALL_DEFER_MAX_BOOTS`'s to state, since it takes a stamped handoff
+ // as well as a floor and only that site carries both.
sentinel = {
bootId: String(detectedAt.getTime()),
startedAt: detectedAt.toISOString(),
@@ -1020,11 +1185,8 @@ export function createCrashDetection(deps: CrashDetectionDeps): CrashDetection {
if (sentinel === null || cleanQuitMarked) return;
const nowAt = deps.now();
if (sentinel.pendingOsShutdownAt !== undefined) {
- const announcedMs = Date.parse(sentinel.pendingOsShutdownAt);
- if (
- Number.isFinite(announcedMs) &&
- nowAt.getTime() - announcedMs > OS_SHUTDOWN_MARKER_TTL_MS
- ) {
+ const announcedMs = epochMsOrNull(sentinel.pendingOsShutdownAt);
+ if (announcedMs !== null && nowAt.getTime() - announcedMs > OS_SHUTDOWN_MARKER_TTL_MS) {
delete sentinel.pendingOsShutdownAt;
// Cleared with the marker they describe: a cancelled shutdown we
// outlived must not leave the next boot a cause for an event that
diff --git a/packages/desktop/src/main/desktop-logger.ts b/packages/desktop/src/main/desktop-logger.ts
index 89e56230e..50679cfc3 100644
--- a/packages/desktop/src/main/desktop-logger.ts
+++ b/packages/desktop/src/main/desktop-logger.ts
@@ -147,10 +147,10 @@ export function getRootDesktopLogger(): pino.Logger {
/**
* Force-drain the async log destination synchronously. Created with
- * `sync: false`, the destination buffers writes — so a process killed without
- * draining (an auto-update `quitAndInstall` → Squirrel SIGKILL, or any app
- * quit) loses its unwritten tail, which is precisely the window where the most
- * diagnostic lines are emitted. Shutdown-path callers invoke this so those
+ * `sync: false`, the destination buffers writes — so a process that exits
+ * without draining (an auto-update `quitAndInstall`, or any app quit) loses its
+ * unwritten tail, which is precisely the window where the most diagnostic lines
+ * are emitted. Shutdown-path callers invoke this so those
* lines reach disk. Best-effort: never throws, so it can't derail a shutdown.
*/
export function flushDesktopLogger(): void {
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 0e86b3368..513c94c2f 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -184,7 +184,7 @@ import { resolveEffectiveInstanceName } from './auto-instance.ts';
import {
bootAutoUpdater,
channelFromVersion,
- installMayStillBeRunning,
+ installWasInFlightDuring,
type StartAutoUpdaterHandle,
} from './auto-updater.ts';
import { applyBackgroundThrottle } from './background-throttle.ts';
@@ -8009,8 +8009,10 @@ function bootPrimaryInstance(): void {
now: () => new Date(),
currentBootSessionUuid: readBootSessionUuid,
// Was an install this app committed to still possibly running when the
- // previous session ended? If so the installer killed it to replace its
- // files, and the dirty sentinel it left behind is not a crash.
+ // previous session ended? If so the session ended without its quit sequence
+ // completing so the installer could replace the app's files, and the dirty
+ // sentinel it left behind is not a crash. Which of the two platforms ends
+ // it, and how, is `crash-detection.ts`'s account to keep.
//
// Answered from `bootStateSnapshot`, taken at the top of this function
// before anything here can mutate the state file, so the verdict does not
@@ -8018,13 +8020,18 @@ function bootPrimaryInstance(): void {
// The staging stamp is passed as-is: the snapshot predates the stale-pending
// clear, so the field still holds the moment the artifact was staged.
//
- // Asked of the updater's own predicate rather than re-derived, so the bound
- // cannot drift from the one deciding whether to tell the user an install
- // failed.
- installInFlight: () =>
- installMayStillBeRunning(
+ // The span comes from detection and is forwarded whole. Only `deathFromMs`
+ // carries anything this boot does not already have, and substituting a
+ // wall-clock read for it reverts the suppression to decaying with how long
+ // the user left the app closed. TypeScript does not reject that
+ // substitution, so `install-in-flight-wiring.test.ts` pins this wiring and
+ // carries the derivation. Asked of the updater's own predicate rather than
+ // re-derived, so neither the bound nor the handoff resolution can drift
+ // from the one deciding whether to tell the user an install failed.
+ installInFlight: (span) =>
+ installWasInFlightDuring(
bootStateSnapshot,
- Date.now(),
+ span,
bootStateSnapshot.versionPendingInstallStagedAt,
),
logger: getLogger('crash-detection'),
@@ -9197,9 +9204,9 @@ function bootPrimaryInstance(): void {
// genuinely clean before ShipIt's pre-swap validation runs.
await wm?.stopAllOwnedServers();
// Drain the async log buffer before `quitAndInstall()` hands off to
- // Squirrel, which SIGKILLs this process for the bundle swap. Without
- // this, the relaunch-trigger + update lines emitted moments earlier
- // never reach disk (the destination is `sync: false`).
+ // Squirrel, which waits for this process to exit and then swaps the
+ // bundle. Without this, the relaunch-trigger + update lines emitted
+ // moments earlier never reach disk (the destination is `sync: false`).
flushDesktopLogger();
},
sweepUpdateSurvivors: sweepConsoleHostsBeforeUpdate,
diff --git a/packages/desktop/src/main/state-store.ts b/packages/desktop/src/main/state-store.ts
index 4e8baac27..8e04c4e69 100644
Binary files a/packages/desktop/src/main/state-store.ts and b/packages/desktop/src/main/state-store.ts differ
diff --git a/packages/desktop/tests/integration/install-in-flight-wiring.test.ts b/packages/desktop/tests/integration/install-in-flight-wiring.test.ts
new file mode 100644
index 000000000..6b752ebde
--- /dev/null
+++ b/packages/desktop/tests/integration/install-in-flight-wiring.test.ts
@@ -0,0 +1,123 @@
+/**
+ * Bypass-pin: `index.ts` must still forward crash detection's death span to
+ * the updater untouched.
+ *
+ * The reduction itself, the clamp arithmetic and the ladder that derives the
+ * span are all covered by tests that call the production functions directly
+ * (`auto-updater-install-in-flight.test.ts`, `crash-detection.test.ts`). The
+ * one fact those cannot reach is what the boot closure actually passes.
+ * `index.ts` is ~9,000 lines and imports `electron` at module scope, so no test
+ * can import it, and TypeScript will not help here: parameter-count
+ * assignability accepts a zero-argument closure against a one-required-parameter
+ * signature, so a closure that ignores the span and reads this boot's clock
+ * type-checks. That mis-wiring breaks the fix with every other test green. It
+ * narrows the span the question is asked over, collapsing it onto this boot,
+ * and a narrower span can only suppress less. So it withholds no prompt that
+ * was owed. It arms ones that were not, which is the symptom this fix exists to
+ * remove.
+ *
+ * Transposed bounds are the compiler's to catch, not this pin's: the span is one
+ * argument with named fields, so there is no positional pair to swap. The pin
+ * therefore only has to cover forwarding.
+ *
+ * What a text match cannot see is where the snapshot came from, so the second
+ * test asserts the one ordering the first depends on. It compares text
+ * positions, which stand in for execution order here because the snapshot runs
+ * synchronously in `bootPrimaryInstance`'s body while the updater boot is
+ * deferred into the `whenReady` continuation further down it. A synchronous
+ * statement always precedes that continuation whatever the text order says.
+ * Moving the snapshot INTO that continuation below the updater boot, or into a
+ * helper declared above its call site, would preserve the text order and invert
+ * the real one, which is the same argument for the extraction below.
+ *
+ * Everything else about the closure remains outside both: this is a stopgap for
+ * a composition root no test can import, not a substitute for constructing the
+ * deps and checking the verdict, which would need the dep construction lifted
+ * into a module of its own.
+ *
+ * A tight grep, not a structural parse, matching the posture and rationale of
+ * the bypass-pins in `server-exit-wiring.test.ts` and `dock-visibility.test.ts`.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+
+const indexTsPath = resolve(fileURLToPath(new URL('../../src/main/index.ts', import.meta.url)));
+const src = readFileSync(indexTsPath, 'utf-8');
+
+const FIX = (what: string): string =>
+ `\n[install-in-flight] ${what}\n\n` +
+ `Crash detection asks whether an update install was in flight during the span the previous\n` +
+ `session died in. The boot closure in index.ts is the only place that span reaches the updater,\n` +
+ `and it must forward the span it was handed. Reading this boot's clock instead type-checks and\n` +
+ `narrows the span, which fabricates crash prompts the app never owed. The full rationale is in\n` +
+ `the JSDoc of installWasInFlightDuring in auto-updater.ts.\n`;
+
+describe('install-in-flight death-span wiring (bypass-pin)', () => {
+ test('index.ts forwards the span it was handed to the updater', () => {
+ // Anchored end to end rather than on the callee alone: an unanchored match
+ // would accept a closure that names the parameter and then passes something
+ // else, which is exactly the reversion this guards. Match-counted like the
+ // sibling pin, so a second wiring added elsewhere has to be looked at
+ // rather than silently satisfying this one.
+ //
+ // The back-reference captures the identifier alone, not the padding around
+ // it. Capturing the padding too would make the pin formatting-sensitive: it
+ // would then demand the same spacing at both the parameter and the argument,
+ // so a reformatted call site would red CI claiming the span is no longer
+ // forwarded when it still is.
+ const wiring =
+ /installInFlight:\s*\(\s*(\w+)\s*\)\s*=>\s*installWasInFlightDuring\(\s*bootStateSnapshot\s*,\s*\1\s*,/g;
+ expect(
+ (src.match(wiring) ?? []).length,
+ FIX('index.ts no longer forwards the death span straight through to the updater.'),
+ ).toBe(1);
+ // The third argument is pinned in the same shape and for a stronger reason
+ // than the second: `appState` is `emptyState()` this early in boot, so a
+ // closure reading the staging stamp off it would pass null on every boot and
+ // silently kill the whole stampless branch, which is the win32 field shape.
+ // Nothing else covers it: the unit suites construct their own closures and
+ // pass the stamp by hand.
+ const stagingStamp =
+ /installWasInFlightDuring\(\s*bootStateSnapshot\s*,\s*\w+\s*,\s*bootStateSnapshot\.versionPendingInstallStagedAt\s*,?\s*\)/g;
+ expect(
+ (src.match(stagingStamp) ?? []).length,
+ FIX('index.ts no longer reads the staging stamp off the pre-reconciliation snapshot.'),
+ ).toBe(1);
+ });
+
+ test('the state snapshot is taken before the updater boots', () => {
+ // The argument name above is only worth pinning while the binding still
+ // holds a pre-reconciliation read: the stale-pending clear nulls
+ // `versionPendingInstallStagedAt`, which is the whole lower bound on the
+ // stampless path. A refactor moving the load below the updater boot leaves
+ // the regex above matching verbatim, so the ordering is asserted on its
+ // own rather than left implied by it.
+ // Anchored on the assignment rather than on `bootAutoUpdater(` alone: the
+ // file's boot-order header names that function in prose, and a single
+ // space removed from it would move this anchor into a comment and fire the
+ // assertion below with a cause that never happened.
+ const snapshotAt = src.indexOf('const bootStateSnapshot = loadAppState()');
+ const updaterBootAt = src.indexOf('autoUpdaterHandle = await bootAutoUpdater(');
+ expect(
+ snapshotAt,
+ FIX(
+ 'index.ts no longer takes its state snapshot with `const bootStateSnapshot = loadAppState()`.',
+ ),
+ ).toBeGreaterThan(-1);
+ expect(
+ updaterBootAt,
+ FIX(
+ 'index.ts no longer awaits bootAutoUpdater into autoUpdaterHandle, so this pin cannot see the ordering.',
+ ),
+ ).toBeGreaterThan(-1);
+ expect(
+ snapshotAt,
+ FIX(
+ 'the state snapshot is now taken after the updater boots, so it no longer carries the staging stamp.',
+ ),
+ ).toBeLessThan(updaterBootAt);
+ });
+});
diff --git a/packages/desktop/tests/unit/auto-updater-install-in-flight.test.ts b/packages/desktop/tests/unit/auto-updater-install-in-flight.test.ts
index bd3f4fd2c..8c83deb80 100644
--- a/packages/desktop/tests/unit/auto-updater-install-in-flight.test.ts
+++ b/packages/desktop/tests/unit/auto-updater-install-in-flight.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'vitest';
-import { installMayStillBeRunning } from '../../src/main/auto-updater.ts';
+import { installMayStillBeRunning, installWasInFlightDuring } from '../../src/main/auto-updater.ts';
import type { AppState } from '../../src/main/state-store.ts';
import { emptyState } from '../../src/main/state-store.ts';
@@ -61,8 +61,8 @@ describe('installMayStillBeRunning', () => {
});
test('the staging moment stands in when no live process recorded the handoff', () => {
- // A session killed mid-flight never quits, so it never stamps a handoff —
- // the path the macOS instances this class was first reported from take.
+ // A session that reached neither commit point, neither the "Relaunch now"
+ // click nor `before-quit`, never stamps a handoff of its own.
const inFlight = check(
state({ attemptedInstall: '0.61.3', versionPendingInstallStagedAt: NOW - 60_000 }),
);
@@ -130,6 +130,23 @@ describe('installMayStillBeRunning', () => {
).toBeNull();
});
+ test('a handoff that is not a number reads as no claim rather than a fresh one', () => {
+ // The failure here is one-directional and silent: every comparison against
+ // `NaN` is false, so an unrejected one passes the staleness bound by
+ // failing it and suppresses whatever the record's real age, then reaches
+ // the breadcrumb as a moment that cannot be formatted. Nothing produces
+ // this today, because the state loader coerces these fields. Both public
+ // entry points funnel through the same age helper, so both are pinned.
+ const nonNumeric = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: Number.NaN,
+ });
+ expect(check(nonNumeric)).toBeNull();
+ expect(
+ installWasInFlightDuring(nonNumeric, { deathFromMs: NOW - 60_000, deathToMs: NOW }, null),
+ ).toBeNull();
+ });
+
test('the hold terminates once the boot budget is spent', () => {
const lastBoot = state({
attemptedInstall: '0.61.3',
@@ -149,3 +166,206 @@ describe('installMayStillBeRunning', () => {
expect(check(spent)).toBeNull();
});
});
+
+/**
+ * The span-shaped sibling. Crash detection knows only that the previous
+ * session was alive at one moment and gone by another, so its question is
+ * whether the in-flight window overlaps that span rather than whether it
+ * covers one chosen instant. The overlap is reduced to a single anchor and
+ * delegated, so every boundary above still owns itself and none is restated
+ * here. What these pin is the reduction.
+ */
+describe('installWasInFlightDuring', () => {
+ const TWO_HOURS_MS = 2 * 60 * 60 * 1000;
+
+ function during(s: AppState, deathFromMs: number, deathToMs: number) {
+ return installWasInFlightDuring(s, { deathFromMs, deathToMs }, s.versionPendingInstallStagedAt);
+ }
+
+ test('a handoff before the span still counts while the span starts inside the window', () => {
+ // The window opened before the session was last seen alive and had not
+ // closed by then, so the install really was running during the span.
+ const s = state({ attemptedInstall: '0.61.3', attemptedInstallHandoffAt: NOW - 30 * 60_000 });
+
+ expect(during(s, NOW - 25 * 60_000, NOW)).not.toBeNull();
+ });
+
+ test('a handoff older than the grace at the start of the span is closed', () => {
+ // Nothing about a long span can revive a window that had already closed
+ // before the earliest moment the span covers.
+ const s = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: NOW - 25 * 60_000 - GRACE_MS - 1,
+ });
+
+ expect(during(s, NOW - 25 * 60_000, NOW)).toBeNull();
+ });
+
+ test('a window that opens and closes inside the span counts, however long the span', () => {
+ // The shape the instant-shaped predicate cannot answer at either end. The
+ // handoff lands after the last heartbeat and the window closes hours before
+ // the reopen, so both ends of the span read empty while the truth is that
+ // the install was running for part of it.
+ const handoffAt = NOW - TWO_HOURS_MS + 45_000;
+ const s = state({ attemptedInstall: '0.61.3', attemptedInstallHandoffAt: handoffAt });
+
+ expect(during(s, NOW - TWO_HOURS_MS, NOW)).toEqual({
+ attemptedVersion: '0.61.3',
+ handoffAt,
+ recordedHandoff: true,
+ });
+ });
+
+ test('a handoff after the span ended is not in flight during it', () => {
+ // A stamp ahead of the whole span is the wall-clock correction the instant
+ // predicate already refuses, and clamping must not launder it into a yes.
+ const s = state({ attemptedInstall: '0.61.3', attemptedInstallHandoffAt: NOW + 60_000 });
+
+ expect(during(s, NOW - 60 * 60_000, NOW)).toBeNull();
+ });
+
+ test('a span whose start is later than its end collapses to its end', () => {
+ // A lower bound that postdates the boot which read it carries no usable
+ // information, so the question falls back to the single instant the caller
+ // can vouch for rather than inverting into a span that never happened.
+ const fresh = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: NOW - 5 * 60_000,
+ });
+ const stale = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: NOW - GRACE_MS - 1,
+ });
+
+ expect(during(fresh, NOW + 60 * 60_000, NOW)).toEqual(check(fresh));
+ expect(during(stale, NOW + 60 * 60_000, NOW)).toEqual(check(stale));
+ });
+
+ test('a span end that is not a number takes the question out of play', () => {
+ // Nothing is left to anchor to when it is the end that is unusable, and
+ // every comparison against NaN is false, so an unguarded one would pass the
+ // staleness gate by failing it and hold a record the grace retired hours
+ // ago. The answer is no claim at all.
+ const stale = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: NOW - 5 * 60 * 60 * 1000,
+ });
+
+ expect(during(stale, NOW - TWO_HOURS_MS, Number.NaN)).toBeNull();
+ });
+
+ test('a span start that is not a number collapses onto the end', () => {
+ // The end is still an instant the caller can vouch for, so the question
+ // degrades to that single moment rather than being abandoned, the same
+ // treatment a start that postdates its end already gets. Two rows, because
+ // they pin different halves: the fresh handoff shows the collapse landing
+ // on the end rather than the question being refused, and the stale one is
+ // what an unguarded `Math.min` would carry through as NaN and suppress.
+ const fresh = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: NOW - 5 * 60_000,
+ });
+ const stale = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: NOW - 5 * 60 * 60 * 1000,
+ });
+
+ expect(during(fresh, Number.NaN, NOW)).toEqual(check(fresh));
+ expect(during(stale, Number.NaN, NOW)).toBeNull();
+ });
+
+ test('the boot budget does not bound a span that covers an interval', () => {
+ // A widened span drops the cap, and the same fixture is refused in the
+ // instant frame, which is where the count belongs.
+ // `installWasInFlightDuring` carries why.
+ const s = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: NOW - TWO_HOURS_MS + 45_000,
+ attemptedInstallDeferredBoots: MAX_BOOTS,
+ });
+
+ expect(during(s, NOW - TWO_HOURS_MS, NOW)).toEqual({
+ attemptedVersion: '0.61.3',
+ handoffAt: NOW - TWO_HOURS_MS + 45_000,
+ recordedHandoff: true,
+ });
+ expect(check(s)).toBeNull();
+ });
+
+ test('a staged commit with nothing stamped still answers at the instant', () => {
+ // The branch that carries no stamp at all, which nothing else in this block
+ // reaches. The staging moment is the only date available, so the span
+ // collapses onto its later end and the answer is the one the instant-shaped
+ // predicate gives. `recordedHandoff` is asserted because it is what a
+ // triager branches on to know which frame produced the verdict.
+ const stagedAt = NOW - 5 * 60_000;
+ const s = state({ attemptedInstall: '0.61.3', versionPendingInstallStagedAt: stagedAt });
+
+ expect(during(s, NOW - TWO_HOURS_MS, NOW)).toEqual({
+ attemptedVersion: '0.61.3',
+ handoffAt: stagedAt,
+ recordedHandoff: false,
+ });
+ expect(during(s, NOW - TWO_HOURS_MS, NOW)).toEqual(check(s));
+ });
+
+ test('the boot budget still bounds the span question with nothing stamped', () => {
+ // The other half of the same branch. Where the anchor is this boot's own
+ // clock the count is coherent again, and it is the only bound that
+ // terminates the hold there, for the re-arm reason the cap constant sets
+ // out. Answering as the instant frame does is what keeps this path
+ // unchanged by the span reduction.
+ const stagedAt = NOW - 5 * 60_000;
+ const s = state({
+ attemptedInstall: '0.61.3',
+ versionPendingInstallStagedAt: stagedAt,
+ attemptedInstallDeferredBoots: MAX_BOOTS,
+ });
+
+ expect(during(s, NOW - TWO_HOURS_MS, NOW)).toBeNull();
+ expect(check(s)).toBeNull();
+ });
+
+ test('the boot budget bounds a stamped handoff whose span floor collapsed', () => {
+ // The stamp is not what the cap turns on. A sentinel carrying no usable
+ // heartbeat leaves the caller passing its own clock as both ends, so even a
+ // stamped handoff is asked at the detecting instant, which is the frame the
+ // count belongs to. Gating on the stamp instead would drop the bound here
+ // and suppress on a boot the instant predicate refuses, which is the one
+ // direction that fails toward silence.
+ const s = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: NOW - 5 * 60_000,
+ attemptedInstallDeferredBoots: MAX_BOOTS,
+ });
+
+ expect(during(s, NOW, NOW)).toEqual(check(s));
+ expect(during(s, NOW, NOW)).toBeNull();
+ // Under the grace and under the cap, the same collapsed span still answers.
+ const held = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: NOW - 5 * 60_000,
+ });
+ expect(during(held, NOW, NOW)).toEqual(check(held));
+ expect(during(held, NOW, NOW)).not.toBeNull();
+ });
+
+ test('a handoff inherited from an earlier boot suppresses within the grace of the span', () => {
+ // The widening this reduction accepts, pinned rather than left implicit. A
+ // stamp no longer describing anything running still suppresses a death it
+ // sits within half an hour of, because nothing in the record distinguishes
+ // it from one that does. The grace is what keeps that to half an hour: the
+ // same stamp a minute older is refused.
+ const inside = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: NOW - 20 * 60_000,
+ });
+ const outside = state({
+ attemptedInstall: '0.61.3',
+ attemptedInstallHandoffAt: NOW - 20 * 60_000 - GRACE_MS - 1,
+ });
+
+ expect(during(inside, NOW - 60_000, NOW)).not.toBeNull();
+ expect(during(outside, NOW - 60_000, NOW)).toBeNull();
+ });
+});