Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Record the interface language in bug reports and report language changes (PRD-7878) (#3371)

Andrew Mikofalvy2f4b75cf8578
diff --git a/.changeset/bug-report-interface-language.md b/.changeset/bug-report-interface-language.md
new file mode 100644
index 000000000..7547a4864
--- /dev/null
+++ b/.changeset/bug-report-interface-language.md
@@ -0,0 +1,11 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Bug reports now record which language the app was in when they were filed, and the app reports when someone changes that setting.
+
+Until now a report said nothing about the interface language, so a problem that only happens in one language — text running the wrong way, a label that overflows its button, a date read the wrong way round — arrived looking like it happened in English. Reports now carry the language setting exactly as it was chosen, what it resolved to at that moment, which of the four tiers decided (an environment override, the saved choice, the operating system, or the fallback), and the system language list that tier read. That last part matters most for the default setting, "System": on its own it says nothing, and beside the resolved language and the list behind it, the difference between the app guessing wrong and the operating system being set to something unexpected becomes visible without a round of questions.
+
+Reports filed from the desktop app record the language actually on screen, including a change made moments earlier that has not finished saving — which is the report someone files when changing the language appears not to take. Only the interface language is recorded; document text, titles, and filenames are untouched, and nothing about their contents is described.
+
+The app also now reports when the language setting is changed, so which languages people choose can inform which ones get translated next. It records the previous and new setting only — "System" stays "System" rather than being resolved to a specific language, so choosing English deliberately stays distinguishable from inheriting it. As with all product telemetry this is off unless telemetry is enabled.
diff --git a/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx
index ed7b61f70..237808563 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx
+++ b/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx
@@ -10,11 +10,12 @@ import {
PICKER_LOCALES,
SavedThemesListSuccessSchema,
} from '@inkeep/open-knowledge-core';
+import { type Attributes, type Tracer, trace } from '@opentelemetry/api';
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider, useTheme } from 'next-themes';
import type { ReactNode } from 'react';
-import { afterEach, describe, expect, test } from 'vitest';
+import { afterEach, describe, expect, type Mock, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { ConfigContext, type ConfigContextValue } from '@/lib/config-context';
import { emitConfigValidationRejected } from '@/lib/config-validation-events';
@@ -392,6 +393,105 @@ describe('SettingsDialogBody language picker', () => {
});
});
+ /**
+ * The signal behind locale promotion. Recorded at the picker rather than
+ * where the language is applied, because only the picker knows the user did
+ * it — the apply path also runs for an external edit to `global.yml` and for
+ * another window's change arriving over the CRDT.
+ *
+ * The OTel boundary is faked with `spyOn(trace, 'getTracer')` rather than a
+ * module mock, which would persist in the shared unit-test module registry
+ * and clobber the real provider other files register.
+ */
+ describe('change telemetry', () => {
+ const spans: { name: string; attributes: Attributes | undefined }[] = [];
+ let getTracerSpy: Mock<typeof trace.getTracer>;
+
+ function installTracerSpy(): void {
+ spans.length = 0;
+ getTracerSpy = vi.spyOn(trace, 'getTracer').mockImplementation(
+ () =>
+ ({
+ startSpan: (name: string, options?: { attributes?: Attributes }) => {
+ spans.push({ name, attributes: options?.attributes });
+ return { end: () => undefined };
+ },
+ }) as unknown as Tracer,
+ );
+ }
+
+ afterEach(() => {
+ getTracerSpy?.mockRestore();
+ });
+
+ test('picking a language records the change with both preferences', async () => {
+ installTracerSpy();
+ const user = userEvent.setup();
+ const { binding } = makeBinding();
+ renderPreferences(binding);
+
+ await openLanguagePicker(user);
+ await user.click(screen.getByRole('option', { name: 'español' }));
+
+ await waitFor(() => {
+ expect(spans).toEqual([
+ {
+ name: 'ok.language.preferenceChanged',
+ attributes: { 'ok.language.from': 'system', 'ok.language.to': 'es' },
+ },
+ ]);
+ });
+ });
+
+ // Unresolved on the way out: a user who deliberately picked English and one
+ // following an English OS are the same resolved locale and opposite signals
+ // for promotion.
+ test('switching back to System is recorded as the sentinel', async () => {
+ installTracerSpy();
+ const user = userEvent.setup();
+ const { binding } = makeBinding(ConfigSchema.parse({ appearance: { language: 'fr' } }));
+ renderPreferences(binding);
+
+ await openLanguagePicker(user);
+ await user.click(screen.getByRole('option', { name: 'System' }));
+
+ await waitFor(() => {
+ expect(spans[0]?.attributes).toEqual({
+ 'ok.language.from': 'fr',
+ 'ok.language.to': 'system',
+ });
+ });
+ });
+
+ // Re-selecting the language already in force is not a change, and counting
+ // it would inflate exactly the number promotion decisions read.
+ //
+ // The absence is asserted only AFTER a real emission has been observed on
+ // this same mount. A bare "nothing was recorded" cannot tell a working
+ // guard from a telemetry path that never fires at all, so the first half
+ // establishes that spans do arrive here before the second half claims one
+ // did not.
+ test('re-picking the current language records nothing', async () => {
+ installTracerSpy();
+ const user = userEvent.setup();
+ const { binding } = makeBinding(ConfigSchema.parse({ appearance: { language: 'es' } }));
+ renderPreferences(binding);
+
+ await openLanguagePicker(user);
+ await user.click(screen.getByRole('option', { name: 'System' }));
+ await waitFor(() => {
+ expect(spans).toHaveLength(1);
+ });
+
+ await openLanguagePicker(user);
+ await user.click(screen.getByRole('option', { name: 'System' }));
+
+ await waitFor(() => {
+ expect(spans).toHaveLength(1);
+ });
+ });
+ });
+
test('a hand-set withheld locale still shows, without becoming an option', async () => {
const user = userEvent.setup();
const config = ConfigSchema.parse({ appearance: { language: 'ar' } });
diff --git a/packages/app/src/components/settings/field-controls.tsx b/packages/app/src/components/settings/field-controls.tsx
index ca700a335..2e04f9bfa 100644
--- a/packages/app/src/components/settings/field-controls.tsx
+++ b/packages/app/src/components/settings/field-controls.tsx
@@ -49,8 +49,10 @@ import {
resolveModePreference,
} from '@/lib/color-themes';
import { useConfigContextOptional } from '@/lib/config-context';
+import { recordLanguagePreferenceChanged } from '@/lib/language-telemetry';
import { recordSavedThemeAssignment } from '@/lib/saved-themes-telemetry';
import { applyColorThemeToDom } from '@/lib/use-apply-config-color-theme';
+import { narrowLanguagePreference } from '@/lib/use-apply-config-language';
import { cn } from '@/lib/utils';
import { LanguageSelect } from './LanguageSelect';
import { SavedThemesTiles } from './SavedThemesTiles';
@@ -360,6 +362,19 @@ function FieldControlBody({
ref={ctl.ref}
onBlur={ctl.onBlur}
onValueChange={(next) => {
+ // Recorded HERE rather than where the language is applied, because
+ // only this site knows the user did it. `useApplyConfigLanguage` also
+ // runs for an external edit to `global.yml` and for another window's
+ // change arriving over the CRDT, which would inflate the count and
+ // attribute someone else's pick to this session.
+ //
+ // Guarded on an actual difference so the count means changes rather
+ // than interactions, without resting on whether the underlying Select
+ // chooses to fire for a re-pick of the value already in force.
+ const previous = narrowLanguagePreference(ctl.value) ?? 'system';
+ if (previous !== next) {
+ recordLanguagePreferenceChanged({ from: previous, to: next });
+ }
ctl.onChange(next);
onCommit();
}}
diff --git a/packages/app/src/lib/language-telemetry.test.ts b/packages/app/src/lib/language-telemetry.test.ts
new file mode 100644
index 000000000..6979a2322
--- /dev/null
+++ b/packages/app/src/lib/language-telemetry.test.ts
@@ -0,0 +1,80 @@
+/**
+ * Renderer language telemetry — assert the emitter starts a span under the
+ * canonical name carrying the unresolved `from`/`to` preferences, and that an
+ * OTel SDK fault (a `getTracer` / `startSpan` throw from the third-party
+ * boundary) is contained: it must never escape the picker's change handler and
+ * take the language switch down with it.
+ *
+ * The OTel boundary is faked with `spyOn(trace, 'getTracer')` rather than
+ * `vi.doMock('@opentelemetry/api')`: a module mock persists in the shared
+ * unit-test module registry and would clobber the real provider that
+ * `lib/perf/otel-spans.test.ts` registers. The spy is installed per-test and
+ * restored in `afterEach`, so nothing bleeds into another file's tracer.
+ */
+
+import { type Attributes, type Tracer, trace } from '@opentelemetry/api';
+import { afterEach, beforeEach, describe, expect, type Mock, test, vi } from 'vitest';
+import { recordLanguagePreferenceChanged } from './language-telemetry';
+
+const spans: { name: string; attributes: Attributes | undefined }[] = [];
+let startSpanThrows = false;
+let getTracerSpy: Mock<typeof trace.getTracer>;
+
+beforeEach(() => {
+ spans.length = 0;
+ startSpanThrows = false;
+ getTracerSpy = vi.spyOn(trace, 'getTracer').mockImplementation(
+ () =>
+ ({
+ startSpan: (name: string, options?: { attributes?: Attributes }) => {
+ if (startSpanThrows) throw new Error('otel provider fault');
+ spans.push({ name, attributes: options?.attributes });
+ return { end: () => undefined };
+ },
+ }) as unknown as Tracer,
+ );
+});
+
+afterEach(() => {
+ getTracerSpy.mockRestore();
+});
+
+describe('renderer language telemetry', () => {
+ test('records the change under ok.language.preferenceChanged', () => {
+ recordLanguagePreferenceChanged({ from: 'system', to: 'es' });
+ expect(spans).toEqual([
+ {
+ name: 'ok.language.preferenceChanged',
+ attributes: { 'ok.language.from': 'system', 'ok.language.to': 'es' },
+ },
+ ]);
+ });
+
+ // The whole point of the event: promotion decisions need to know which
+ // language was chosen, so a name-only span would answer nothing.
+ test('carries the chosen locale, not just the fact of a change', () => {
+ recordLanguagePreferenceChanged({ from: 'en', to: 'zh-Hans' });
+ expect(spans[0]?.attributes).toEqual({
+ 'ok.language.from': 'en',
+ 'ok.language.to': 'zh-Hans',
+ });
+ });
+
+ // `'system'` must survive as `'system'`. Resolving it before emitting would
+ // make a user who deliberately picked English indistinguishable from one
+ // following an English OS — opposite signals for promotion.
+ test('reports a switch back to system unresolved', () => {
+ recordLanguagePreferenceChanged({ from: 'fr', to: 'system' });
+ expect(spans[0]?.attributes).toEqual({
+ 'ok.language.from': 'fr',
+ 'ok.language.to': 'system',
+ });
+ });
+});
+
+describe('renderer language telemetry — SDK fault isolation', () => {
+ test('a startSpan throw does not escape the emitter', () => {
+ startSpanThrows = true;
+ expect(() => recordLanguagePreferenceChanged({ from: 'system', to: 'ar' })).not.toThrow();
+ });
+});
diff --git a/packages/app/src/lib/language-telemetry.ts b/packages/app/src/lib/language-telemetry.ts
new file mode 100644
index 000000000..421bbb66d
--- /dev/null
+++ b/packages/app/src/lib/language-telemetry.ts
@@ -0,0 +1,61 @@
+/**
+ * Interface-language telemetry — the signal behind locale promotion.
+ *
+ * Emits one span when the user changes the language in Settings. Which
+ * languages get picked, and how often `'system'` is overridden, is what decides
+ * whether a locale earns promotion out of the layout-deferred set and where
+ * translation effort goes next; without it that is a guess.
+ *
+ * Unlike the sibling adoption markers (`terminal-telemetry.ts`,
+ * `slides-telemetry.ts`), this one carries attributes. Those deliberately carry
+ * none because their payload would be document names and shell I/O — user
+ * content. A locale tag is not: `from` and `to` each range over a closed enum
+ * (`'system'` plus `SUPPORTED_LOCALES`), so the pair is bounded at
+ * `(1 + SUPPORTED_LOCALES.length)²` regardless of how that list grows — well
+ * inside the cardinality discipline — and the whole question the event exists
+ * to answer is *which* language. A bare marker would record that someone
+ * changed language and lose the only part worth having.
+ *
+ * The preference is reported UNRESOLVED, so `'system'` arrives as `'system'`.
+ * Resolving it here would erase the distinction between a user who deliberately
+ * chose English and one following an English OS — the two look identical in the
+ * resolved value and mean opposite things for promotion.
+ *
+ * `@opentelemetry/api` returns a no-op tracer when no SDK is registered, so
+ * this is zero-cost unless `VITE_OTEL_ENABLED='true'`.
+ */
+import type { LanguagePreference } from '@inkeep/open-knowledge-core';
+import { trace } from '@opentelemetry/api';
+
+const TRACER_NAME = 'open-knowledge-app';
+
+/**
+ * The user picked a different interface language.
+ *
+ * Wrapped so an opt-in OTel SDK fault (a `startSpan`/`end` throw from a
+ * misconfigured provider or a flush-while-shutdown race — `@opentelemetry/api`
+ * is a third-party boundary that can genuinely throw) cannot escape the picker's
+ * change handler and take the language switch down with it. Mirrors the
+ * fault-isolation wrap in `lib/terminal-telemetry.ts`.
+ */
+export function recordLanguagePreferenceChanged({
+ from,
+ to,
+}: {
+ from: LanguagePreference;
+ to: LanguagePreference;
+}): void {
+ try {
+ trace
+ .getTracer(TRACER_NAME)
+ .startSpan('ok.language.preferenceChanged', {
+ attributes: { 'ok.language.from': from, 'ok.language.to': to },
+ })
+ .end();
+ } catch (err) {
+ console.warn(
+ '[language-telemetry] span emit failed:',
+ err instanceof Error ? err : String(err),
+ );
+ }
+}
diff --git a/packages/cli/src/commands/bug-report-bundle.ts b/packages/cli/src/commands/bug-report-bundle.ts
index 3658d1569..5f5a170e8 100644
--- a/packages/cli/src/commands/bug-report-bundle.ts
+++ b/packages/cli/src/commands/bug-report-bundle.ts
@@ -25,6 +25,7 @@ import type { ZipFile } from 'yazl';
// Keep this import type-only: `diagnose/bundle.ts` imports from this module
// too, so a value import in either direction would form a runtime cycle.
import type { DesktopMetadata } from '../diagnose/bundle.ts';
+import type { LanguageMetadata } from '../report-language.ts';
import { redactContent, SECRET_PATTERN_NAMES } from './bug-report-redact.ts';
import { DESKTOP_BUNDLE_ID } from './desktop-dispatch.ts';
@@ -97,6 +98,12 @@ export interface CollectStandardBundleOptions {
* full-level bundle's `host.desktop: null` convention.
*/
desktop?: DesktopMetadata | null;
+ /**
+ * Interface-language metadata recorded in `sysinfo.json` (and, through it,
+ * the manifest). Omitted reads as "the caller supplied no reader", which is
+ * distinguishable from a bundle predating the field.
+ */
+ language?: LanguageMetadata | null;
logger?: BundleLogger;
}
@@ -398,6 +405,9 @@ export async function collectStandardBundle(
// Always present so a recipient can distinguish "not an Electron host"
// (null) from a bundle predating the field (absent).
sysinfo.desktop = opts.desktop ?? null;
+ // The interface language the report was filed in. Always present for the same
+ // reason, and `null` only for a caller that supplied no reader at all.
+ sysinfo.language = opts.language ?? null;
const { files: logFiles, excludedByProjectSlug: logFilesExcludedByProjectSlug } = collectLogs(
projectSlug,
userLogsDir,
diff --git a/packages/cli/src/diagnose/bundle.test.ts b/packages/cli/src/diagnose/bundle.test.ts
index b1b84972c..7f89a4b31 100644
--- a/packages/cli/src/diagnose/bundle.test.ts
+++ b/packages/cli/src/diagnose/bundle.test.ts
@@ -20,6 +20,7 @@ import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { afterEach, describe, expect, test } from 'vitest';
import { ZipFile } from 'yazl';
+import type { LanguageMetadata } from '../report-language.ts';
import {
CHECKPOINT_REF_GIT_FORMAT,
type CollectBundleDeps,
@@ -46,6 +47,13 @@ afterEach(() => {
tmpDirs.length = 0;
});
+const DETERMINISTIC_LANGUAGE = {
+ preference: 'system',
+ locale: 'en',
+ source: 'fallback',
+ systemLanguages: [],
+} as const satisfies LanguageMetadata;
+
function makeDeterministicDeps(over: Partial<CollectBundleDeps> = {}): CollectBundleDeps {
return {
fetchAgentPresence: async () => null,
@@ -56,6 +64,10 @@ function makeDeterministicDeps(over: Partial<CollectBundleDeps> = {}): CollectBu
now: () => new Date('2026-05-28T14:22:01.000Z'),
okVersion: () => '0.7.99',
readDesktopEnv: () => null,
+ // Pinned like every sibling seam here: the real reader resolves against the
+ // running machine's user config and `LANG`, which would make these
+ // assertions read differently on a developer box than in CI.
+ readLanguage: () => DETERMINISTIC_LANGUAGE,
readRuntime: () => ({
nodeVersion: 'v22.18.0',
platform: 'darwin',
@@ -89,7 +101,10 @@ describe('collectBundle — smoke', () => {
platform: 'darwin',
arch: 'arm64',
});
- expect(collected.manifest.host).toEqual({ desktop: null });
+ expect(collected.manifest.host).toEqual({
+ desktop: null,
+ language: DETERMINISTIC_LANGUAGE,
+ });
expect(collected.manifest.serverStatus).toBe('not-running');
expect(collected.manifest.redaction).toEqual({ applied: false });
@@ -571,7 +586,7 @@ describe('collectBundle — state files', () => {
platform: 'darwin',
arch: 'arm64',
});
- expect(runtime.host).toEqual({ desktop: null });
+ expect(runtime.host).toEqual({ desktop: null, language: DETERMINISTIC_LANGUAGE });
collected.cleanup();
});
diff --git a/packages/cli/src/diagnose/bundle.ts b/packages/cli/src/diagnose/bundle.ts
index 1c65b2cba..21d73e116 100644
--- a/packages/cli/src/diagnose/bundle.ts
+++ b/packages/cli/src/diagnose/bundle.ts
@@ -41,6 +41,7 @@ import { ZipFile } from 'yazl';
import type { BundleExtraFile, BundleLogger } from '../commands/bug-report-bundle.ts';
import { redactContent } from '../commands/bug-report-redact.ts';
import { PACKAGE_VERSION } from '../constants.ts';
+import { defaultReadLanguage, type LanguageMetadata } from '../report-language.ts';
import { isRotatedLogPath, redactStagedBundle } from './bundle-redact.ts';
// ---------------------------------------------------------------------------
@@ -115,6 +116,12 @@ interface BundleManifest {
};
host: {
desktop: DesktopMetadata | null;
+ /**
+ * The interface language the report was filed in. `null` when the caller
+ * supplied no reader — distinguishable from a manifest predating the field,
+ * which has no key at all.
+ */
+ language: LanguageMetadata | null;
};
contentDir: {
/** SHA-256 of the absolute content-dir path. 64 lowercase hex chars. */
@@ -240,6 +247,15 @@ export interface CollectBundleDeps {
okVersion?: () => string;
/** Returns the `OK_DESKTOP_*` env block, or `null` when no desktop host is present. */
readDesktopEnv?: () => DesktopMetadata | null;
+ /**
+ * Returns the interface language the report is being filed in. Defaults to
+ * the POSIX-environment reader, which is right for every caller that reaches
+ * this collector directly — they are all shell commands. The Electron host
+ * arrives through `collectReportBundle` instead and injects its own, because
+ * a GUI process has no `LANG` to resolve against and this default would
+ * report the fallback locale no matter what the user was looking at.
+ */
+ readLanguage?: () => LanguageMetadata;
/** Returns runtime introspection — Node version, platform, arch. */
readRuntime?: () => { nodeVersion: string; platform: string; arch: string };
/**
@@ -709,6 +725,7 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedB
const now = deps.now ?? (() => new Date());
const okVersion = deps.okVersion ?? (() => PACKAGE_VERSION);
const readDesktopEnv = deps.readDesktopEnv ?? defaultReadDesktopEnv;
+ const readLanguage = deps.readLanguage ?? defaultReadLanguage;
const readRuntime = deps.readRuntime ?? defaultReadRuntime;
const isOtlpPushEnabled = deps.isOtlpPushEnabled ?? defaultIsOtlpPushEnabled;
@@ -827,6 +844,7 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedB
// Runtime + desktop block.
const runtime = readRuntime();
const desktop = readDesktopEnv();
+ const language = readLanguage();
const runtimeJson = {
ok: {
version: okVersion(),
@@ -834,7 +852,7 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedB
platform: runtime.platform,
arch: runtime.arch,
},
- host: { desktop },
+ host: { desktop, language },
};
writeFileSync(
join(stagingDir, 'state', 'runtime.json'),
@@ -919,7 +937,7 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedB
platform: runtime.platform,
arch: runtime.arch,
},
- host: { desktop },
+ host: { desktop, language },
contentDir: {
// pathSha256 stays as the SHA-256 of the original absolute path — it's
// a stable correlation identifier for the recipient. The absolutePath
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 0060cc548..8d330a52c 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -147,6 +147,9 @@ export {
type ReportBundleResult,
type ReportBundleSummary,
} from './report-bundle.ts';
+// The value type of `collectReportBundle`'s `readLanguage` seam, so the desktop
+// app can inject the language it is actually rendering in.
+export type { LanguageMetadata } from './report-language.ts';
export {
addOkPathsToGitExclude,
type ExcludeWriteResult,
diff --git a/packages/cli/src/report-bundle.test.ts b/packages/cli/src/report-bundle.test.ts
index b68912151..63f02b599 100644
--- a/packages/cli/src/report-bundle.test.ts
+++ b/packages/cli/src/report-bundle.test.ts
@@ -13,6 +13,7 @@ import { SERVER_CRASH_LOG } from '@inkeep/open-knowledge-core';
import { afterEach, describe, expect, test } from 'vitest';
import { collectReportBundle as collectReportBundleFromIndex } from './index.ts';
import { collectReportBundle } from './report-bundle.ts';
+import type { LanguageMetadata } from './report-language.ts';
const tmpDirs: string[] = [];
@@ -721,6 +722,98 @@ describe('collectReportBundle — desktop metadata seam', () => {
});
});
+describe('collectReportBundle — interface-language seam', () => {
+ const LANGUAGE = {
+ preference: 'system',
+ locale: 'es',
+ source: 'system',
+ systemLanguages: ['es-ES', 'en-US'],
+ } as const satisfies LanguageMetadata;
+
+ test('injected language lands in the standard sysinfo and manifest', async () => {
+ const projectDir = makeStandardProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectReportBundle({
+ level: 'standard',
+ projectDir,
+ redact: true,
+ outputPath,
+ readLanguage: () => LANGUAGE,
+ });
+
+ expect(JSON.parse(readZipEntry(zipPath, 'sysinfo.json')).language).toEqual(LANGUAGE);
+ expect(JSON.parse(readZipEntry(zipPath, 'MANIFEST.json')).sysinfo.language).toEqual(LANGUAGE);
+ });
+
+ test('injected language lands in the full runtime block and manifest host', async () => {
+ const projectDir = makeFullProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectReportBundle({
+ level: 'full',
+ projectDir,
+ redact: false,
+ outputPath,
+ readLanguage: () => LANGUAGE,
+ });
+
+ expect(JSON.parse(readZipEntry(zipPath, 'state/runtime.json')).host.language).toEqual(LANGUAGE);
+ expect(JSON.parse(readZipEntry(zipPath, 'manifest.json')).host.language).toEqual(LANGUAGE);
+ });
+
+ // The preference is the field a triager reads to tell a deliberate choice
+ // from an inherited one, so it has to survive the round trip unresolved —
+ // a bundle recording `'es'` where the user chose `'system'` reads as a
+ // decision they never made.
+ test('an explicit choice is recorded unresolved beside what it resolved to', async () => {
+ const projectDir = makeStandardProjectDir();
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectReportBundle({
+ level: 'standard',
+ projectDir,
+ redact: true,
+ outputPath,
+ readLanguage: () => ({
+ preference: 'ar',
+ locale: 'ar',
+ source: 'explicit',
+ systemLanguages: ['en-US'],
+ }),
+ });
+
+ const { language } = JSON.parse(readZipEntry(zipPath, 'sysinfo.json'));
+ expect(language.preference).toBe('ar');
+ expect(language.source).toBe('explicit');
+ });
+
+ // Every bundle carries the key, so an absent language is legible as "this
+ // build could not tell" rather than as a bundle predating the field.
+ test('the default seam still records a language block at both levels', async () => {
+ const standardOut = join(makeTmpDir(), 'standard.zip');
+ const fullOut = join(makeTmpDir(), 'full.zip');
+
+ const standard = await collectReportBundle({
+ level: 'standard',
+ projectDir: makeStandardProjectDir(),
+ redact: true,
+ outputPath: standardOut,
+ });
+ const full = await collectReportBundle({
+ level: 'full',
+ projectDir: makeFullProjectDir(),
+ redact: false,
+ outputPath: fullOut,
+ });
+
+ const standardLanguage = JSON.parse(readZipEntry(standard.zipPath, 'sysinfo.json')).language;
+ expect(typeof standardLanguage.locale).toBe('string');
+ expect(typeof standardLanguage.preference).toBe('string');
+ expect(JSON.parse(readZipEntry(full.zipPath, 'manifest.json')).host).toHaveProperty('language');
+ });
+});
+
describe('collectReportBundle — opted-in extras that cannot be staged', () => {
function makeRecordingLogger() {
const warnings: Array<{ payload: Record<string, unknown>; message: string }> = [];
diff --git a/packages/cli/src/report-bundle.ts b/packages/cli/src/report-bundle.ts
index d0b31f667..208273766 100644
--- a/packages/cli/src/report-bundle.ts
+++ b/packages/cli/src/report-bundle.ts
@@ -27,6 +27,7 @@ import {
defaultReadDesktopEnv,
writeBundle,
} from './diagnose/bundle.ts';
+import { defaultReadLanguage, type LanguageMetadata } from './report-language.ts';
import { isObject } from './utils/is-object.ts';
// The level + summary types live in core so the desktop bridge contract's
@@ -71,6 +72,14 @@ export interface CollectReportBundleOptions {
* Electron host" and is recorded as such at both levels.
*/
readDesktopEnv?: () => DesktopMetadata | null;
+ /**
+ * Interface-language source for the bundle's language block, recorded at both
+ * levels. Defaults to the POSIX-environment reader, which is right for `ok
+ * bug-report` from a shell; the desktop app injects its own, because a macOS
+ * GUI process has no `LANG` to resolve against and would otherwise report the
+ * fallback for every report filed from the app.
+ */
+ readLanguage?: () => LanguageMetadata;
}
export interface ReportBundleResult {
@@ -111,6 +120,7 @@ async function collectFullBundle(
opts: CollectReportBundleOptions,
projectDir: string,
readDesktopEnv: () => DesktopMetadata | null,
+ readLanguage: () => LanguageMetadata,
): Promise<ReportBundleResult> {
const projectSlug = resolveProjectSlug(projectDir, opts.logger);
const collected = await collectBundle({
@@ -130,7 +140,7 @@ async function collectFullBundle(
// app bundle, and it is the only record of why a post-exit install failed.
...collectShipItLogFiles(opts.cachesDir ?? join(homedir(), 'Library', 'Caches')),
],
- deps: { readDesktopEnv, logger: opts.logger },
+ deps: { readDesktopEnv, readLanguage, logger: opts.logger },
});
try {
mkdirSync(dirname(opts.outputPath), { recursive: true });
@@ -178,8 +188,9 @@ export async function collectReportBundle(
): Promise<ReportBundleResult> {
const { projectDir } = opts;
const readDesktopEnv = opts.readDesktopEnv ?? defaultReadDesktopEnv;
+ const readLanguage = opts.readLanguage ?? defaultReadLanguage;
if (opts.level === 'full' && projectDir !== undefined) {
- return collectFullBundle(opts, projectDir, readDesktopEnv);
+ return collectFullBundle(opts, projectDir, readDesktopEnv, readLanguage);
}
const { zipPath, summary } = await collectStandardBundle({
projectDir,
@@ -191,6 +202,7 @@ export async function collectReportBundle(
note: opts.note,
extraFiles: opts.extraFiles,
desktop: readDesktopEnv(),
+ language: readLanguage(),
});
return {
zipPath,
diff --git a/packages/cli/src/report-language.test.ts b/packages/cli/src/report-language.test.ts
new file mode 100644
index 000000000..a662383a1
--- /dev/null
+++ b/packages/cli/src/report-language.test.ts
@@ -0,0 +1,106 @@
+/**
+ * Tests for the CLI's default interface-language reader. Real disk fixtures
+ * (no fs mocks) with an injected home and environment, so nothing here touches
+ * the developer's own `~/.ok/global.yml` or `LANG`.
+ */
+
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, resolve } from 'node:path';
+import { resolveConfigPath } from '@inkeep/open-knowledge-core/server';
+import { afterEach, describe, expect, test } from 'vitest';
+import { defaultReadLanguage } from './report-language.ts';
+
+const tmpDirs: string[] = [];
+
+function makeHome(configBody?: string): string {
+ const home = mkdtempSync(resolve(tmpdir(), 'ok-report-language-'));
+ tmpDirs.push(home);
+ if (configBody !== undefined) {
+ const absPath = resolveConfigPath('user', home, home);
+ mkdirSync(dirname(absPath), { recursive: true });
+ writeFileSync(absPath, configBody);
+ }
+ return home;
+}
+
+afterEach(() => {
+ for (const d of tmpDirs) {
+ if (existsSync(d)) rmSync(d, { recursive: true, force: true });
+ }
+ tmpDirs.length = 0;
+});
+
+describe('defaultReadLanguage', () => {
+ test('reads an explicit choice unresolved, beside what it resolved to', () => {
+ const home = makeHome('appearance:\n language: es\n');
+
+ const language = defaultReadLanguage({ home, env: { LANG: 'en_US.UTF-8' } });
+
+ expect(language.preference).toBe('es');
+ expect(language.locale).toBe('es');
+ expect(language.source).toBe('explicit');
+ });
+
+ // The distinction the whole block exists for: 'system' resolving to English
+ // and English being chosen are the same `locale` and opposite diagnoses.
+ test("an unset preference reads as 'system' and resolves off the OS list", () => {
+ const home = makeHome();
+
+ const language = defaultReadLanguage({ home, env: { LANG: 'fr_FR.UTF-8' } });
+
+ expect(language.preference).toBe('system');
+ expect(language.locale).toBe('fr');
+ expect(language.source).toBe('system');
+ expect(language.systemLanguages).toEqual(['fr-FR']);
+ });
+
+ test('records the OS list that the system tier matched against', () => {
+ const home = makeHome();
+
+ const language = defaultReadLanguage({
+ home,
+ env: { LANG: 'en_US.UTF-8', LANGUAGE: 'pt_BR:es_ES' },
+ });
+
+ expect(language.systemLanguages).toEqual(['pt-BR', 'es-ES', 'en-US']);
+ });
+
+ test('an OK_LANG override is reported as the tier that decided', () => {
+ const home = makeHome('appearance:\n language: es\n');
+
+ const language = defaultReadLanguage({ home, env: { OK_LANG: 'fr', LANG: 'en_US.UTF-8' } });
+
+ expect(language.locale).toBe('fr');
+ expect(language.source).toBe('override');
+ // The stored choice is still what the user selected — the override says
+ // why the app is not showing it, and erasing it here would hide that.
+ expect(language.preference).toBe('es');
+ });
+
+ test('no locale signal at all lands on the fallback rather than throwing', () => {
+ const home = makeHome();
+
+ const language = defaultReadLanguage({ home, env: {} });
+
+ expect(language.source).toBe('fallback');
+ expect(language.locale).toBe('en');
+ });
+
+ // A config that no longer parses may be the very thing being reported, so the
+ // capture must still produce a bundle.
+ test('a corrupt user config degrades to system instead of failing the capture', () => {
+ const home = makeHome('appearance: [this is not\n valid: yaml\n');
+
+ const language = defaultReadLanguage({ home, env: { LANG: 'en_US.UTF-8' } });
+
+ expect(language.preference).toBe('system');
+ expect(language.locale).toBe('en');
+ });
+
+ test('a language the schema does not know degrades rather than rejecting the read', () => {
+ const home = makeHome('appearance:\n language: kl\n');
+
+ expect(() => defaultReadLanguage({ home, env: { LANG: 'en_US.UTF-8' } })).not.toThrow();
+ });
+});
diff --git a/packages/cli/src/report-language.ts b/packages/cli/src/report-language.ts
new file mode 100644
index 000000000..cf1cb05ce
--- /dev/null
+++ b/packages/cli/src/report-language.ts
@@ -0,0 +1,105 @@
+/**
+ * The interface language a bug report was filed in, recorded at both bundle
+ * levels so a triager can tell which language the reporter was actually
+ * reading.
+ *
+ * Three fields rather than one, because the obvious single value answers none
+ * of the questions triage asks. `'system'` is the default and the most common
+ * stored value, so a bundle carrying only the preference usually says nothing
+ * at all; a bundle carrying only the resolved locale cannot tell a language the
+ * user chose from one the OS handed them, which is the difference between "the
+ * picker is broken" and "the resolver guessed". `source` names the tier that
+ * decided, and `systemLanguages` is that tier's input — together they turn "the
+ * app is in the wrong language" from a report into a diagnosis.
+ *
+ * Chrome only. The reporter's documents, titles, and frontmatter are in
+ * whatever language they wrote them in, and nothing here describes those.
+ *
+ * Supplied through an injected seam for the same reason `readDesktopEnv` is:
+ * the default below reads POSIX environment variables, which a macOS GUI app
+ * does not have — an Electron host resolves against
+ * `app.getPreferredSystemLanguages()` and injects the answer, so a desktop
+ * bundle records the language on the reporter's screen rather than one derived
+ * from an environment the app never consulted.
+ */
+
+import { homedir } from 'node:os';
+import {
+ AUTO_DETECTABLE_LOCALES,
+ type LanguagePreference,
+ type LocaleSource,
+ resolveLocale,
+ SUPPORTED_LOCALES,
+ type SupportedLocale,
+} from '@inkeep/open-knowledge-core';
+import {
+ type LocaleEnvironment,
+ readConfigSafely,
+ readNodeLocaleSignal,
+ resolveConfigPath,
+} from '@inkeep/open-knowledge-core/server';
+
+export interface LanguageMetadata {
+ /** `appearance.language` as stored — the setting as selected, `'system'` when unset. */
+ preference: LanguagePreference;
+ /** What that preference resolves to right now. */
+ locale: SupportedLocale;
+ /** Which resolution tier decided: an `OK_LANG` override, the stored choice, the OS list, or the fallback. */
+ source: LocaleSource;
+ /** The OS preferred-language list the `'system'` tier matched against, most-preferred first. */
+ systemLanguages: readonly string[];
+}
+
+/**
+ * Read `appearance.language` out of the user-scope config without throwing and
+ * without sidelining the file.
+ *
+ * Fail-open on the same reasoning the sibling `resolveContentDir` uses: a
+ * config that no longer parses may be the very thing being reported, and a
+ * capture that refuses to run because of it takes away the evidence.
+ *
+ * The cost is that an unreadable file yields `'system'`, which is also the
+ * unset default, so a corrupt user config reads at triage exactly like a
+ * deliberate System choice. Nothing else in the bundle distinguishes them:
+ * the collector stages the PROJECT `.ok/config.yml`, never this user-scope
+ * file, and this reader is not on a logger. The desktop path does better —
+ * it passes a real `warn` that lands in the staged desktop log — so the
+ * ambiguity is confined to a shell-run capture over a config that no longer
+ * parses. Surfacing it here would mean widening `LanguageMetadata` for that
+ * narrow case; `source` plus `systemLanguages` already carry the resolution.
+ */
+function readStoredPreference(home: string): LanguagePreference {
+ const absPath = resolveConfigPath('user', home, home);
+ const result = readConfigSafely({ absPath, sideline: false, warn: () => {} });
+ return result.value.appearance?.language ?? 'system';
+}
+
+/**
+ * The CLI's own answer: the stored preference resolved against this process's
+ * POSIX locale environment (`LC_ALL` / `LC_MESSAGES` / `LANG` / `LANGUAGE`) and
+ * the `OK_LANG` override.
+ *
+ * Faithful for `ok bug-report` from a shell, which is the surface that has
+ * those variables. The desktop app injects its own reader instead.
+ */
+export function defaultReadLanguage({
+ home = homedir(),
+ env = process.env,
+}: {
+ home?: string;
+ env?: LocaleEnvironment;
+} = {}): LanguageMetadata {
+ const preference = readStoredPreference(home);
+ const { override, preferenceList } = readNodeLocaleSignal(env);
+ const { locale, source } = resolveLocale({
+ override,
+ storedPreference: preference,
+ // The whole enumerated set: a preference naming a locale that is not yet
+ // promoted to the picker still has to resolve here, or the bundle would
+ // report a language the app is not in.
+ supportedLocales: SUPPORTED_LOCALES,
+ preferenceList,
+ autoDetectableLocales: AUTO_DETECTABLE_LOCALES,
+ });
+ return { preference, locale, source, systemLanguages: preferenceList };
+}
diff --git a/packages/desktop/src/main/boot-locale.ts b/packages/desktop/src/main/boot-locale.ts
index 0d14e40ea..16b51f4ea 100644
--- a/packages/desktop/src/main/boot-locale.ts
+++ b/packages/desktop/src/main/boot-locale.ts
@@ -17,10 +17,12 @@
* a function so the whole chain is unit-testable without an Electron runtime.
*/
+import type { LanguageMetadata } from '@inkeep/open-knowledge';
import {
AUTO_DETECTABLE_LOCALES,
asBcp47Tag,
type LanguagePreference,
+ type LocaleResolution,
resolveLocale,
SUPPORTED_LOCALES,
type SupportedLocale,
@@ -114,8 +116,13 @@ interface DesktopLocaleInputs {
* The pure half — the same four-tier policy every runtime shares, with
* Electron's preferred-language list as the platform signal. Split out so the
* IPC path can re-resolve a pushed preference without re-reading disk.
+ *
+ * Returns the whole resolution rather than the locale alone. The applied
+ * callers below take `.locale` and ignore the rest; the reporting caller needs
+ * the tier that decided. Handing back both is what keeps the reported language
+ * and the rendered one the same derivation rather than two copies of it.
*/
-export function resolveDesktopLocaleFrom(inputs: DesktopLocaleInputs): SupportedLocale {
+function resolveDesktopLocaleResolution(inputs: DesktopLocaleInputs): LocaleResolution {
return resolveLocale({
override: (inputs.override === undefined ? null : asBcp47Tag(inputs.override)) ?? undefined,
storedPreference: inputs.storedPreference,
@@ -124,5 +131,53 @@ export function resolveDesktopLocaleFrom(inputs: DesktopLocaleInputs): Supported
// The OS list is a guess, and the menu bar sits above the same unfinished
// chrome layout the renderer does, so it declines the same guesses.
autoDetectableLocales: AUTO_DETECTABLE_LOCALES,
- }).locale;
+ });
+}
+
+export function resolveDesktopLocaleFrom(inputs: DesktopLocaleInputs): SupportedLocale {
+ return resolveDesktopLocaleResolution(inputs).locale;
+}
+
+/**
+ * The same resolution the menu bar runs, reported rather than applied: the
+ * preference, what it resolved to, which tier decided, and the platform list
+ * that tier read.
+ *
+ * Exists for the bug-report bundle, which needs the whole derivation and not
+ * just its answer — `'system'` resolving to English is either correct or the
+ * bug, and only the tier plus its input separates the two.
+ *
+ * `pushedPreference` is the value the renderer last pushed, or `null` to read
+ * disk. It is preferred when present for the reason the menu prefers it: the
+ * renderer pushes on change but the config write is debounced, so between the
+ * two the file still holds the language the user just left. A report filed in
+ * that window would otherwise name the previous language — precisely the window
+ * where someone reports that changing the language did not take.
+ */
+export function describeDesktopLanguage(
+ deps: DesktopLocaleDeps & { readonly pushedPreference: LanguagePreference | null },
+): LanguageMetadata {
+ const storedPreference =
+ deps.pushedPreference ??
+ readStoredLanguagePreference(deps.homedir, (message) =>
+ getLogger('boot-locale').warn(
+ { message },
+ 'user config unreadable; bug report records the system fallback',
+ ),
+ );
+ const preferredSystemLanguages = deps.preferredSystemLanguages();
+ // Through the shared resolver, not a second copy of its arguments: the doc
+ // above promises this is the resolution the menu bar runs, and going through
+ // the same function is what keeps that true when a tier is added or changed.
+ const { locale, source } = resolveDesktopLocaleResolution({
+ storedPreference,
+ override: deps.env[LOCALE_OVERRIDE_ENV_VAR],
+ preferredSystemLanguages,
+ });
+ return {
+ preference: storedPreference,
+ locale,
+ source,
+ systemLanguages: preferredSystemLanguages,
+ };
}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 161d92a6f..3417324d9 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -174,6 +174,7 @@ import {
} from './auto-updater.ts';
import { applyBackgroundThrottle } from './background-throttle.ts';
import {
+ describeDesktopLanguage,
readStoredLanguagePreference,
resolveDesktopLocale,
resolveDesktopLocaleForPushed,
@@ -5434,6 +5435,15 @@ function registerIpcHandlers() {
packaged: app.isPackaged,
channel: channelFromVersion(app.getVersion()),
},
+ // The language on screen right now, not the one the debounced config
+ // write has reached disk with — see `describeDesktopLanguage`.
+ readLanguage: () =>
+ describeDesktopLanguage({
+ homedir: osHomedir(),
+ preferredSystemLanguages: () => app.getPreferredSystemLanguages(),
+ env: process.env,
+ pushedPreference: pushedLanguagePreference,
+ }),
newestMinidumpForReport: () =>
crashDetection?.newestMinidumpForReport() ?? {
path: null,
diff --git a/packages/desktop/src/main/ipc/bug-report.test.ts b/packages/desktop/src/main/ipc/bug-report.test.ts
index eeff94ab3..756337674 100644
--- a/packages/desktop/src/main/ipc/bug-report.test.ts
+++ b/packages/desktop/src/main/ipc/bug-report.test.ts
@@ -260,6 +260,45 @@ describe('handleBugReportCreate — project bundle', () => {
});
});
+ /**
+ * The seam this feature exists for. A macOS app launched from Finder has no
+ * `LANG`, so if the collector ever fell through to its POSIX default the
+ * bundle would report the fallback locale for every in-app report no matter
+ * what the user was reading. The env below is set to a DIFFERENT language
+ * than the injected reader returns, so a fall-through cannot pass this.
+ */
+ test('the injected desktop language reaches the bundle, not the POSIX default', async () => {
+ const projectDir = makeProjectDir();
+ const desktopLanguage = {
+ preference: 'zh-Hant',
+ locale: 'zh-Hant',
+ source: 'explicit',
+ systemLanguages: ['zh-TW', 'en-US'],
+ } as const;
+ const deps = makeDeps({ projectDir, readLanguage: () => desktopLanguage });
+ const priorLang = process.env.LANG;
+ process.env.LANG = 'fr_FR.UTF-8';
+
+ try {
+ const full = await handleBugReportCreate(deps, { kind: 'create', level: 'full' });
+ if (!full.ok) throw new Error(`expected ok, got: ${full.error}`);
+ const runtime = JSON.parse(readZipEntry(full.zipPath, 'state/runtime.json'));
+ expect(runtime.host.language).toEqual(desktopLanguage);
+
+ const standard = await handleBugReportCreate(
+ makeDeps({ projectDir, readLanguage: () => desktopLanguage }),
+ { kind: 'create', level: 'standard' },
+ );
+ if (!standard.ok) throw new Error(`expected ok, got: ${standard.error}`);
+ expect(JSON.parse(readZipEntry(standard.zipPath, 'sysinfo.json')).language).toEqual(
+ desktopLanguage,
+ );
+ } finally {
+ if (priorLang === undefined) delete process.env.LANG;
+ else process.env.LANG = priorLang;
+ }
+ });
+
test('standard level records the desktop host metadata in sysinfo and the manifest', async () => {
const projectDir = makeProjectDir();
const deps = makeDeps({ projectDir });
diff --git a/packages/desktop/src/main/ipc/bug-report.ts b/packages/desktop/src/main/ipc/bug-report.ts
index 91a627ea2..0c4d3b24b 100644
--- a/packages/desktop/src/main/ipc/bug-report.ts
+++ b/packages/desktop/src/main/ipc/bug-report.ts
@@ -24,6 +24,7 @@ import {
type BundleLogger,
collectReportBundle,
defaultBugReportZipPath,
+ type LanguageMetadata,
redactContent,
} from '@inkeep/open-knowledge';
import {
@@ -118,6 +119,20 @@ export interface BugReportCreateDeps {
/** Sender window's project root; `null` (Navigator, no project) degrades to a system-wide bundle. */
projectDir: string | null;
desktopMeta: BugReportDesktopMeta;
+ /**
+ * The interface language this report is being filed in, handed to the bundle
+ * collector through its `readLanguage` seam.
+ *
+ * Injected rather than left to the collector's default for the same reason
+ * `desktopMeta` is: that default resolves `'system'` against `LANG` /
+ * `LC_ALL`, and a macOS app launched from Finder has neither — every report
+ * from the packaged app would claim the fallback locale no matter what the
+ * user was looking at. Main resolves against the platform language list
+ * instead, and against the preference the renderer last pushed, so the
+ * recorded language is the one on screen rather than the one on disk (the
+ * config write is debounced and lands later).
+ */
+ readLanguage?: () => LanguageMetadata;
/** Zip destination override; defaults to `~/.ok/bug-reports/<timestamp>-bugreport.zip`. */
outputPath?: string;
/** User-level logs directory override (standard-level test seam). */
@@ -406,6 +421,7 @@ export async function handleBugReportCreate(
packaged: deps.desktopMeta.packaged,
channel: deps.desktopMeta.channel,
}),
+ readLanguage: deps.readLanguage,
});
const { size: zipSizeBytes } = await stat(zipPath);
// Persist the durable `generated` record next to the zip. A failure here
diff --git a/packages/desktop/tests/main/boot-locale.test.ts b/packages/desktop/tests/main/boot-locale.test.ts
index b81855a08..ecdf4a36f 100644
--- a/packages/desktop/tests/main/boot-locale.test.ts
+++ b/packages/desktop/tests/main/boot-locale.test.ts
@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
+ describeDesktopLanguage,
readStoredLanguagePreference,
resolveDesktopLocale,
resolveDesktopLocaleForPushed,
@@ -268,3 +269,86 @@ describe('resolveDesktopLocaleForPushed', () => {
).toBe('fr');
});
});
+
+describe('describeDesktopLanguage', () => {
+ const OS_LIST = ['en-US'];
+ const deps = {
+ preferredSystemLanguages: () => OS_LIST,
+ env: {} as NodeJS.ProcessEnv,
+ };
+
+ test('reports the stored choice unresolved, beside what it resolved to', () => {
+ writeUserConfig('appearance:\n language: zh-Hant\n');
+
+ expect(describeDesktopLanguage({ homedir: home, pushedPreference: null, ...deps })).toEqual({
+ preference: 'zh-Hant',
+ locale: 'zh-Hant',
+ source: 'explicit',
+ systemLanguages: OS_LIST,
+ });
+ });
+
+ /**
+ * `'system'` is the default and the most common stored value, so a bundle
+ * carrying only the preference would say nothing about most reports. The
+ * resolved locale plus the tier that decided is what makes it diagnosable.
+ */
+ test('a system preference carries the resolved locale and the list it matched', () => {
+ const language = describeDesktopLanguage({
+ homedir: home,
+ pushedPreference: null,
+ preferredSystemLanguages: () => ['es-ES', 'en-US'],
+ env: {} as NodeJS.ProcessEnv,
+ });
+
+ expect(language.preference).toBe('system');
+ expect(language.locale).toBe('es');
+ expect(language.source).toBe('system');
+ expect(language.systemLanguages).toEqual(['es-ES', 'en-US']);
+ });
+
+ /**
+ * The same debounced-persistence window `resolveDesktopLocaleForPushed`
+ * exists for. A report filed inside it is exactly the report claiming that
+ * changing the language did not take — recording the stale on-disk value
+ * would corroborate a bug that is not there and hide the one that is.
+ */
+ test('prefers the pushed preference over the value still on disk', () => {
+ writeUserConfig('appearance:\n language: zh-Hans\n');
+
+ const language = describeDesktopLanguage({
+ homedir: home,
+ pushedPreference: 'fr',
+ ...deps,
+ });
+
+ expect(language.preference).toBe('fr');
+ expect(language.locale).toBe('fr');
+ });
+
+ test('an override is named as the tier that decided, keeping the stored choice visible', () => {
+ writeUserConfig('appearance:\n language: es\n');
+
+ const language = describeDesktopLanguage({
+ homedir: home,
+ pushedPreference: null,
+ preferredSystemLanguages: () => OS_LIST,
+ env: { OK_LANG: 'fr' } as NodeJS.ProcessEnv,
+ });
+
+ expect(language.locale).toBe('fr');
+ expect(language.source).toBe('override');
+ expect(language.preference).toBe('es');
+ });
+
+ test('a corrupt user config degrades to system rather than throwing', () => {
+ writeUserConfig('appearance: [not\n valid: yaml\n');
+
+ expect(() =>
+ describeDesktopLanguage({ homedir: home, pushedPreference: null, ...deps }),
+ ).not.toThrow();
+ expect(
+ describeDesktopLanguage({ homedir: home, pushedPreference: null, ...deps }).preference,
+ ).toBe('system');
+ });
+});