The best way to control Claude Code, Codex and more from any computer or phone
[codex] Preserve desktop backend log failures (#3375)
Co-authored-by: codex <codex@users.noreply.github.com>
Julius Marminge committed
Jun 20, 2026 at 15:12 UTC
faccdd4ca9511204144f3ec8d696a8993d878946
2 files changed
+273
-46
apps/desktop/src/app/DesktopBackendOutputLog.test.ts
new
+122
@@ -0,0 +1,122 @@
1
+import { assert, describe, it } from "@effect/vitest";
2
+import * as Effect from "effect/Effect";
3
+import * as FileSystem from "effect/FileSystem";
4
+import * as Layer from "effect/Layer";
5
+import * as Logger from "effect/Logger";
6
+import * as Path from "effect/Path";
7
+import * as PlatformError from "effect/PlatformError";
8
+
9
+import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
10
+import * as DesktopConfig from "./DesktopConfig.ts";
11
+import * as DesktopEnvironment from "./DesktopEnvironment.ts";
12
+
13
+const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
14
+
15
+const environmentLayer = DesktopEnvironment.layer({
16
+ dirname: "/repo/apps/desktop/dist-electron",
17
+ homeDirectory: "/Users/alice",
18
+ platform: "darwin",
19
+ processArch: "arm64",
20
+ appVersion: "1.2.3",
21
+ appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
22
+ isPackaged: true,
23
+ resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
24
+ runningUnderArm64Translation: false,
25
+}).pipe(Layer.provide(Layer.merge(Path.layer, DesktopConfig.layerTest({}))));
26
+
27
+const withOutputLog = <A, E, R>(
28
+ effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
29
+ fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
30
+ messages: Array<ReadonlyArray<unknown>>,
31
+) => {
32
+ const logger = Logger.make(({ message }) => {
33
+ messages.push(Array.isArray(message) ? message : [message]);
34
+ });
35
+ const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
36
+ Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
37
+ Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
38
+ );
39
+ return effect.pipe(Effect.provide(outputLogLayer));
40
+};
41
+
42
+const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
43
+ messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
44
+ ?.error;
45
+
46
+describe("DesktopBackendOutputLog", () => {
47
+ it.effect("logs setup failures with the log path and exact cause", () => {
48
+ const messages: Array<ReadonlyArray<unknown>> = [];
49
+ const cause = PlatformError.systemError({
50
+ _tag: "PermissionDenied",
51
+ module: "FileSystem",
52
+ method: "makeDirectory",
53
+ pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
54
+ description: "private setup diagnostic",
55
+ });
56
+ const fileSystemLayer = FileSystem.layerNoop({
57
+ makeDirectory: () => Effect.fail(cause),
58
+ });
59
+
60
+ return withOutputLog(
61
+ Effect.gen(function* () {
62
+ const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
63
+ yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
64
+
65
+ const error = loggedError(messages);
66
+ assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
67
+ assert.equal(error.logFilePath, LOG_FILE_PATH);
68
+ assert.strictEqual(error.cause, cause);
69
+ assert.equal(
70
+ error.message,
71
+ `Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
72
+ );
73
+ assert.notInclude(error.message, "private setup diagnostic");
74
+ }),
75
+ fileSystemLayer,
76
+ messages,
77
+ );
78
+ });
79
+
80
+ it.effect("logs record write failures with the operation and exact cause", () => {
81
+ const messages: Array<ReadonlyArray<unknown>> = [];
82
+ const missingCause = PlatformError.systemError({
83
+ _tag: "NotFound",
84
+ module: "FileSystem",
85
+ method: "stat",
86
+ pathOrDescriptor: LOG_FILE_PATH,
87
+ });
88
+ const writeCause = PlatformError.systemError({
89
+ _tag: "PermissionDenied",
90
+ module: "FileSystem",
91
+ method: "writeFile",
92
+ pathOrDescriptor: LOG_FILE_PATH,
93
+ description: "private write diagnostic",
94
+ });
95
+ const fileSystemLayer = FileSystem.layerNoop({
96
+ makeDirectory: () => Effect.void,
97
+ stat: () => Effect.fail(missingCause),
98
+ readDirectory: () => Effect.succeed([]),
99
+ writeFile: () => Effect.fail(writeCause),
100
+ });
101
+
102
+ return withOutputLog(
103
+ Effect.gen(function* () {
104
+ const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
105
+ yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
106
+
107
+ const error = loggedError(messages);
108
+ assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
109
+ assert.equal(error.operation, "write-record");
110
+ assert.equal(error.logFilePath, LOG_FILE_PATH);
111
+ assert.strictEqual(error.cause, writeCause);
112
+ assert.equal(
113
+ error.message,
114
+ `Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
115
+ );
116
+ assert.notInclude(error.message, "private write diagnostic");
117
+ }),
118
+ fileSystemLayer,
119
+ messages,
120
+ );
121
+ });
122
+});
apps/desktop/src/app/DesktopBackendOutputLog.ts
+151
-46
@@ -19,8 +19,75 @@ export const DESKTOP_LOG_FILE_MAX_FILES = 10;
19
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
20
21
interface RotatingLogFileWriter {
22
- readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
23
- readonly writeText: (chunk: string) => Effect.Effect<void>;
22
+ readonly filePath: string;
23
+ readonly writeBytes: (
24
+ chunk: Uint8Array,
25
+ ) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
26
+ readonly writeText: (
27
+ chunk: string,
28
+ ) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
29
+}
30
+
31
+class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
32
+ "DesktopLogFileWriterConfigurationError",
33
+ {
34
+ option: Schema.Literals(["maxBytes", "maxFiles"]),
35
+ value: Schema.Number,
36
+ },
37
+) {
38
+ override get message(): string {
39
+ return `${this.option} must be >= 1 (received ${this.value})`;
40
+ }
41
+}
42
+
43
+class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
44
+ "DesktopLogFileWriterRecoveryError",
45
+ {
46
+ logFilePath: Schema.String,
47
+ cause: Schema.Defect(),
48
+ recoveryCause: Schema.Defect(),
49
+ },
50
+) {
51
+ override get message(): string {
52
+ return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
53
+ }
54
+}
55
+
56
+export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
57
+ "DesktopBackendOutputLogSetupError",
58
+ {
59
+ logFilePath: Schema.String,
60
+ cause: Schema.Defect(),
61
+ },
62
+) {
63
+ override get message(): string {
64
+ return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
65
+ }
66
+}
67
+
68
+export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
69
+ "DesktopBackendOutputLogWriteError",
70
+ {
71
+ operation: Schema.Literals(["encode-record", "write-record"]),
72
+ logFilePath: Schema.String,
73
+ cause: Schema.Defect(),
74
+ },
75
+) {
76
+ override get message(): string {
77
+ return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
78
+ }
79
+}
80
+
81
+export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
82
+ "DesktopBackendConsoleWriteError",
83
+ {
84
+ streamName: Schema.Literals(["stdout", "stderr"]),
85
+ cause: Schema.Defect(),
86
+ },
87
+) {
88
+ override get message(): string {
89
+ return `Failed to mirror desktop backend output to ${this.streamName}.`;
90
+ }
91
}
92
93
export class DesktopBackendOutputLog extends Context.Service<
@@ -37,18 +104,6 @@ export class DesktopBackendOutputLog extends Context.Service<
104
}
105
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
106
40
-class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
41
- "DesktopLogFileWriterConfigurationError",
42
- {
43
- option: Schema.Literals(["maxBytes", "maxFiles"]),
44
- value: Schema.Number,
45
- },
46
-) {
47
- override get message(): string {
48
- return `${this.option} must be >= 1 (received ${this.value})`;
49
- }
50
-}
51
-
107
type DesktopLogFileWriterError =
108
| DesktopLogFileWriterConfigurationError
109
| PlatformError.PlatformError;
@@ -85,10 +140,13 @@ const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").t
140
const refreshFileSize = (
141
fileSystem: FileSystem.FileSystem,
142
filePath: string,
88
-): Effect.Effect<number, never> =>
143
+): Effect.Effect<number, PlatformError.PlatformError> =>
144
fileSystem.stat(filePath).pipe(
145
Effect.map((stat) => Number(stat.size)),
91
- Effect.orElseSucceed(() => 0),
146
+ Effect.catchTags({
147
+ PlatformError: (error) =>
148
+ error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
149
+ }),
150
);
151
152
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
@@ -126,41 +184,52 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
184
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
185
const mutex = yield* Semaphore.make(1);
186
187
+ const recoverCurrentSize = (
188
+ cause: PlatformError.PlatformError,
189
+ ): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
190
+ refreshFileSize(fileSystem, input.filePath).pipe(
191
+ Effect.matchEffect({
192
+ onFailure: (recoveryCause) =>
193
+ Effect.fail(
194
+ new DesktopLogFileWriterRecoveryError({
195
+ logFilePath: input.filePath,
196
+ cause,
197
+ recoveryCause,
198
+ }),
199
+ ),
200
+ onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
201
+ }),
202
+ );
203
+
204
const pruneOverflowBackups = Effect.gen(function* () {
130
- const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
205
+ const entries = yield* fileSystem.readDirectory(directory);
206
for (const entry of entries) {
207
if (!entry.startsWith(`${baseName}.`)) continue;
208
const suffix = Number(entry.slice(baseName.length + 1));
209
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
135
- yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
210
+ yield* fileSystem.remove(path.join(directory, entry), { force: true });
211
}
212
});
213
214
const rotate = Effect.gen(function* () {
140
- yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
215
+ yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
216
for (let index = maxFiles - 1; index >= 1; index -= 1) {
217
const source = withSuffix(index);
143
- const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
218
+ const sourceExists = yield* fileSystem.exists(source);
219
if (sourceExists) {
220
yield* fileSystem.rename(source, withSuffix(index + 1));
221
}
222
}
148
- const currentExists = yield* fileSystem
149
- .exists(input.filePath)
150
- .pipe(Effect.orElseSucceed(() => false));
223
+ const currentExists = yield* fileSystem.exists(input.filePath);
224
if (currentExists) {
225
yield* fileSystem.rename(input.filePath, withSuffix(1));
226
}
227
yield* Ref.set(currentSize, 0);
155
- }).pipe(
156
- Effect.catch(() =>
157
- refreshFileSize(fileSystem, input.filePath).pipe(
158
- Effect.flatMap((size) => Ref.set(currentSize, size)),
159
- ),
160
- ),
161
- );
228
+ });
229
163
- const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
230
+ const writeBytes = (
231
+ chunk: Uint8Array,
232
+ ): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
233
if (chunk.byteLength === 0) return Effect.void;
234
235
return mutex.withPermits(1)(
@@ -178,11 +247,9 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
247
yield* rotate;
248
}
249
}).pipe(
181
- Effect.catch(() =>
182
- refreshFileSize(fileSystem, input.filePath).pipe(
183
- Effect.flatMap((size) => Ref.set(currentSize, size)),
184
- ),
185
- ),
250
+ Effect.catchTags({
251
+ PlatformError: recoverCurrentSize,
252
+ }),
253
),
254
);
255
};
@@ -190,6 +257,7 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
257
yield* pruneOverflowBackups;
258
259
return {
260
+ filePath: input.filePath,
261
writeBytes,
262
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
263
} satisfies RotatingLogFileWriter;
@@ -199,10 +267,17 @@ const writeDevelopmentConsoleOutput = (
267
streamName: "stdout" | "stderr",
268
chunk: Uint8Array,
269
): Effect.Effect<void> =>
202
- Effect.sync(() => {
203
- const output = streamName === "stderr" ? process.stderr : process.stdout;
204
- output.write(chunk);
205
- }).pipe(Effect.ignore);
270
+ Effect.try({
271
+ try: () => {
272
+ const output = streamName === "stderr" ? process.stderr : process.stdout;
273
+ output.write(chunk);
274
+ },
275
+ catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
276
+ }).pipe(
277
+ Effect.catchTags({
278
+ DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
279
+ }),
280
+ );
281
282
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
283
function* (
@@ -222,17 +297,47 @@ const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackend
297
annotations: input.annotations,
298
spans: {},
299
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
225
- });
226
- yield* logFile.writeText(`${encoded}\n`);
227
- }).pipe(Effect.ignore({ log: true }));
300
+ }).pipe(
301
+ Effect.mapError(
302
+ (cause) =>
303
+ new DesktopBackendOutputLogWriteError({
304
+ operation: "encode-record",
305
+ logFilePath: logFile.filePath,
306
+ cause,
307
+ }),
308
+ ),
309
+ );
310
+ yield* logFile.writeText(`${encoded}\n`).pipe(
311
+ Effect.mapError(
312
+ (cause) =>
313
+ new DesktopBackendOutputLogWriteError({
314
+ operation: "write-record",
315
+ logFilePath: logFile.filePath,
316
+ cause,
317
+ }),
318
+ ),
319
+ );
320
+ }).pipe(
321
+ Effect.catchTags({
322
+ DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
323
+ }),
324
+ );
325
},
326
);
327
231
-const make = Effect.gen(function* () {
328
+export const make = Effect.gen(function* () {
329
const environment = yield* DesktopEnvironment.DesktopEnvironment;
330
+ const logFilePath = environment.path.join(environment.logDir, "server-child.log");
331
const writer = yield* makeRotatingLogFileWriter({
234
- filePath: environment.path.join(environment.logDir, "server-child.log"),
235
- }).pipe(Effect.option);
332
+ filePath: logFilePath,
333
+ }).pipe(
334
+ Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
335
+ Effect.map(Option.some),
336
+ Effect.catchTags({
337
+ DesktopBackendOutputLogSetupError: (error) =>
338
+ Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
339
+ }),
340
+ );
341
342
const service = Option.match(writer, {
343
onNone: () => DesktopBackendOutputLogNoop,