Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(desktop): send diagnostics to a configurable receiver
claude-opus-5-5-medium5f945e0f6a3d
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 4499d001..22200ffe 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -202,8 +202,19 @@ Gateway and runs Agents. The daemon exits with the app.`control.key`, `credential.json`, `launch.html`, `*.env`, `*.input.json`,keys, cookies, databases) never go in, every saved voice key is replacedwherever a log printed it, and every text passes through `redact` plus a- secret-key JSON filter. It imports no Electron API, so it is- tested with Windows paths on any platform.+ secret-key JSON filter, and the person's home folder becomes `~`. It+ imports no Electron API, so it is tested with Windows paths on any+ platform.+- `src/main/diagnostics-upload.ts`: "Send Diagnostics" on the same three+ surfaces, shown only while a receiver is set up (`diagnosticsUploadUrl` in+ `config.json`, else `HOSTED_DIAGNOSTICS_UPLOAD_URL`, a placeholder that is+ unset until the hosted receiver runs). `DiagnosticsSender` builds the zip+ into `<userData>/diagnostics-outbox`, waits for consent showing every file,+ the size and the host, uploads it with the+ [`linger.diagnostics-upload/v1`](../../docs/diagnostics-upload.md)+ protocol and shows the receiver's report id; a retryable failure keeps the+ zip for Try Again. The setup page draws the flow itself; the tray and the+ start failure page use native dialogs (`diagnostics-dialogs.ts`).- `src/main/window-manager.ts`: one `BaseWindow` with two views, the title bar(`app://shell/titlebar`) and the SPA. macOS keeps native traffic lights,Windows uses `titleBarOverlay`, Linux draws its own controls. Closing hidesdiff --git a/apps/desktop/src/main/config.ts b/apps/desktop/src/main/config.tsindex 7210c56f..c1084f37 100644--- a/apps/desktop/src/main/config.ts+++ b/apps/desktop/src/main/config.ts@@ -4,6 +4,8 @@ import path from "node:path";import { z } from "zod";+import { isUploadUrl } from "./diagnostics-upload.js";+const workspaceGrant = z.object({grantId: z.string().min(1),path: z.string().min(1),@@ -41,6 +43,14 @@ const desktopConfig = z.object({// releases (update-manifest.ts); GitHub's simplexai-labs/linger when unset.// A value that is not a URL is dropped rather than resetting the file.updateFeedUrl: z.string().url().optional().catch(undefined),+ // Where Send Diagnostics uploads to (docs/diagnostics-upload.md); set by+ // hand for a self-hosted receiver. An invalid value is dropped, not the+ // whole file.+ diagnosticsUploadUrl: z+ .string()+ .refine(isUploadUrl)+ .optional()+ .catch(undefined),window: z.object({x: z.number().int(),diff --git a/apps/desktop/src/main/diagnostics-dialogs.ts b/apps/desktop/src/main/diagnostics-dialogs.tsnew file mode 100644index 00000000..5b0282a3--- /dev/null+++ b/apps/desktop/src/main/diagnostics-dialogs.ts@@ -0,0 +1,61 @@+import {+ clipboard,+ dialog,+ type BaseWindow,+ type MessageBoxOptions,+} from "electron";++import { consentText, type DiagnosticsPrompts } from "./diagnostics-upload.js";++// Send Diagnostics' native dialogs for the tray and the start failure page.+export const diagnosticsDialogs = (+ window: () => BaseWindow | undefined,+): DiagnosticsPrompts => {+ const show = async (options: MessageBoxOptions): Promise<number> => {+ const parent = window();+ const { response } = await (parent+ ? dialog.showMessageBox(parent, options)+ : dialog.showMessageBox(options));+ return response;+ };+ return {+ consent: async (state) =>+ (await show({+ type: "question",+ ...consentText(state),+ buttons: ["Send", "Cancel"],+ defaultId: 0,+ cancelId: 1,+ })) === 0,+ sent: async (state) => {+ const copy = await show({+ type: "info",+ message: "Diagnostics sent",+ detail: `Report ID: ${state.reportId}\nGive this ID to Linger support so they can find your report.`,+ buttons: ["Copy Report ID", "Done"],+ defaultId: 0,+ cancelId: 1,+ });+ if (copy === 0) clipboard.writeText(state.reportId);+ },+ failed: async (state) =>+ (await show({+ type: "warning",+ message: "Couldn't send diagnostics",+ detail: state.retry+ ? state.error+ : `${state.error}\nYou can still use Save Diagnostics and send the file by hand.`,+ buttons: state.retry ? ["Try Again", "Close"] : ["Close"],+ defaultId: 0,+ cancelId: state.retry ? 1 : 0,+ })) === 0 && state.retry,+ busy: async () => {+ await show({+ type: "info",+ message: "Diagnostics are already being sent",+ detail: "Finish or cancel that report in the Linger setup window.",+ buttons: ["OK"],+ });+ },+ };+};diff --git a/apps/desktop/src/main/diagnostics-upload.test.ts b/apps/desktop/src/main/diagnostics-upload.test.tsnew file mode 100644index 00000000..139f0d77--- /dev/null+++ b/apps/desktop/src/main/diagnostics-upload.test.ts@@ -0,0 +1,477 @@+import { createHash } from "node:crypto";+import { existsSync, writeFileSync } from "node:fs";+import http from "node:http";+import type { AddressInfo } from "node:net";+import path from "node:path";++import { afterEach, describe, expect, it, vi } from "vitest";++import type { SetupDiagnosticsSend } from "../shared/setup.js";+import { ConfigStore } from "./config.js";+import {+ DIAGNOSTICS_UPLOAD_SCHEMA,+ DiagnosticsSender,+ DiagnosticsUploadError,+ MAX_DIAGNOSTICS_UPLOAD_BYTES,+ consentText,+ diagnosticsUploadUrl,+ isUploadUrl,+ sendWithPrompts,+ uploadDiagnostics,+ type DiagnosticsPrompts,+ type PreparedDiagnostics,+} from "./diagnostics-upload.js";+import { tempDirectory } from "./test-support.js";++describe("isUploadUrl", () => {+ it.each([+ "https://diagnostics.example.com/v1/reports",+ "http://127.0.0.1:8080/v1/reports",+ "http://localhost:8080/v1/reports",+ "http://[::1]:8080/v1/reports",+ ])("accepts %s", (url) => expect(isUploadUrl(url)).toBe(true));++ it.each([+ "http://diagnostics.example.com/v1/reports",+ "https://user:[email protected]/",+ "ftp://diagnostics.example.com/",+ "not a url",+ ])("refuses %s", (url) => expect(isUploadUrl(url)).toBe(false));+});++describe("diagnosticsUploadUrl in config.json", () => {+ it("keeps a valid receiver and drops an invalid one without the rest", () => {+ const file = path.join(tempDirectory(), "config.json");+ writeFileSync(+ file,+ JSON.stringify({+ computerId: "computer-1",+ diagnosticsUploadUrl: "https://diagnostics.example.com/v1/reports",+ }),+ );+ expect(diagnosticsUploadUrl(new ConfigStore(file).get())).toBe(+ "https://diagnostics.example.com/v1/reports",+ );+ writeFileSync(+ file,+ JSON.stringify({+ computerId: "computer-1",+ diagnosticsUploadUrl: "http://diagnostics.example.com/v1/reports",+ }),+ );+ const config = new ConfigStore(file).get();+ expect(config.computerId).toBe("computer-1");+ expect(config.diagnosticsUploadUrl).toBeUndefined();+ expect(diagnosticsUploadUrl(config)).toBeUndefined();+ });+});++interface Received {+ ticket?: Record<string, unknown>;+ put?: { headers: http.IncomingHttpHeaders; body: Buffer };+}++// A receiver on this computer: POST hands out a ticket for PUT /blob.+const receiver = async (+ answer?: (+ request: http.IncomingMessage,+ response: http.ServerResponse,+ ) => boolean,+) => {+ const received: Received = {};+ const server = http.createServer((request, response) => {+ const chunks: Buffer[] = [];+ request.on("data", (chunk: Buffer) => chunks.push(chunk));+ request.on("end", () => {+ const body = Buffer.concat(chunks);+ if (answer?.(request, response)) return;+ if (request.method === "POST") {+ received.ticket = JSON.parse(body.toString("utf8")) as Record<+ string,+ unknown+ >;+ response.writeHead(201, { "content-type": "application/json" });+ response.end(+ JSON.stringify({+ schema: DIAGNOSTICS_UPLOAD_SCHEMA,+ reportId: "LD-7K3Q9XPM",+ upload: {+ method: "PUT",+ url: `http://127.0.0.1:${port()}/blob?signature=abc`,+ headers: {+ "content-type": "application/zip",+ "Content-Length": "1",+ },+ },+ }),+ );+ return;+ }+ received.put = { headers: request.headers, body };+ response.writeHead(200).end();+ });+ });+ await new Promise<void>((resolve) =>+ server.listen(0, "127.0.0.1", () => resolve()),+ );+ const port = () => (server.address() as AddressInfo).port;+ servers.push(server);+ return { url: `http://127.0.0.1:${port()}/v1/reports`, received };+};++const servers: http.Server[] = [];+afterEach(async () => {+ await Promise.all(+ servers+ .splice(0)+ .map((server) => new Promise((resolve) => server.close(resolve))),+ );+});++const zipFile = (bytes = 200_000): { file: string; data: Buffer } => {+ const file = path.join(tempDirectory(), "linger-diagnostics.zip");+ const data = Buffer.alloc(bytes, 7);+ writeFileSync(file, data);+ return { file, data };+};++const client = { version: "1.2.3", platform: "linux-x64" };++describe("uploadDiagnostics", () => {+ it("asks for a ticket, then PUTs the zip where it says", async () => {+ const { url, received } = await receiver();+ const { file, data } = zipFile();+ const progress: number[] = [];+ const reportId = await uploadDiagnostics({+ endpoint: url,+ file,+ bytes: data.length,+ client,+ onProgress: (sent) => progress.push(sent),+ });+ expect(reportId).toBe("LD-7K3Q9XPM");+ expect(received.ticket).toEqual({+ schema: DIAGNOSTICS_UPLOAD_SCHEMA,+ size: data.length,+ sha256: createHash("sha256").update(data).digest("hex"),+ client: { name: "linger-desktop", ...client },+ });+ expect(received.put!.body.equals(data)).toBe(true);+ expect(received.put!.headers["content-type"]).toBe("application/zip");+ // The receiver cannot set the length the client sends.+ expect(received.put!.headers["content-length"]).toBe(String(data.length));+ expect(progress.at(-1)).toBe(data.length);+ });++ it("refuses a bundle over the limit without a request", async () => {+ const { url, received } = await receiver();+ const { file } = zipFile(10);+ await expect(+ uploadDiagnostics({+ endpoint: url,+ file,+ bytes: MAX_DIAGNOSTICS_UPLOAD_BYTES + 1,+ client,+ }),+ ).rejects.toMatchObject({ retryable: false });+ expect(received.ticket).toBeUndefined();+ });++ it("says when to try again after a rate limit", async () => {+ const { url } = await receiver((request, response) => {+ response+ .writeHead(429, {+ "content-type": "application/json",+ "retry-after": "600",+ })+ .end(+ JSON.stringify({+ error: { code: "RATE_LIMITED", message: "Slow down" },+ }),+ );+ return true;+ });+ const { file, data } = zipFile(10);+ const error = await uploadDiagnostics({+ endpoint: url,+ file,+ bytes: data.length,+ client,+ }).catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(DiagnosticsUploadError);+ expect(error).toMatchObject({+ retryable: true,+ message: "Too many reports were sent. Try again in 10 min.",+ });+ });++ it("does not retry a bundle the server finds too large", async () => {+ const { url } = await receiver((request, response) => {+ response.writeHead(413).end();+ return true;+ });+ const { file, data } = zipFile(10);+ await expect(+ uploadDiagnostics({ endpoint: url, file, bytes: data.length, client }),+ ).rejects.toMatchObject({ retryable: false });+ });++ it("refuses a ticket that would upload over plain http", async () => {+ const { url, received } = await receiver((request, response) => {+ if (request.method !== "POST") return false;+ response.writeHead(201, { "content-type": "application/json" }).end(+ JSON.stringify({+ schema: DIAGNOSTICS_UPLOAD_SCHEMA,+ reportId: "LD-1",+ upload: { method: "PUT", url: "http://storage.example.com/x" },+ }),+ );+ return true;+ });+ const { file, data } = zipFile(10);+ await expect(+ uploadDiagnostics({ endpoint: url, file, bytes: data.length, client }),+ ).rejects.toThrow("doesn't understand");+ expect(received.put).toBeUndefined();+ });++ it("reports a refused PUT", async () => {+ const { url } = await receiver((request, response) => {+ if (request.method !== "PUT") return false;+ response.writeHead(403).end();+ return true;+ });+ const { file, data } = zipFile(10);+ await expect(+ uploadDiagnostics({ endpoint: url, file, bytes: data.length, client }),+ ).rejects.toThrow("The upload was refused (HTTP 403)");+ });+});++const bundle = (): PreparedDiagnostics => {+ const { file, data } = zipFile(10);+ return {+ file,+ entries: ["summary.json", "desktop/logs/main.log"],+ bytes: data.length,+ };+};++const sender = (+ upload: (bundle: PreparedDiagnostics) => Promise<string>,+ options: {+ endpoint?: string | undefined;+ prepare?: () => Promise<PreparedDiagnostics>;+ } = {},+) => {+ const states: SetupDiagnosticsSend["phase"][] = [];+ const prepared: PreparedDiagnostics[] = [];+ const instance = new DiagnosticsSender({+ endpoint: () =>+ "endpoint" in options+ ? options.endpoint+ : "https://diagnostics.example.com/v1/reports",+ prepare:+ options.prepare ??+ (async () => {+ const next = bundle();+ prepared.push(next);+ return next;+ }),+ upload: (_endpoint, next, onProgress) => {+ onProgress(next.bytes);+ return upload(next);+ },+ discard: async (file) => writeFileSync(`${file}.discarded`, ""),+ onChange: (state) => states.push(state.phase),+ });+ return { instance, states, prepared };+};++const discarded = (item: PreparedDiagnostics) =>+ existsSync(`${item.file}.discarded`);++describe("DiagnosticsSender", () => {+ it("shows what will be sent and uploads nothing before consent", async () => {+ const upload = vi.fn(async () => "LD-1");+ const { instance, prepared } = sender(upload);+ await instance.start();+ expect(instance.state()).toEqual({+ phase: "confirm",+ host: "diagnostics.example.com",+ files: ["summary.json", "desktop/logs/main.log"],+ bytes: 10,+ });+ expect(upload).not.toHaveBeenCalled();+ await instance.cancel();+ expect(instance.state()).toEqual({ phase: "idle" });+ expect(discarded(prepared[0]!)).toBe(true);+ expect(upload).not.toHaveBeenCalled();+ });++ it("uploads after consent and shows the report id", async () => {+ const { instance, states, prepared } = sender(async () => "LD-7K3Q9XPM");+ await instance.start();+ await instance.confirm();+ expect(instance.state()).toEqual({+ phase: "sent",+ host: "diagnostics.example.com",+ reportId: "LD-7K3Q9XPM",+ });+ expect(states).toEqual([+ "preparing",+ "confirm",+ "sending",+ "sending",+ "sent",+ ]);+ expect(discarded(prepared[0]!)).toBe(true);+ });++ it("tries the same bundle again after a retryable failure", async () => {+ const upload = vi+ .fn<(bundle: PreparedDiagnostics) => Promise<string>>()+ .mockRejectedValueOnce(new DiagnosticsUploadError("offline", true))+ .mockResolvedValueOnce("LD-2");+ const { instance, prepared } = sender(upload);+ await instance.start();+ await instance.confirm();+ expect(instance.state()).toEqual({+ phase: "failed",+ error: "offline",+ retry: true,+ });+ expect(discarded(prepared[0]!)).toBe(false);+ await instance.retry();+ expect(instance.state()).toMatchObject({ phase: "sent", reportId: "LD-2" });+ expect(upload.mock.calls.map(([item]) => item)).toEqual([+ prepared[0],+ prepared[0],+ ]);+ expect(prepared).toHaveLength(1);+ });++ it("drops the bundle when trying again cannot help", async () => {+ const { instance, prepared } = sender(async () => {+ throw new DiagnosticsUploadError("too large", false);+ });+ await instance.start();+ await instance.confirm();+ expect(instance.state()).toEqual({+ phase: "failed",+ error: "too large",+ retry: false,+ });+ expect(discarded(prepared[0]!)).toBe(true);+ await instance.retry();+ expect(instance.state().phase).toBe("failed");+ });++ it("collects again when collecting failed", async () => {+ const prepare = vi+ .fn<() => Promise<PreparedDiagnostics>>()+ .mockRejectedValueOnce(new Error("disk full"))+ .mockImplementationOnce(async () => bundle());+ const { instance } = sender(async () => "LD-3", { prepare });+ await instance.start();+ expect(instance.state()).toEqual({+ phase: "failed",+ error: "Couldn't collect the diagnostics: disk full",+ retry: true,+ });+ await instance.retry();+ expect(instance.state().phase).toBe("confirm");+ });++ it("fails without a receiver", async () => {+ const { instance } = sender(async () => "LD-4", { endpoint: undefined });+ await instance.start();+ expect(instance.state()).toMatchObject({ phase: "failed", retry: false });+ });+});++const prompts = (answers: { consent: boolean; retry?: boolean }) => {+ const asked: string[] = [];+ const value: DiagnosticsPrompts = {+ consent: async () => {+ asked.push("consent");+ return answers.consent;+ },+ sent: async (state) => {+ asked.push(`sent ${state.reportId}`);+ },+ failed: async (state) => {+ asked.push(`failed ${state.error}`);+ return answers.retry ?? false;+ },+ busy: async () => {+ asked.push("busy");+ },+ };+ return { value, asked };+};++describe("sendWithPrompts", () => {+ it("sends nothing when consent is declined", async () => {+ const upload = vi.fn(async () => "LD-1");+ const { instance } = sender(upload);+ const { value, asked } = prompts({ consent: false });+ await sendWithPrompts(instance, value);+ expect(asked).toEqual(["consent"]);+ expect(upload).not.toHaveBeenCalled();+ expect(instance.state().phase).toBe("idle");+ });++ it("offers Try Again, then shows the report id", async () => {+ const upload = vi+ .fn<(bundle: PreparedDiagnostics) => Promise<string>>()+ .mockRejectedValueOnce(new DiagnosticsUploadError("offline", true))+ .mockResolvedValueOnce("LD-5");+ const { instance } = sender(upload);+ const { value, asked } = prompts({ consent: true, retry: true });+ await sendWithPrompts(instance, value);+ expect(asked).toEqual(["consent", "failed offline", "sent LD-5"]);+ expect(instance.state().phase).toBe("idle");+ });++ it("asks about a report left waiting for consent", async () => {+ const upload = vi.fn(async () => "LD-6");+ const { instance } = sender(upload);+ await instance.start();+ const { value, asked } = prompts({ consent: true });+ await sendWithPrompts(instance, value);+ expect(asked).toEqual(["consent", "sent LD-6"]);+ expect(upload).toHaveBeenCalledTimes(1);+ });++ it("says so while another send runs", async () => {+ let finish = (_id: string) => {};+ const { instance } = sender(+ () => new Promise<string>((resolve) => (finish = resolve)),+ );+ await instance.start();+ const sending = instance.confirm();+ const { value, asked } = prompts({ consent: true });+ await sendWithPrompts(instance, value);+ expect(asked).toEqual(["busy"]);+ finish("LD-7");+ await sending;+ });+});++describe("consentText", () => {+ it("names the receiver, the size and the files", () => {+ const text = consentText(+ {+ phase: "confirm",+ host: "diagnostics.example.com",+ files: ["a", "b", "c"],+ bytes: 3 * 1024 * 1024,+ },+ 2,+ );+ expect(text.message).toBe("Send diagnostics to diagnostics.example.com?");+ expect(text.detail).toContain("3 files, 3.0 MB");+ expect(text.detail).toContain(" a\n b\n and 1 more");+ });+});diff --git a/apps/desktop/src/main/diagnostics-upload.ts b/apps/desktop/src/main/diagnostics-upload.tsnew file mode 100644index 00000000..c9f53303--- /dev/null+++ b/apps/desktop/src/main/diagnostics-upload.ts@@ -0,0 +1,448 @@+import { createHash } from "node:crypto";+import { createReadStream } from "node:fs";+import http from "node:http";+import https from "node:https";++import { z } from "zod";++import type { SetupDiagnosticsSend } from "../shared/setup.js";++// Sends the diagnostics zip to a receiver that implements+// docs/diagnostics-upload.md: one POST asks for a report id and a+// one-time upload URL, one PUT sends the zip there.++export const DIAGNOSTICS_UPLOAD_SCHEMA = "linger.diagnostics-upload/v1";++// The hosted receiver. Placeholder: no hosted receiver runs yet, so Send+// Diagnostics shows only when config.json names one in+// diagnosticsUploadUrl. Set this to the receiver's https URL once it is+// live.+export const HOSTED_DIAGNOSTICS_UPLOAD_URL: string | undefined = undefined;++// Receivers may accept less; this keeps a runaway log from leaving at all.+export const MAX_DIAGNOSTICS_UPLOAD_BYTES = 50 * 1024 * 1024;++const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);++// https, or http to this computer for a receiver under development. No+// user name or password in the URL, since it is shown on the consent+// screen and logged.+export const isUploadUrl = (value: string): boolean => {+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ return false;+ }+ if (url.username || url.password) return false;+ return (+ url.protocol === "https:" ||+ (url.protocol === "http:" && LOOPBACK.has(url.hostname))+ );+};++// The receiver this app sends to, or none: then Send Diagnostics is hidden.+export const diagnosticsUploadUrl = (config: {+ readonly diagnosticsUploadUrl?: string | undefined;+}): string | undefined =>+ config.diagnosticsUploadUrl ?? HOSTED_DIAGNOSTICS_UPLOAD_URL;++const uploadTicket = z.object({+ schema: z.literal(DIAGNOSTICS_UPLOAD_SCHEMA),+ reportId: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9-]{3,63}$/),+ upload: z.object({+ method: z.literal("PUT"),+ url: z.string().refine(isUploadUrl, "Upload URL must use https"),+ headers: z.record(z.string(), z.string()).default({}),+ }),+});++const errorEnvelope = z.object({+ error: z.object({ code: z.string(), message: z.string() }),+});++// Set by the client itself; a receiver cannot override them.+const RESERVED_HEADERS = new Set([+ "host",+ "content-length",+ "transfer-encoding",+ "connection",+]);++export class DiagnosticsUploadError extends Error {+ constructor(+ message: string,+ // Whether trying again can help: not for a refused or invalid bundle.+ readonly retryable: boolean,+ ) {+ super(message);+ this.name = "DiagnosticsUploadError";+ }+}++export interface DiagnosticsUploadOptions {+ readonly endpoint: string;+ readonly file: string;+ readonly bytes: number;+ readonly client: {+ readonly version: string;+ readonly platform: string;+ };+ readonly onProgress?: (sent: number) => void;+}++const sha256File = async (file: string): Promise<string> => {+ const hash = createHash("sha256");+ for await (const chunk of createReadStream(file))+ hash.update(chunk as Buffer);+ return hash.digest("hex");+};++const refusal = async (response: Response): Promise<DiagnosticsUploadError> => {+ const body = errorEnvelope.safeParse(+ await response.json().catch(() => undefined),+ );+ const said = body.success ? `: ${body.data.error.message}` : "";+ if (response.status === 413)+ return new DiagnosticsUploadError(+ `The diagnostics are too large for the server${said}`,+ false,+ );+ if (response.status === 429) {+ const after = Number(response.headers.get("retry-after"));+ return new DiagnosticsUploadError(+ Number.isFinite(after) && after > 0+ ? `Too many reports were sent. Try again in ${Math.ceil(after / 60)} min.`+ : "Too many reports were sent. Try again later.",+ true,+ );+ }+ return new DiagnosticsUploadError(+ `The server refused the report (HTTP ${response.status})${said}`,+ response.status >= 500,+ );+};++// Asks the receiver for a report id and an upload URL, uploads the zip and+// returns the report id.+export const uploadDiagnostics = async (+ options: DiagnosticsUploadOptions,+): Promise<string> => {+ if (!isUploadUrl(options.endpoint))+ throw new DiagnosticsUploadError(+ "The upload address must use https",+ false,+ );+ if (options.bytes > MAX_DIAGNOSTICS_UPLOAD_BYTES)+ throw new DiagnosticsUploadError(+ `The diagnostics are larger than ${MAX_DIAGNOSTICS_UPLOAD_BYTES / 1024 / 1024} MB`,+ false,+ );+ let response: Response;+ try {+ response = await fetch(options.endpoint, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ accept: "application/json",+ },+ body: JSON.stringify({+ schema: DIAGNOSTICS_UPLOAD_SCHEMA,+ size: options.bytes,+ sha256: await sha256File(options.file),+ client: { name: "linger-desktop", ...options.client },+ }),+ // A redirect could leave https; receivers answer directly.+ redirect: "error",+ signal: AbortSignal.timeout(30_000),+ });+ } catch (error) {+ throw new DiagnosticsUploadError(+ `Couldn't reach ${new URL(options.endpoint).host}: ${+ error instanceof Error ? error.message : String(error)+ }`,+ true,+ );+ }+ if (!response.ok) throw await refusal(response);+ const ticket = uploadTicket.safeParse(+ await response.json().catch(() => undefined),+ );+ if (!ticket.success)+ throw new DiagnosticsUploadError(+ "The server gave an answer this version of Linger doesn't understand",+ false,+ );+ const headers: Record<string, string> = {};+ for (const [name, value] of Object.entries(ticket.data.upload.headers))+ if (!RESERVED_HEADERS.has(name.toLowerCase())) headers[name] = value;+ await put(ticket.data.upload.url, headers, options);+ return ticket.data.reportId;+};++// Streams the file with a Content-Length, which object stores require of+// a presigned PUT, and reports the bytes sent.+const put = (+ url: string,+ headers: Record<string, string>,+ options: DiagnosticsUploadOptions,+): Promise<void> =>+ new Promise((resolve, reject) => {+ const target = new URL(url);+ const fail = (message: string, retryable = true) =>+ reject(new DiagnosticsUploadError(message, retryable));+ const request = (target.protocol === "https:" ? https : http).request(+ target,+ {+ method: "PUT",+ headers: { ...headers, "content-length": String(options.bytes) },+ },+ (response) => {+ response.resume();+ const status = response.statusCode ?? 0;+ if (status >= 200 && status < 300) resolve();+ else+ fail(+ `The upload was refused (HTTP ${status})`,+ status >= 500 || status === 403,+ );+ },+ );+ request.setTimeout(60_000, () =>+ request.destroy(new Error("The upload stalled")),+ );+ request.on("error", (error) => fail(`The upload failed: ${error.message}`));+ let sent = 0;+ const source = createReadStream(options.file);+ source.on("data", (chunk) => {+ sent += chunk.length;+ options.onProgress?.(sent);+ });+ source.on("error", (error) => request.destroy(error));+ source.pipe(request);+ });++const PROGRESS_INTERVAL_MS = 150;++// A bundle built and waiting for the person's consent, or kept after a+// failed upload so Try Again sends the same files.+export interface PreparedDiagnostics {+ readonly file: string;+ readonly entries: readonly string[];+ readonly bytes: number;+}++export interface DiagnosticsSenderOptions {+ readonly endpoint: () => string | undefined;+ readonly prepare: () => Promise<PreparedDiagnostics>;+ readonly upload: (+ endpoint: string,+ bundle: PreparedDiagnostics,+ onProgress: (sent: number) => void,+ ) => Promise<string>;+ readonly discard: (file: string) => Promise<void>;+ readonly onChange?: (state: SetupDiagnosticsSend) => void;+}++// The send flow every surface shares: build the zip, wait for consent,+// upload, then show the report id or why it failed. Nothing leaves this+// computer before confirm().+export class DiagnosticsSender {+ readonly #options: DiagnosticsSenderOptions;+ #state: SetupDiagnosticsSend = { phase: "idle" };+ #bundle: PreparedDiagnostics | undefined;+ #endpoint: string | undefined;++ constructor(options: DiagnosticsSenderOptions) {+ this.#options = options;+ }++ state(): SetupDiagnosticsSend {+ return this.#state;+ }++ // Whether start() may run now; one send at a time.+ idle(): boolean {+ return ["idle", "sent", "failed"].includes(this.#state.phase);+ }++ async start(): Promise<void> {+ if (!this.idle()) return;+ await this.#drop();+ const endpoint = this.#options.endpoint();+ if (!endpoint) {+ this.#set({+ phase: "failed",+ error: "No diagnostics server is set up.",+ retry: false,+ });+ return;+ }+ this.#endpoint = endpoint;+ this.#set({ phase: "preparing" });+ try {+ this.#bundle = await this.#options.prepare();+ } catch (error) {+ this.#set({+ phase: "failed",+ error: `Couldn't collect the diagnostics: ${message(error)}`,+ retry: true,+ });+ return;+ }+ if (this.#bundle.bytes > MAX_DIAGNOSTICS_UPLOAD_BYTES) {+ await this.#drop();+ this.#set({+ phase: "failed",+ error: `The diagnostics are larger than ${MAX_DIAGNOSTICS_UPLOAD_BYTES / 1024 / 1024} MB. Use Save Diagnostics instead.`,+ retry: false,+ });+ return;+ }+ this.#set({+ phase: "confirm",+ host: new URL(endpoint).host,+ files: this.#bundle.entries,+ bytes: this.#bundle.bytes,+ });+ }++ // The person agreed to the files shown; uploads them.+ async confirm(): Promise<void> {+ const bundle = this.#bundle;+ const endpoint = this.#endpoint;+ if (this.#state.phase !== "confirm" || !bundle || !endpoint) return;+ await this.#upload(endpoint, bundle);+ }++ // After a failure: uploads the same files again, or collects them again+ // when collecting was what failed.+ async retry(): Promise<void> {+ if (this.#state.phase !== "failed" || !this.#state.retry) return;+ const bundle = this.#bundle;+ const endpoint = this.#endpoint;+ if (bundle && endpoint) await this.#upload(endpoint, bundle);+ else {+ this.#set({ phase: "idle" });+ await this.start();+ }+ }++ // Declines, or closes the result; the zip is deleted either way.+ async cancel(): Promise<void> {+ if (this.#state.phase === "preparing" || this.#state.phase === "sending")+ return;+ await this.#drop();+ this.#set({ phase: "idle" });+ }++ async #upload(endpoint: string, bundle: PreparedDiagnostics): Promise<void> {+ const host = new URL(endpoint).host;+ const total = bundle.bytes;+ this.#set({ phase: "sending", host, sent: 0, total });+ // Each chunk would be a state push; a few per second draw the bar.+ let shown = 0;+ try {+ const reportId = await this.#options.upload(endpoint, bundle, (sent) => {+ const now = Date.now();+ if (sent < total && now - shown < PROGRESS_INTERVAL_MS) return;+ shown = now;+ this.#set({ phase: "sending", host, sent, total });+ });+ await this.#drop();+ this.#set({ phase: "sent", host, reportId });+ } catch (error) {+ const retry =+ error instanceof DiagnosticsUploadError ? error.retryable : true;+ if (!retry) await this.#drop();+ this.#set({ phase: "failed", error: message(error), retry });+ }+ }++ async #drop(): Promise<void> {+ const bundle = this.#bundle;+ this.#bundle = undefined;+ if (bundle) await this.#options.discard(bundle.file).catch(() => {});+ }++ #set(state: SetupDiagnosticsSend): void {+ this.#state = state;+ this.#options.onChange?.(state);+ }+}++const message = (error: unknown): string =>+ error instanceof Error ? error.message : String(error);++export const formatBytes = (bytes: number): string =>+ bytes < 1024+ ? `${bytes} B`+ : bytes < 1024 * 1024+ ? `${Math.ceil(bytes / 1024)} KB`+ : `${(bytes / 1024 / 1024).toFixed(1)} MB`;++// What the consent prompt says, for the native dialog of the tray and the+// start failure page; the setup page draws the same facts itself.+export const consentText = (+ state: Extract<SetupDiagnosticsSend, { phase: "confirm" }>,+ shown = 12,+): { readonly message: string; readonly detail: string } => {+ const files = state.files.slice(0, shown).map((file) => ` ${file}`);+ if (state.files.length > shown)+ files.push(` and ${state.files.length - shown} more`);+ return {+ message: `Send diagnostics to ${state.host}?`,+ detail: [+ `${state.files.length} files, ${formatBytes(state.bytes)}: logs and settings of this app and of Linger on this computer.`,+ "Passwords, tokens, keys and your home folder path are removed first; credential files and your data are never included.",+ `Only the people who run ${state.host} can read the report.`,+ "",+ ...files,+ ].join("\n"),+ };+};++// The questions a surface without its own page asks (the tray, the start+// failure page): consent, then the report id, or the failure with Try+// Again.+export interface DiagnosticsPrompts {+ consent(+ state: Extract<SetupDiagnosticsSend, { phase: "confirm" }>,+ ): Promise<boolean>;+ sent(state: Extract<SetupDiagnosticsSend, { phase: "sent" }>): Promise<void>;+ // Resolves true to try again.+ failed(+ state: Extract<SetupDiagnosticsSend, { phase: "failed" }>,+ ): Promise<boolean>;+ // Another send is still running, from the setup page.+ busy(): Promise<void>;+}++// Walks one send through native prompts. A report still waiting for+// consent, say from a setup window that was closed, is asked about here+// instead of blocking the send.+export const sendWithPrompts = async (+ sender: DiagnosticsSender,+ prompts: DiagnosticsPrompts,+): Promise<void> => {+ if (sender.state().phase !== "confirm") {+ if (!sender.idle()) return prompts.busy();+ await sender.start();+ }+ for (;;) {+ const state = sender.state();+ if (state.phase === "confirm") {+ if (await prompts.consent(state)) await sender.confirm();+ else return sender.cancel();+ } else if (state.phase === "sent") {+ await prompts.sent(state);+ return sender.cancel();+ } else if (state.phase === "failed") {+ if (state.retry && (await prompts.failed(state))) await sender.retry();+ else {+ if (!state.retry) await prompts.failed(state);+ return sender.cancel();+ }+ } else return;+ }+};diff --git a/apps/desktop/src/main/diagnostics.test.ts b/apps/desktop/src/main/diagnostics.test.tsindex cf643c39..9db63bee 100644--- a/apps/desktop/src/main/diagnostics.test.ts+++ b/apps/desktop/src/main/diagnostics.test.ts@@ -8,6 +8,7 @@ import {collectDiagnostics,diagnosticsEntry,excludedFromDiagnostics,+ homeRedactor,redactDiagnostics,} from "./diagnostics.js";import { tempDirectory } from "./test-support.js";@@ -95,7 +96,63 @@ describe("redactDiagnostics", () => {});});+describe("homeRedactor", () => {+ it("replaces a macOS or Linux home folder with ~", () => {+ const strip = homeRedactor("/Users/alice/");+ expect(strip("open /Users/alice/.linger/x.log and /Users/alice")).toBe(+ "open ~/.linger/x.log and ~",+ );+ // Another account whose name starts the same stays.+ expect(strip("/Users/alice2/notes")).toBe("/Users/alice2/notes");+ });++ it("replaces a Windows home in every form a log prints it", () => {+ const strip = homeRedactor("C:\\Users\\Alice");+ expect(+ strip(+ [+ "C:\\Users\\Alice\\.linger\\job.log",+ '{"path":"C:\\\\Users\\\\Alice\\\\.linger"}',+ "c:/users/alice/AppData",+ ].join("\n"),+ ),+ ).toBe(+ ["~\\.linger\\job.log", '{"path":"~\\\\.linger"}', "~/AppData"].join(+ "\n",+ ),+ );+ });++ it("leaves text alone for a home at the root", () => {+ expect(homeRedactor("/root")("/root/.linger")).toBe("/root/.linger");+ });+});+describe("collectDiagnostics", () => {+ it("replaces the home folder in every entry and the summary", async () => {+ const root = tempDirectory();+ const userHome = path.join(root, "people", "alice");+ const home = path.join(userHome, ".linger");+ const output = path.join(root, "out");+ mkdirSync(output);+ write(+ path.join(home, "installer", "jobs", "job_1.log"),+ `unpacking into ${path.join(home, "source")}\n`,+ );+ const { file } = await collectDiagnostics({+ userData: path.join(root, "userData"),+ homes: [home],+ output,+ summary: {},+ userHome,+ });+ const text = [...unzip(file).values()].join("\n");+ expect(text).not.toContain(userHome);+ expect(unzip(file).get("linger-home/installer/jobs/job_1.log")).toBe(+ `unpacking into ${path.join("~", ".linger", "source")}\n`,+ );+ });+it("bundles logs and job state without credentials", async () => {const root = tempDirectory();const userData = path.join(root, "userData");@@ -132,7 +189,11 @@ describe("collectDiagnostics", () => {);write(path.join(home, "instances", "desktop", "data", "db.json"), "{}");- const file = await collectDiagnostics({+ const {+ file,+ entries: listed,+ bytes,+ } = await collectDiagnostics({userData,homes: [home, home],output,@@ -144,6 +205,8 @@ describe("collectDiagnostics", () => {if (process.platform !== "win32")expect(statSync(file).mode & 0o777).toBe(0o600);const entries = unzip(file);+ expect(bytes).toBe(statSync(file).size);+ expect([...listed].sort()).toEqual([...entries.keys()].sort());expect([...entries.keys()].sort()).toEqual(["desktop/logs/computer-daemon.log","desktop/logs/main.log",@@ -177,12 +240,14 @@ describe("collectDiagnostics", () => {"connecting with soniox-123\nlive session key xai-456 rejected\n",);const entries = unzip(- await collectDiagnostics({- userData: path.join(root, "userData"),- homes: [home],- output,- summary: {},- }),+ (+ await collectDiagnostics({+ userData: path.join(root, "userData"),+ homes: [home],+ output,+ summary: {},+ })+ ).file,);expect(entries.has("linger-home/instances/desktop/user.env")).toBe(false);const text = [...entries.values()].join("\n");diff --git a/apps/desktop/src/main/diagnostics.ts b/apps/desktop/src/main/diagnostics.tsindex aa7af771..a6c65d90 100644--- a/apps/desktop/src/main/diagnostics.ts+++ b/apps/desktop/src/main/diagnostics.ts@@ -1,5 +1,5 @@import { createWriteStream } from "node:fs";-import { open, readdir, rename, rm, stat } from "node:fs/promises";+import { mkdir, open, readdir, rename, rm, stat } from "node:fs/promises";import os from "node:os";import path from "node:path";import { pipeline } from "node:stream/promises";@@ -7,6 +7,12 @@ import { pipeline } from "node:stream/promises";import { redact } from "@linger/local-installation/redaction";import { ZipFile } from "yazl";+import {+ DiagnosticsSender,+ diagnosticsUploadUrl,+ uploadDiagnostics,+ type PreparedDiagnostics,+} from "./diagnostics-upload.js";import type { LocalServerModule } from "./local-server.js";import { LOCAL_INSTANCE } from "./local-server.js";import type { Module, ModuleContext } from "./modules.js";@@ -70,6 +76,33 @@ const SECRET_KEY =export const redactDiagnostics = (text: string): string =>redact(text.replace(SECRET_KEY, '$1"[REDACTED]"'));+const escapeRegExp = (text: string): string =>+ text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++// Replaces the home folder with ~ as logs print it: native separators,+// forward slashes, and doubled backslashes inside JSON. Windows paths+// compare case-insensitively. The account name in it often names the+// person.+export const homeRedactor = (home: string): ((text: string) => string) => {+ const trimmed = home.replace(/[\\/]+$/, "");+ // A home at the root would turn every path into ~.+ if (trimmed.split(/[\\/]/).filter(Boolean).length < 2) return (text) => text;+ const windows = /^[A-Za-z]:\\/.test(trimmed) || trimmed.includes("\\");+ const forms = new Set([+ trimmed,+ trimmed.replaceAll("\\", "/"),+ trimmed.replaceAll("\\", "\\\\"),+ ]);+ const pattern = new RegExp(+ `(?:${[...forms]+ .sort((a, b) => b.length - a.length)+ .map(escapeRegExp)+ .join("|")})(?![\\w.-])`,+ windows ? "gi" : "g",+ );+ return (text) => text.replace(pattern, "~");+};+// Logs keep their newest part; the bundle stays small enough to send.const MAX_FILE_BYTES = 8 * 1024 * 1024;@@ -177,23 +210,29 @@ export interface DiagnosticsOptions {// Shown first in the bundle: version, platform and the setup state.readonly summary: Record<string, unknown>;readonly now?: Date;+ // The person's home folder, replaced with ~ everywhere.+ readonly userHome?: string;}// Writes linger-diagnostics-<time>.zip with every text redacted and-// returns its path.+// returns its path, entries and size.export const collectDiagnostics = async (options: DiagnosticsOptions,-): Promise<string> => {+): Promise<PreparedDiagnostics> => {const zip = new ZipFile();const added = new Set<string>();const homes = [...new Set(options.homes.map((home) => path.resolve(home)))];// The saved keys themselves, wherever a service printed them.const keys = homes.flatMap((home) => savedSecretValues(home, LOCAL_INSTANCE));+ const withoutHome = homeRedactor(options.userHome ?? os.homedir());const addText = (entry: string, text: string) => {if (added.has(entry)) return;added.add(entry);for (const key of keys) text = text.replaceAll(key, "[REDACTED]");- zip.addBuffer(Buffer.from(redactDiagnostics(text), "utf8"), entry);+ zip.addBuffer(+ Buffer.from(withoutHome(redactDiagnostics(text)), "utf8"),+ entry,+ );};const files = [...(await desktopFiles(options.userData))];for (const [index, home] of homes.entries()) {@@ -237,7 +276,11 @@ export const collectDiagnostics = async (} finally {await rm(partial, { force: true });}- return target;+ return {+ file: target,+ entries: [...added],+ bytes: (await stat(target)).size,+ };};export interface DiagnosticsModuleOptions {@@ -250,23 +293,65 @@ export interface DiagnosticsModuleOptions {readonly output: () => string;readonly openFolder: (folder: string) => Promise<string>;readonly showFile: (file: string) => void;+ // Where a bundle waits for consent; deleted once sent or declined.+ readonly outbox: string;}-// "Show Logs" and "Save Diagnostics" for the setup page, the start failure-// page and the tray.+// "Show Logs", "Save Diagnostics" and "Send Diagnostics" for the setup+// page, the start failure page and the tray.export class DiagnosticsModule implements Module {readonly name = "Diagnostics";readonly dependsOn = ["LocalServer"];readonly #options: DiagnosticsModuleOptions;#ctx: ModuleContext | undefined;#saving: Promise<string> | undefined;+ readonly sender: DiagnosticsSender;constructor(options: DiagnosticsModuleOptions) {this.#options = options;+ this.sender = new DiagnosticsSender({+ endpoint: () => this.uploadUrl(),+ prepare: async () => {+ await mkdir(options.outbox, { recursive: true, mode: 0o700 });+ return this.#collect(options.outbox);+ },+ upload: (endpoint, bundle, onProgress) =>+ uploadDiagnostics({+ endpoint,+ file: bundle.file,+ bytes: bundle.bytes,+ client: {+ version: options.version,+ platform: `${process.platform}-${process.arch}`,+ },+ onProgress,+ }),+ discard: (file) => rm(file, { force: true }),+ onChange: (state) => {+ if (state.phase === "sent")+ this.#ctx?.log.info("diagnostics.sent", {+ host: state.host,+ report_id: state.reportId,+ });+ if (state.phase === "failed")+ this.#ctx?.log.warn("diagnostics.send_failed", {+ error: state.error,+ });+ this.#ctx?.bus.emit("diagnostics.changed");+ },+ });}async start(ctx: ModuleContext): Promise<void> {this.#ctx = ctx;+ // A bundle left by a send the app quit during.+ await rm(this.#options.outbox, { recursive: true, force: true });+ }++ // The receiver Send Diagnostics uploads to; none hides it.+ uploadUrl(): string | undefined {+ const config = this.#ctx?.config.get();+ return config && diagnosticsUploadUrl(config);}async stop(): Promise<void> {}@@ -286,12 +371,19 @@ export class DiagnosticsModule implements Module {}async #save(): Promise<string> {+ const { file } = await this.#collect(this.#options.output());+ this.#ctx?.log.info("diagnostics.saved", { file });+ this.#options.showFile(file);+ return file;+ }++ #collect(output: string): Promise<PreparedDiagnostics> {const local = this.#ctx?.get<LocalServerModule>("LocalServer").status();const config = this.#ctx?.config.get();- const file = await collectDiagnostics({+ return collectDiagnostics({userData: this.#options.userData,homes: [this.#options.home, ...(local ? [local.location.path] : [])],- output: this.#options.output(),+ output,summary: {version: this.#options.version,platform: `${process.platform}-${process.arch}`,@@ -305,8 +397,5 @@ export class DiagnosticsModule implements Module {},},});- this.#ctx?.log.info("diagnostics.saved", { file });- this.#options.showFile(file);- return file;}}diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 2997e42b..f887828d 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -308,6 +308,7 @@ async function main(): Promise<void> {output: () => app.getPath("downloads"),openFolder: (folder) => shell.openPath(folder),showFile: (file) => shell.showItemInFolder(file),+ outbox: path.join(userData, "diagnostics-outbox"),}),setup,updater,diff --git a/apps/desktop/src/main/modules.ts b/apps/desktop/src/main/modules.tsindex 3cf78f6a..58461299 100644--- a/apps/desktop/src/main/modules.ts+++ b/apps/desktop/src/main/modules.ts@@ -19,6 +19,7 @@ export interface BusEvents {// Why the Computer service keeps exiting at start, or undefined once it ran."computer.failed": [reason: string | undefined];"computer.renamed": [];+ "diagnostics.changed": [];"grants.changed": [];"local-server.changed": [];// Forget the installation the window used and set this computer up again.diff --git a/apps/desktop/src/main/setup-command.test.ts b/apps/desktop/src/main/setup-command.test.tsindex 269e1e3c..6f7c7204 100644--- a/apps/desktop/src/main/setup-command.test.ts+++ b/apps/desktop/src/main/setup-command.test.ts@@ -23,6 +23,9 @@ describe("parseSetupCommand", () => {runtime: "local",}),).toEqual({ op: "local.start", runtime: "local" });+ expect(+ parseSetupCommand({ op: "diagnostics.send", action: "confirm" }),+ ).toEqual({ op: "diagnostics.send", action: "confirm" });expect(parseSetupCommand({ op: "local.location.pick" })).toEqual({op: "local.location.pick",});diff --git a/apps/desktop/src/main/setup-command.ts b/apps/desktop/src/main/setup-command.tsindex c9b5760e..3f84e25f 100644--- a/apps/desktop/src/main/setup-command.ts+++ b/apps/desktop/src/main/setup-command.ts@@ -68,6 +68,12 @@ const setupCommand = z.discriminatedUnion("op", [z.object({ op: z.literal("finish") }).strict(),z.object({ op: z.literal("logs.open") }).strict(),z.object({ op: z.literal("diagnostics.save") }).strict(),+ z+ .object({+ op: z.literal("diagnostics.send"),+ action: z.enum(["start", "confirm", "retry", "cancel", "copy"]),+ })+ .strict(),]);// Commands come from a local page, but are still validated at the boundary.diff --git a/apps/desktop/src/main/setup-window.ts b/apps/desktop/src/main/setup-window.tsindex 199c6092..0c226dd7 100644--- a/apps/desktop/src/main/setup-window.ts+++ b/apps/desktop/src/main/setup-window.ts@@ -133,6 +133,7 @@ export class SetupWindowModule implements Module {() => session.defaultSession.cookies.off("changed", onCookie),() => pages.protocol.unhandle("app"),ctx.bus.on("computer.changed", push),+ ctx.bus.on("diagnostics.changed", push),ctx.bus.on("power.changed", push),ctx.bus.on("grants.changed", push),ctx.bus.on("local-server.changed", onLocal),@@ -205,6 +206,9 @@ export class SetupWindowModule implements Module {window.on("closed", () => {if (this.#window === window) this.#window = undefined;this.#account?.hide();+ // A report waiting on this page's consent would block other sends.+ const sender = this.#ctx?.get<DiagnosticsModule>("Diagnostics").sender;+ if (sender?.state().phase === "confirm") void sender.cancel();});this.#window = window;void window.loadURL(SETUP_URL).catch(() => undefined);@@ -321,6 +325,18 @@ export class SetupWindowModule implements Module {};}return;+ case "diagnostics.send": {+ const sender = ctx.get<DiagnosticsModule>("Diagnostics").sender;+ const state = sender.state();+ // Collecting and uploading report through diagnostics.changed, so+ // the page stays usable meanwhile.+ if (command.action === "start") void sender.start();+ else if (command.action === "confirm") void sender.confirm();+ else if (command.action === "retry") void sender.retry();+ else if (command.action === "cancel") await sender.cancel();+ else if (state.phase === "sent") clipboard.writeText(state.reportId);+ return;+ }case "finish":this.#window?.close();windows.show();@@ -331,6 +347,7 @@ export class SetupWindowModule implements Module {#state(): SetupState {const ctx = this.#ctx!;const config = ctx.config.get();+ const diagnostics = ctx.get<DiagnosticsModule>("Diagnostics");return {platform: process.platform as SetupState["platform"],version: this.#options.version,@@ -350,6 +367,9 @@ export class SetupWindowModule implements Module {this.#account?.view(),),...(this.#diagnostics ? { diagnostics: this.#diagnostics } : {}),+ ...(diagnostics.uploadUrl()+ ? { diagnosticsSend: diagnostics.sender.state() }+ : {}),...(this.#permissions ? { permissions: this.#permissions } : {}),};}diff --git a/apps/desktop/src/main/tray-menu.test.ts b/apps/desktop/src/main/tray-menu.test.tsindex 3087593e..6c74d8c9 100644--- a/apps/desktop/src/main/tray-menu.test.ts+++ b/apps/desktop/src/main/tray-menu.test.ts@@ -27,6 +27,20 @@ describe("trayMenu", () => {]);});+ it("offers Send Diagnostics only while a receiver is set up", () => {+ const actions = (canSendDiagnostics: boolean) =>+ trayMenu({+ status: { tone: "error", label: "Offline" },+ preventSleep: false,+ enrolled: true,+ canSendDiagnostics,+ }).flatMap((i) => (i.kind === "action" ? i.action : []));+ expect(actions(false)).not.toContain("send-diagnostics");+ expect(actions(true)).toEqual(+ expect.arrayContaining(["save-diagnostics", "send-diagnostics"]),+ );+ });+it("connects an unenrolled computer and reconnects an enrolled one", () => {const label = (enrolled: boolean) =>trayMenu({diff --git a/apps/desktop/src/main/tray-menu.ts b/apps/desktop/src/main/tray-menu.tsindex 5c5904e0..99a9b70b 100644--- a/apps/desktop/src/main/tray-menu.ts+++ b/apps/desktop/src/main/tray-menu.ts@@ -9,6 +9,7 @@ export type TrayAction =| "check-update"| "show-logs"| "save-diagnostics"+ | "send-diagnostics"| "quit";export type TrayMenuItem =@@ -28,6 +29,8 @@ export interface TrayMenuState {// The updater's progress; a failure says why, since it is otherwise only// in the log.readonly update?: UpdateState;+ // A diagnostics server is set up, so reports can be sent from here.+ readonly canSendDiagnostics?: boolean;}// The tray menu. Items for features that do not exist yet@@ -56,6 +59,15 @@ export const trayMenu = (state: TrayMenuState): TrayMenuItem[] => [// What to send when something goes wrong.{ kind: "action", action: "show-logs", label: "Show Logs" },{ kind: "action", action: "save-diagnostics", label: "Save Diagnostics…" },+ ...(state.canSendDiagnostics+ ? [+ {+ kind: "action" as const,+ action: "send-diagnostics" as const,+ label: "Send Diagnostics…",+ },+ ]+ : []),{ kind: "separator" },// Tasks run in the app, so quitting takes the computer offline.{ kind: "action", action: "quit", label: "Quit Linger" },diff --git a/apps/desktop/src/main/tray.ts b/apps/desktop/src/main/tray.tsindex c92a8ffe..4ab599b1 100644--- a/apps/desktop/src/main/tray.ts+++ b/apps/desktop/src/main/tray.ts@@ -13,6 +13,8 @@ import mark32 from "../../resources/tray/mark-32.png";import tile16 from "../../resources/tray/tile-16.png";import tile32 from "../../resources/tray/tile-32.png";import type { DiagnosticsModule } from "./diagnostics.js";+import { diagnosticsDialogs } from "./diagnostics-dialogs.js";+import { sendWithPrompts } from "./diagnostics-upload.js";import { EnrollmentError, type EnrollmentModule } from "./enrollment.js";import type { Module, ModuleContext } from "./modules.js";import type { PowerGuardModule } from "./power-guard.js";@@ -152,6 +154,8 @@ export class TrayModule implements Module {preventSleep: power.alwaysOn(),enrolled: !!this.#ctx!.config.get().computerId,update,+ canSendDiagnostics:+ !!this.#ctx!.get<DiagnosticsModule>("Diagnostics").uploadUrl(),});return Menu.buildFromTemplate(items.map((item) => this.#item(item)));}@@ -200,6 +204,14 @@ export class TrayModule implements Module {);break;}+ case "send-diagnostics":+ void sendWithPrompts(+ ctx.get<DiagnosticsModule>("Diagnostics").sender,+ diagnosticsDialogs(() =>+ ctx.get<WindowManagerModule>("WindowManager").window(),+ ),+ );+ break;case "quit":this.#options.quit();break;diff --git a/apps/desktop/src/main/window-manager.ts b/apps/desktop/src/main/window-manager.tsindex 28f00771..b4d1665d 100644--- a/apps/desktop/src/main/window-manager.ts+++ b/apps/desktop/src/main/window-manager.ts@@ -21,6 +21,8 @@ import {type TitlebarState,} from "../shared/shell.js";import type { DiagnosticsModule } from "./diagnostics.js";+import { diagnosticsDialogs } from "./diagnostics-dialogs.js";+import { sendWithPrompts } from "./diagnostics-upload.js";import type { Module, ModuleContext } from "./modules.js";import {OFFLINE_ORIGIN,@@ -280,6 +282,12 @@ export class WindowManagerModule implements Module {#loadLocal(mode: "updating" | "starting" | "failed", value: string): void {const url = new URL(`${OFFLINE_ORIGIN}/`);url.searchParams.set(mode, value);+ // Send Diagnostics shows only while a diagnostics server is set up.+ if (+ mode === "failed" &&+ this.#ctx!.get<DiagnosticsModule>("Diagnostics").uploadUrl()+ )+ url.searchParams.set("send", "1");void this.#content?.webContents.loadURL(url.toString()).catch(() => undefined);@@ -469,6 +477,13 @@ export class WindowManagerModule implements Module {);return new Response(null, { status: 204 });}+ if (url.pathname === "/send") {+ void sendWithPrompts(+ this.#ctx!.get<DiagnosticsModule>("Diagnostics").sender,+ diagnosticsDialogs(() => this.#window),+ );+ return new Response(null, { status: 204 });+ }if (url.pathname === "/restart") {this.#ctx!.bus.emit("local-server.retry");return new Response(null, { status: 204 });diff --git a/apps/desktop/src/shared/setup.ts b/apps/desktop/src/shared/setup.tsindex 4ff25ddb..d6dc1975 100644--- a/apps/desktop/src/shared/setup.ts+++ b/apps/desktop/src/shared/setup.ts@@ -148,6 +148,31 @@ export interface SetupProviderKeys {readonly composio?: string;}+// Send Diagnostics: the zip is built (preparing), shown for consent with+// what it holds and where it goes (confirm), uploaded (sending), then the+// receiver's report id (sent) or why it failed and whether Try Again can+// help.+export type SetupDiagnosticsSend =+ | { readonly phase: "idle" | "preparing" }+ | {+ readonly phase: "confirm";+ readonly host: string;+ readonly files: readonly string[];+ readonly bytes: number;+ }+ | {+ readonly phase: "sending";+ readonly host: string;+ readonly sent: number;+ readonly total: number;+ }+ | { readonly phase: "sent"; readonly host: string; readonly reportId: string }+ | {+ readonly phase: "failed";+ readonly error: string;+ readonly retry: boolean;+ };+export interface SetupState {readonly platform: "darwin" | "win32" | "linux";readonly version: string;@@ -161,6 +186,8 @@ export interface SetupState {readonly localServer: SetupLocalServer;// The diagnostics zip last saved from this window, or why it failed.readonly diagnostics?: { readonly file?: string; readonly error?: string };+ // Send Diagnostics, present only while a diagnostics server is set up.+ readonly diagnosticsSend?: SetupDiagnosticsSend;// macOS privacy permissions; absent on other platforms or until checked.readonly permissions?: Readonly<Record<SetupPermission, SetupPermissionStatus>@@ -209,7 +236,13 @@ export type SetupCommand =| { readonly op: "finish" }// Opens the log folder, or saves a redacted diagnostics zip and shows it.| { readonly op: "logs.open" }- | { readonly op: "diagnostics.save" };+ | { readonly op: "diagnostics.save" }+ // Send Diagnostics: build the zip and ask, send it, try again, cancel or+ // close, or copy the report id.+ | {+ readonly op: "diagnostics.send";+ readonly action: "start" | "confirm" | "retry" | "cancel" | "copy";+ };export interface LingerSetupApi {getState(): Promise<SetupState>;diff --git a/apps/desktop/src/shell/offline.html b/apps/desktop/src/shell/offline.htmlindex 50399c3d..13cc7666 100644--- a/apps/desktop/src/shell/offline.html+++ b/apps/desktop/src/shell/offline.html@@ -125,13 +125,15 @@}.actions {display: flex;+ flex-wrap: wrap;align-items: center;- gap: 12px;+ gap: 4px 12px;margin-top: 24px;}button,.link {height: 36px;+ white-space: nowrap;padding: 0 16px;border-radius: 8px;font: inherit;@@ -237,6 +239,9 @@<button class="link failed-only" id="diagnostics" type="button">Save Diagnostics</button>+ <button class="link failed-only" id="send" type="button" hidden>+ Send Diagnostics+ </button><button class="link failed-only" id="reset" type="button">Set Up Again</button>@@ -314,6 +319,11 @@$("diagnostics").addEventListener("click", () => {location.href = "app://offline/diagnostics";});+ // Asks before sending, in a dialog of the main process.+ $("send").hidden = !params.has("send");+ $("send").addEventListener("click", () => {+ location.href = "app://offline/send";+ });$("edit").addEventListener("click", () => {document.body.classList.add("editing");$("server").select();diff --git a/apps/desktop/src/shell/setup-page.test.ts b/apps/desktop/src/shell/setup-page.test.tsindex 943b8d4b..8bd3dfcb 100644--- a/apps/desktop/src/shell/setup-page.test.ts+++ b/apps/desktop/src/shell/setup-page.test.ts@@ -541,3 +541,130 @@ describe("setup page download progress", () => {);});});++describe("setup page Send Diagnostics", () => {+ // A failure scrolls its actions into view, which jsdom lacks.+ beforeEach(() => {+ Element.prototype.scrollIntoView = () => {};+ });++ const failed = (+ diagnosticsSend?: SetupState["diagnosticsSend"],+ ): SetupState => {+ const base = state("failed");+ return {+ ...base,+ localServer: { ...base.localServer, message: "Services did not start" },+ ...(diagnosticsSend ? { diagnosticsSend } : {}),+ };+ };++ it("hides Send Diagnostics while no receiver is set up", async () => {+ await openPage(failed());+ expect($("installing-diagnostics").hidden).toBe(false);+ expect($("send-diagnostics").hidden).toBe(true);+ expect($("send-modal").hidden).toBe(true);+ });++ it("asks before sending and lists every file", async () => {+ const { run, push } = await openPage(failed({ phase: "idle" }));+ expect($("send-diagnostics").hidden).toBe(false);+ $("send-diagnostics").click();+ await vi.waitFor(() =>+ expect(run).toHaveBeenCalledWith({+ op: "diagnostics.send",+ action: "start",+ }),+ );+ push(failed({ phase: "preparing" }));+ expect($("send-modal").hidden).toBe(false);+ expect($("send-title").textContent).toBe("Preparing diagnostics");+ expect($("send-primary").hidden).toBe(true);+ push(+ failed({+ phase: "confirm",+ host: "diagnostics.example.com",+ files: ["summary.json", "desktop/logs/main.log"],+ bytes: 2048,+ }),+ );+ expect($("send-title").textContent).toBe(+ "Send diagnostics to diagnostics.example.com?",+ );+ expect($("send-lead").textContent).toContain("2 files, 2 KB");+ expect($("send-lead").textContent).toContain("home folder path");+ expect(+ [...$("send-files").querySelectorAll("li")].map((li) => li.textContent),+ ).toEqual(["summary.json", "desktop/logs/main.log"]);+ expect($("send-primary").textContent).toBe("Send");+ expect($("send-close").textContent).toBe("Cancel");+ $("send-primary").click();+ await vi.waitFor(() =>+ expect(run).toHaveBeenLastCalledWith({+ op: "diagnostics.send",+ action: "confirm",+ }),+ );+ });++ it("shows progress, then the report id to copy", async () => {+ const { run, push } = await openPage(failed({ phase: "idle" }));+ push(+ failed({+ phase: "sending",+ host: "diagnostics.example.com",+ sent: 512,+ total: 2048,+ }),+ );+ expect($("send-title").textContent).toBe("Sending diagnostics");+ expect($("send-lead").textContent).toBe(+ "Uploading to diagnostics.example.com… 25%",+ );+ expect($("send-track").hidden).toBe(false);+ expect($("send-fill").style.width).toBe("25%");+ expect($("send-close").hidden).toBe(true);+ push(+ failed({+ phase: "sent",+ host: "diagnostics.example.com",+ reportId: "LD-7K3Q9XPM",+ }),+ );+ expect($("send-report").hidden).toBe(false);+ expect($("send-report-id").textContent).toBe("LD-7K3Q9XPM");+ $("send-primary").click();+ await vi.waitFor(() =>+ expect($("send-primary").textContent).toBe("Copied"),+ );+ expect(run).toHaveBeenCalledWith({+ op: "diagnostics.send",+ action: "copy",+ });+ $("send-close").click();+ await vi.waitFor(() =>+ expect(run).toHaveBeenLastCalledWith({+ op: "diagnostics.send",+ action: "cancel",+ }),+ );+ });++ it("offers Try Again only when it can help", async () => {+ const { run, push } = await openPage(failed({ phase: "idle" }));+ push(failed({ phase: "failed", error: "Couldn't reach it", retry: true }));+ expect($("send-error").textContent).toBe("Couldn't reach it");+ expect($("send-primary").textContent).toBe("Try Again");+ $("send-primary").click();+ await vi.waitFor(() =>+ expect(run).toHaveBeenLastCalledWith({+ op: "diagnostics.send",+ action: "retry",+ }),+ );+ push(failed({ phase: "failed", error: "Too large", retry: false }));+ expect($("send-primary").hidden).toBe(true);+ expect($("send-lead").textContent).toContain("Save Diagnostics");+ expect($("send-close").textContent).toBe("Close");+ });+});diff --git a/apps/desktop/src/shell/setup.html b/apps/desktop/src/shell/setup.htmlindex ca546dff..12887665 100644--- a/apps/desktop/src/shell/setup.html+++ b/apps/desktop/src/shell/setup.html@@ -1177,9 +1177,46 @@margin: 6px auto 0;font-size: 12px;}- .diagnostics[hidden] {+ .diagnostics[hidden],+ .diagnostics [hidden] {display: none;}+ /* Send Diagnostics: consent, progress and the report id. */+ .send-modal .files {+ max-height: 132px;+ margin: 0 0 14px;+ padding: 8px 10px;+ overflow: auto;+ border: 1px solid var(--line);+ border-radius: 8px;+ list-style: none;+ color: var(--muted);+ font:+ 11px/1.6 ui-monospace,+ SFMono-Regular,+ Menlo,+ monospace;+ overflow-wrap: anywhere;+ }+ .send-modal .track {+ margin: 0 0 14px;+ }+ .send-modal .fill {+ transition: width 200ms linear;+ }+ .send-modal .report strong {+ display: block;+ margin-top: 6px;+ color: var(--ink);+ font:+ 600 16px ui-monospace,+ SFMono-Regular,+ Menlo,+ monospace;+ letter-spacing: 0.06em;+ user-select: all;+ -webkit-user-select: all;+ }.diagnostics output {flex-basis: 100%;color: #52524b;@@ -1601,8 +1638,36 @@<button class="link quiet" id="save-diagnostics" type="button">Save Diagnostics</button>+ <button class="link quiet" id="send-diagnostics" type="button" hidden>+ Send Diagnostics+ </button><output id="diagnostics-note"></output></div>+ <div+ class="signin-modal send-modal"+ id="send-modal"+ role="dialog"+ aria-modal="true"+ aria-labelledby="send-title"+ hidden+ >+ <div class="sheet">+ <h2 id="send-title"></h2>+ <p id="send-lead"></p>+ <ul class="files" id="send-files" aria-label="Files to send"></ul>+ <div class="track" id="send-track">+ <div class="fill" id="send-fill"></div>+ </div>+ <p class="report" id="send-report">+ Report ID <strong id="send-report-id"></strong>+ </p>+ <p class="problem" id="send-error" role="alert"></p>+ <div class="actions">+ <button class="primary" id="send-primary" type="button"></button>+ <button class="link quiet" id="send-close" type="button"></button>+ </div>+ </div>+ </div><footer class="actions" id="installing-actions"><button class="ghost" data-go="welcome" type="button">Back</button><button class="primary" id="local-retry" type="button">@@ -2517,6 +2582,7 @@shownDiagnostics = savedKey;$("installing-actions").hidden = !failed;renderSignIn(local, busy);+ renderSend();// Each failure brings its message and actions into view once.if (failed && revealed !== local.attempt) {revealed = local.attempt;@@ -2620,6 +2686,86 @@);};+ // Send Diagnostics, while a diagnostics server is set up.+ const fileSize = (bytes) =>+ bytes < 1024 ** 2+ ? Math.max(1, Math.ceil(bytes / 1024)) + " KB"+ : (bytes / 1024 ** 2).toFixed(1) + " MB";+ let copiedReport;+ const renderSend = () => {+ const send = state.diagnosticsSend;+ $("send-diagnostics").hidden = !send;+ const phase = send?.phase ?? "idle";+ $("send-modal").hidden = phase === "idle";+ if (phase === "idle") return;+ const title = {+ preparing: "Preparing diagnostics",+ confirm: "Send diagnostics to " + send.host + "?",+ sending: "Sending diagnostics",+ sent: "Diagnostics sent",+ failed: "Couldn't send diagnostics",+ }[phase];+ $("send-title").textContent = title;+ const lead = $("send-lead");+ if (phase === "preparing")+ lead.innerHTML =+ '<span class="spinner"></span>Collecting logs and settings…';+ else+ lead.textContent =+ phase === "confirm"+ ? send.files.length ++ " files, " ++ fileSize(send.bytes) ++ ": logs and settings of this app and of Linger on this computer. Passwords, tokens, keys and your home folder path are removed first; credential files and your data are never included. Only the people who run " ++ send.host ++ " can read the report."+ : phase === "sending"+ ? "Uploading to " ++ send.host ++ "… " ++ Math.floor((send.sent / Math.max(1, send.total)) * 100) ++ "%"+ : phase === "sent"+ ? "Give this report ID to Linger support so they can find your report."+ : send.retry+ ? ""+ : "You can still use Save Diagnostics and send the file by hand.";+ const files = $("send-files");+ files.hidden = phase !== "confirm";+ if (+ phase === "confirm" &&+ files.dataset.shown !== send.files.join("\n")+ ) {+ files.replaceChildren(+ ...send.files.map((file) => {+ const item = document.createElement("li");+ item.textContent = file;+ return item;+ }),+ );+ files.dataset.shown = send.files.join("\n");+ }+ $("send-track").hidden = phase !== "sending";+ if (phase === "sending")+ $("send-fill").style.width =+ Math.min(100, (send.sent / Math.max(1, send.total)) * 100) + "%";+ $("send-report").hidden = phase !== "sent";+ $("send-report-id").textContent = phase === "sent" ? send.reportId : "";+ $("send-error").textContent = phase === "failed" ? send.error : "";+ const primary = {+ confirm: "Send",+ sent: copiedReport === send.reportId ? "Copied" : "Copy Report ID",+ failed: send.retry ? "Try Again" : "",+ }[phase];+ $("send-primary").hidden = !primary;+ $("send-primary").textContent = primary ?? "";+ const close = { confirm: "Cancel", sent: "Done", failed: "Close" }[+ phase+ ];+ $("send-close").hidden = !close;+ $("send-close").textContent = close ?? "";+ };+// Runs one command at a time; errors land next to the step.const run = async (command, errorId) => {if (pending !== null) return;@@ -2714,6 +2860,27 @@$("save-diagnostics").addEventListener("click", () =>run({ op: "diagnostics.save" }, "diagnostics-note"),);+ $("send-diagnostics").addEventListener("click", () => {+ copiedReport = undefined;+ run({ op: "diagnostics.send", action: "start" }, "diagnostics-note");+ });+ $("send-primary").addEventListener("click", async () => {+ const send = state.diagnosticsSend;+ if (send?.phase === "confirm")+ run({ op: "diagnostics.send", action: "confirm" }, "send-error");+ else if (send?.phase === "failed")+ run({ op: "diagnostics.send", action: "retry" }, "send-error");+ else if (send?.phase === "sent") {+ if (+ await run({ op: "diagnostics.send", action: "copy" }, "send-error")+ )+ copiedReport = send.reportId;+ render();+ }+ });+ $("send-close").addEventListener("click", () =>+ run({ op: "diagnostics.send", action: "cancel" }, "send-error"),+ );const clearKeys = () => {keys = {};for (const input of document.querySelectorAll("[data-key]")) {diff --git a/docs/diagnostics-upload.md b/docs/diagnostics-upload.mdnew file mode 100644index 00000000..d45150f5--- /dev/null+++ b/docs/diagnostics-upload.md@@ -0,0 +1,141 @@+# Diagnostics upload++When setup or the local services fail, the desktop app can send its+diagnostics zip to a receiver instead of asking the person to mail the file.+This page is the contract a receiver implements, so a team that runs its own+Linger can collect reports too.++## In the app++Send Diagnostics shows on the setup page's failed step ("Installation+stopped"), on the start failure page and in the tray menu, but only while a+receiver is set up. The app builds the same redacted zip as Save Diagnostics+(see `apps/desktop/src/main/diagnostics.ts`): credential files are never+included, secret-looking values are replaced with `[REDACTED]`, and the home+folder path is replaced with `~`. It then lists every file, the size and the+receiver's host and uploads nothing until the person chooses Send. The+receiver's report id is shown at the end with Copy Report ID; the person gives+it to support. A failed upload keeps the zip for Try Again; the zip is deleted+once sent or declined.++The receiver is `diagnosticsUploadUrl` in the desktop `config.json` (in the+app's user data folder). It must be `https`, or `http` to `localhost`,+`127.0.0.1` or `[::1]` while developing a receiver; any other value is+ignored. Without it, the app uses its built-in hosted receiver, and when it+has none, Send Diagnostics is hidden.++```json+{ "diagnosticsUploadUrl": "https://diagnostics.example.com/v1/reports" }+```++## Protocol `linger.diagnostics-upload/v1`++Two requests. The receiver never has to accept the zip itself: it can hand+out a presigned object storage URL.++### 1. Ask for an upload++```http+POST /v1/reports HTTP/1.1+Content-Type: application/json++{+ "schema": "linger.diagnostics-upload/v1",+ "size": 183204,+ "sha256": "<hex SHA-256 of the zip>",+ "client": {+ "name": "linger-desktop",+ "version": "0.16.20",+ "platform": "darwin-arm64"+ }+}+```++The receiver answers `200` or `201`:++```json+{+ "schema": "linger.diagnostics-upload/v1",+ "reportId": "LD-7K3Q9XPM",+ "upload": {+ "method": "PUT",+ "url": "https://storage.example.com/reports/LD-7K3Q9XPM.zip?X-Amz-...",+ "headers": { "content-type": "application/zip" }+ }+}+```++- `reportId`: 4 to 64 letters, digits and `-`, starting with a letter or+ digit. It is what the person reads out, so keep it short, and random+ enough that reports cannot be guessed.+- `upload.url`: `https` (or loopback `http`, as above). The app does not+ follow redirects on the first request.+- `upload.headers`: sent as given with the upload, except `Host`,+ `Content-Length`, `Transfer-Encoding` and `Connection`, which the app sets.++### 2. Upload the zip++```http+PUT <upload.url> HTTP/1.1+Content-Type: application/zip+Content-Length: 183204++<zip bytes>+```++Any `2xx` completes the report. There is no further request.++### Errors++Answer the first request with the repository's error envelope,+`{"error": {"code": "...", "message": "..."}}`; the app shows the message.++| Status | Meaning | The app |+| ------ | ------------------------- | ---------------------------------------- |+| `413` | `size` is over your limit | No Try Again; suggests Save Diagnostics |+| `429` | Rate limited | Try Again; shows `Retry-After` (seconds) |+| `5xx` | Receiver failure | Try Again |+| other | Refused | No Try Again |++A `403` or `5xx` on the upload offers Try Again with the same zip and a new+first request. The app refuses zips over 50 MB itself.++## Running a receiver++A receiver should:++- accept the first request without sign-in (the person may be failing to set+ up the server they would sign in to) and limit it per client address;+- refuse `size` over its limit (50 MB is the app's own) and sign the+ presigned PUT for exactly that `Content-Length` and+ `Content-Type: application/zip`, valid for a few minutes;+- store reports privately (no public read), encrypted at rest, and delete+ them after a fixed time such as 30 days;+- record `reportId`, the `client` fields, `sha256` and the time, so support+ can find a report by id and check the zip.++With S3, the first request is a few lines around `PutObjectCommand` and+`getSignedUrl` from the AWS SDK:++```ts+const reportId = `LD-${randomBytes(5).toString("hex").toUpperCase()}`;+const url = await getSignedUrl(+ s3,+ new PutObjectCommand({+ Bucket: bucket,+ Key: `reports/${new Date().toISOString().slice(0, 10)}/${reportId}.zip`,+ ContentType: "application/zip",+ ContentLength: body.size,+ Metadata: { sha256: body.sha256, version: body.client.version },+ }),+ {+ expiresIn: 300,+ signableHeaders: new Set(["content-type", "content-length"]),+ },+);+// 201 { schema, reportId, upload: { method: "PUT", url,+// headers: { "content-type": "application/zip" } } }+```++Pair it with a bucket lifecycle rule that expires `reports/` after 30 days and+aborts incomplete multipart uploads.diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 3384d27a..d85a6a89 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -42,6 +42,10 @@ develop on the code with hot reload instead, `pnpm dev` runs every service onyour machine against a PostgreSQL you provide; see[CONTRIBUTING.md](../CONTRIBUTING.md).+To collect the desktop app's diagnostics from your people, run a receiver+for [Diagnostics upload](diagnostics-upload.md) and set its address as+`diagnosticsUploadUrl` in each app's `config.json`.+## Troubleshooting| Problem | What to try |