The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; |
| 2 | import desktopPackageJson from "../../package.json" with { type: "json" }; |
| 3 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 4 | import { assert, describe, it } from "@effect/vitest"; |
| 5 | import * as ConfigProvider from "effect/ConfigProvider"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as FileSystem from "effect/FileSystem"; |
| 8 | import * as Layer from "effect/Layer"; |
| 9 | import * as Schema from "effect/Schema"; |
| 10 | import * as HttpClient from "effect/http/HttpClient"; |
| 11 | import * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 12 | |
| 13 | import * as DesktopConfig from "./DesktopConfig.ts"; |
| 14 | import * as DesktopEnvironment from "./DesktopEnvironment.ts"; |
| 15 | import * as DesktopObservability from "./DesktopObservability.ts"; |
| 16 | |
| 17 | const DesktopBackendChildLogRecord = Schema.Struct({ |
| 18 | message: Schema.String, |
| 19 | level: Schema.Literals(["INFO", "ERROR"]), |
| 20 | timestamp: Schema.String, |
| 21 | annotations: Schema.Record(Schema.String, Schema.Unknown), |
| 22 | spans: Schema.Record(Schema.String, Schema.Unknown), |
| 23 | fiberId: Schema.String, |
| 24 | }); |
| 25 | |
| 26 | const decodeDesktopBackendChildLogRecord = Schema.decodeEffect( |
| 27 | Schema.fromJsonString(DesktopBackendChildLogRecord), |
| 28 | ); |
| 29 | |
| 30 | const TraceRecordLine = Schema.Struct({ |
| 31 | name: Schema.String, |
| 32 | attributes: Schema.Record(Schema.String, Schema.Unknown), |
| 33 | events: Schema.Array( |
| 34 | Schema.Struct({ |
| 35 | name: Schema.String, |
| 36 | attributes: Schema.Record(Schema.String, Schema.Unknown), |
| 37 | }), |
| 38 | ), |
| 39 | }); |
| 40 | |
| 41 | const decodeTraceRecordLine = Schema.decodeUnknownSync(Schema.fromJsonString(TraceRecordLine)); |
| 42 | |
| 43 | const environmentInput = (baseDir: string) => |
| 44 | ({ |
| 45 | dirname: "/repo/apps/desktop/dist-electron", |
| 46 | homeDirectory: baseDir, |
| 47 | platform: "darwin", |
| 48 | processArch: "arm64", |
| 49 | appVersion: "1.2.3", |
| 50 | appPath: "/repo", |
| 51 | isPackaged: false, |
| 52 | resourcesPath: "/repo/resources", |
| 53 | runningUnderArm64Translation: false, |
| 54 | }) satisfies DesktopEnvironment.MakeDesktopEnvironmentInput; |
| 55 | |
| 56 | const layerEnvironmentFor = ( |
| 57 | baseDir: string, |
| 58 | isDevelopment = true, |
| 59 | env: Readonly<Record<string, string | undefined>> = {}, |
| 60 | ) => |
| 61 | DesktopEnvironment.layer(environmentInput(baseDir)).pipe( |
| 62 | Layer.provide( |
| 63 | Layer.mergeAll( |
| 64 | NodeServices.layer, |
| 65 | DesktopConfig.layerTest({ |
| 66 | T3CODE_HOME: baseDir, |
| 67 | VITE_DEV_SERVER_URL: isDevelopment ? "http://127.0.0.1:5733" : undefined, |
| 68 | ...env, |
| 69 | }), |
| 70 | ), |
| 71 | ), |
| 72 | ); |
| 73 | |
| 74 | interface ExportedRequest { |
| 75 | readonly url: string; |
| 76 | readonly headers: Readonly<Record<string, string>>; |
| 77 | readonly body: string; |
| 78 | } |
| 79 | |
| 80 | const layerCollector = (requests: Array<ExportedRequest>) => |
| 81 | Layer.succeed( |
| 82 | HttpClient.HttpClient, |
| 83 | HttpClient.make((request) => |
| 84 | Effect.sync(() => { |
| 85 | requests.push({ |
| 86 | url: request.url, |
| 87 | headers: request.headers, |
| 88 | body: |
| 89 | request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "", |
| 90 | }); |
| 91 | return HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })); |
| 92 | }), |
| 93 | ), |
| 94 | ); |
| 95 | |
| 96 | // A developer's own OTEL_* variables would otherwise pick the endpoints. |
| 97 | const layerEmptyEnv = ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })); |
| 98 | |
| 99 | const encodeObservabilitySettingsFile = Schema.encodeSync( |
| 100 | Schema.fromJsonString( |
| 101 | Schema.Struct({ observability: Schema.Record(Schema.String, Schema.String) }), |
| 102 | ), |
| 103 | ); |
| 104 | |
| 105 | const writeObservabilitySettings = Effect.fn(function* ( |
| 106 | environmentLayer: ReturnType<typeof layerEnvironmentFor>, |
| 107 | observability: Readonly<Record<string, string>>, |
| 108 | ) { |
| 109 | const fileSystem = yield* FileSystem.FileSystem; |
| 110 | const { path, serverSettingsPath } = yield* Effect.gen(function* () { |
| 111 | const environment = yield* DesktopEnvironment.DesktopEnvironment; |
| 112 | return environment; |
| 113 | }).pipe(Effect.provide(environmentLayer)); |
| 114 | yield* fileSystem.makeDirectory(path.dirname(serverSettingsPath), { recursive: true }); |
| 115 | yield* fileSystem.writeFileString( |
| 116 | serverSettingsPath, |
| 117 | encodeObservabilitySettingsFile({ observability }), |
| 118 | ); |
| 119 | }); |
| 120 | |
| 121 | describe("DesktopObservability", () => { |
| 122 | it.effect("buffers backend child output and persists it only when a failure is reported", () => |
| 123 | Effect.gen(function* () { |
| 124 | const fileSystem = yield* FileSystem.FileSystem; |
| 125 | const baseDir = yield* fileSystem.makeTempDirectoryScoped({ |
| 126 | prefix: "t3-desktop-backend-output-log-test-", |
| 127 | }); |
| 128 | const layerEnvironment = layerEnvironmentFor(baseDir, false); |
| 129 | const logPath = yield* Effect.gen(function* () { |
| 130 | const environment = yield* DesktopEnvironment.DesktopEnvironment; |
| 131 | return environment.path.join(environment.logDir, "server-child.log"); |
| 132 | }).pipe(Effect.provide(layerEnvironment)); |
| 133 | const tracePath = yield* Effect.gen(function* () { |
| 134 | const environment = yield* DesktopEnvironment.DesktopEnvironment; |
| 135 | return environment.path.join(environment.logDir, "desktop.trace.ndjson"); |
| 136 | }).pipe(Effect.provide(layerEnvironment)); |
| 137 | |
| 138 | yield* Effect.gen(function* () { |
| 139 | const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory; |
| 140 | const outputLog = yield* factory.forInstance("primary"); |
| 141 | yield* outputLog.beginSession({ |
| 142 | details: "pid=123 port=3773 cwd=/repo", |
| 143 | }); |
| 144 | yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("hello server\n")); |
| 145 | assert.isFalse(yield* fileSystem.exists(logPath)); |
| 146 | yield* outputLog.persistFailure({ details: "code=1" }); |
| 147 | yield* outputLog.beginSession({ details: "pid=456" }); |
| 148 | yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("normal shutdown\n")); |
| 149 | yield* outputLog.discardSession; |
| 150 | }).pipe( |
| 151 | Effect.annotateLogs({ runId: "test-run" }), |
| 152 | Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), |
| 153 | ); |
| 154 | |
| 155 | const log = yield* fileSystem.readFileString(logPath); |
| 156 | const lines = log.trimEnd().split("\n"); |
| 157 | const start = yield* decodeDesktopBackendChildLogRecord(lines[0] ?? ""); |
| 158 | const output = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? ""); |
| 159 | const end = yield* decodeDesktopBackendChildLogRecord(lines[2] ?? ""); |
| 160 | |
| 161 | assert.equal(lines.length, 3); |
| 162 | assert.equal(start.message, "backend child process failure output start"); |
| 163 | assert.equal(start.level, "ERROR"); |
| 164 | assert.equal(start.annotations.component, "desktop-backend-child"); |
| 165 | assert.equal(start.annotations.runId, "test-run"); |
| 166 | assert.equal(start.annotations.instanceId, "primary"); |
| 167 | assert.equal(start.annotations.phase, "START"); |
| 168 | assert.equal(start.annotations.details, "pid=123 port=3773 cwd=/repo"); |
| 169 | |
| 170 | assert.equal(output.message, "backend child process output"); |
| 171 | assert.equal(output.level, "INFO"); |
| 172 | assert.equal(output.annotations.component, "desktop-backend-child"); |
| 173 | assert.equal(output.annotations.runId, "test-run"); |
| 174 | assert.equal(output.annotations.instanceId, "primary"); |
| 175 | assert.equal(output.annotations.stream, "stdout"); |
| 176 | assert.equal(output.annotations.text, "hello server\n"); |
| 177 | |
| 178 | assert.equal(end.message, "backend child process failure output end"); |
| 179 | assert.equal(end.level, "ERROR"); |
| 180 | assert.equal(end.annotations.instanceId, "primary"); |
| 181 | assert.equal(end.annotations.phase, "END"); |
| 182 | assert.equal(end.annotations.details, "code=1"); |
| 183 | |
| 184 | const traceRecords = (yield* fileSystem.readFileString(tracePath)) |
| 185 | .trim() |
| 186 | .split("\n") |
| 187 | .filter((line) => line.length > 0) |
| 188 | .map((line) => decodeTraceRecordLine(line)); |
| 189 | assert.isFalse( |
| 190 | traceRecords.some( |
| 191 | (record) => record.name === "desktop.observability.backendOutput.writeOutputChunk", |
| 192 | ), |
| 193 | ); |
| 194 | }).pipe( |
| 195 | Effect.scoped, |
| 196 | Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)), |
| 197 | ), |
| 198 | ); |
| 199 | |
| 200 | it.effect("keeps buffering output after a non-terminal failure snapshot", () => |
| 201 | Effect.gen(function* () { |
| 202 | const fileSystem = yield* FileSystem.FileSystem; |
| 203 | const baseDir = yield* fileSystem.makeTempDirectoryScoped({ |
| 204 | prefix: "t3-desktop-backend-output-snapshot-test-", |
| 205 | }); |
| 206 | const layerEnvironment = layerEnvironmentFor(baseDir, false); |
| 207 | const logPath = yield* Effect.gen(function* () { |
| 208 | const environment = yield* DesktopEnvironment.DesktopEnvironment; |
| 209 | return environment.path.join(environment.logDir, "server-child.log"); |
| 210 | }).pipe(Effect.provide(layerEnvironment)); |
| 211 | |
| 212 | yield* Effect.gen(function* () { |
| 213 | const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory; |
| 214 | const outputLog = yield* factory.forInstance("primary"); |
| 215 | yield* outputLog.beginSession({ details: "pid=123" }); |
| 216 | yield* outputLog.writeOutputChunk("stdout", new TextEncoder().encode("before timeout\n")); |
| 217 | yield* outputLog.persistFailureSnapshot({ details: "readiness timeout" }); |
| 218 | yield* outputLog.writeOutputChunk("stderr", new TextEncoder().encode("after timeout\n")); |
| 219 | yield* outputLog.persistFailure({ details: "code=1" }); |
| 220 | }).pipe( |
| 221 | Effect.annotateLogs({ runId: "test-run" }), |
| 222 | Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), |
| 223 | ); |
| 224 | |
| 225 | const records = yield* Effect.forEach( |
| 226 | (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"), |
| 227 | (line) => decodeDesktopBackendChildLogRecord(line), |
| 228 | ); |
| 229 | assert.equal( |
| 230 | records.some((record) => record.annotations.text === "after timeout\n"), |
| 231 | true, |
| 232 | ); |
| 233 | assert.equal(records.at(-1)?.annotations.details, "code=1"); |
| 234 | }).pipe( |
| 235 | Effect.scoped, |
| 236 | Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)), |
| 237 | ), |
| 238 | ); |
| 239 | |
| 240 | it.effect("retains only the last mebibyte of backend child output", () => |
| 241 | Effect.gen(function* () { |
| 242 | const fileSystem = yield* FileSystem.FileSystem; |
| 243 | const baseDir = yield* fileSystem.makeTempDirectoryScoped({ |
| 244 | prefix: "t3-desktop-backend-output-bound-test-", |
| 245 | }); |
| 246 | const layerEnvironment = layerEnvironmentFor(baseDir, false); |
| 247 | const logPath = yield* Effect.gen(function* () { |
| 248 | const environment = yield* DesktopEnvironment.DesktopEnvironment; |
| 249 | return environment.path.join(environment.logDir, "server-child.log"); |
| 250 | }).pipe(Effect.provide(layerEnvironment)); |
| 251 | const maxBufferedBytes = 1024 * 1024; |
| 252 | const discardedPrefixBytes = 128; |
| 253 | const output = new Uint8Array(maxBufferedBytes + discardedPrefixBytes); |
| 254 | output.fill("x".charCodeAt(0)); |
| 255 | output.fill("y".charCodeAt(0), 0, discardedPrefixBytes); |
| 256 | |
| 257 | yield* Effect.scoped( |
| 258 | Effect.gen(function* () { |
| 259 | const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory; |
| 260 | const outputLog = yield* factory.forInstance("primary"); |
| 261 | yield* outputLog.beginSession({ details: "pid=123" }); |
| 262 | yield* outputLog.writeOutputChunk("stderr", output); |
| 263 | yield* outputLog.persistFailure({ details: "code=1" }); |
| 264 | }).pipe( |
| 265 | Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), |
| 266 | ), |
| 267 | ); |
| 268 | |
| 269 | const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"); |
| 270 | const record = yield* decodeDesktopBackendChildLogRecord(lines[1] ?? ""); |
| 271 | const text = record.annotations.text; |
| 272 | assert.equal(typeof text, "string"); |
| 273 | if (typeof text !== "string") { |
| 274 | return; |
| 275 | } |
| 276 | assert.equal(new TextEncoder().encode(text).byteLength, maxBufferedBytes); |
| 277 | assert.isFalse(text.includes("y")); |
| 278 | }).pipe( |
| 279 | Effect.scoped, |
| 280 | Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)), |
| 281 | ), |
| 282 | ); |
| 283 | |
| 284 | it.effect("startup prunes only canonical rotation suffixes", () => |
| 285 | Effect.gen(function* () { |
| 286 | const fileSystem = yield* FileSystem.FileSystem; |
| 287 | const directory = yield* fileSystem.makeTempDirectoryScoped({ |
| 288 | prefix: "t3-desktop-rotating-prune-test-", |
| 289 | }); |
| 290 | const filePath = `${directory}/server-child.log`; |
| 291 | const retained = ["1", "3", "04", "4.0", "4e0", "0x4", "+4", "notes"]; |
| 292 | for (const suffix of [...retained, "4", "50"]) { |
| 293 | yield* fileSystem.writeFileString(`${filePath}.${suffix}`, suffix); |
| 294 | } |
| 295 | |
| 296 | yield* DesktopObservability.makeRotatingLogFileWriter({ filePath, maxFiles: 3 }); |
| 297 | |
| 298 | assert.deepEqual( |
| 299 | (yield* fileSystem.readDirectory(directory)).sort(), |
| 300 | retained.map((suffix) => `server-child.log.${suffix}`).sort(), |
| 301 | ); |
| 302 | }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), |
| 303 | ); |
| 304 | |
| 305 | it.effect("stops every export when the OpenTelemetry SDK is disabled", () => { |
| 306 | const requests: Array<ExportedRequest> = []; |
| 307 | return Effect.gen(function* () { |
| 308 | const fileSystem = yield* FileSystem.FileSystem; |
| 309 | const baseDir = yield* fileSystem.makeTempDirectoryScoped({ |
| 310 | prefix: "t3-desktop-observability-test-", |
| 311 | }); |
| 312 | const layerEnvironment = layerEnvironmentFor(baseDir); |
| 313 | yield* writeObservabilitySettings(layerEnvironment, { |
| 314 | otlpTracesUrl: "https://settings.example.com/v1/traces", |
| 315 | otlpLogsUrl: "https://settings.example.com/v1/logs", |
| 316 | }); |
| 317 | |
| 318 | yield* Effect.scoped( |
| 319 | Effect.logInfo("desktop log stays local when disabled").pipe( |
| 320 | Effect.withSpan("desktop-disabled-test"), |
| 321 | Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), |
| 322 | ), |
| 323 | ); |
| 324 | |
| 325 | assert.lengthOf(requests, 0); |
| 326 | }).pipe( |
| 327 | Effect.scoped, |
| 328 | Effect.provide( |
| 329 | Layer.mergeAll( |
| 330 | NodeServices.layer, |
| 331 | layerCollector(requests), |
| 332 | ConfigProvider.layer(ConfigProvider.fromEnv({ env: { OTEL_SDK_DISABLED: "true" } })), |
| 333 | ), |
| 334 | ), |
| 335 | ); |
| 336 | }); |
| 337 | |
| 338 | it.effect("reports the app's own version for an unpackaged desktop run", () => { |
| 339 | const requests: Array<ExportedRequest> = []; |
| 340 | return Effect.gen(function* () { |
| 341 | const fileSystem = yield* FileSystem.FileSystem; |
| 342 | const baseDir = yield* fileSystem.makeTempDirectoryScoped({ |
| 343 | prefix: "t3-desktop-observability-test-", |
| 344 | }); |
| 345 | const layerEnvironment = layerEnvironmentFor(baseDir); |
| 346 | yield* writeObservabilitySettings(layerEnvironment, { |
| 347 | otlpLogsUrl: "https://settings.example.com/v1/logs", |
| 348 | }); |
| 349 | |
| 350 | yield* Effect.scoped( |
| 351 | Effect.logInfo("desktop resource under test").pipe( |
| 352 | Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), |
| 353 | ), |
| 354 | ); |
| 355 | |
| 356 | const body = requests.map((request) => request.body).join("\n"); |
| 357 | assert.include( |
| 358 | body, |
| 359 | `"key":"service.version","value":{"stringValue":"${desktopPackageJson.version}"}`, |
| 360 | ); |
| 361 | }).pipe( |
| 362 | Effect.scoped, |
| 363 | Effect.provide(Layer.mergeAll(NodeServices.layer, layerCollector(requests), layerEmptyEnv)), |
| 364 | ); |
| 365 | }); |
| 366 | |
| 367 | it.effect("describes the Node runtime and the desktop mode under semantic or t3code keys", () => { |
| 368 | const requests: Array<ExportedRequest> = []; |
| 369 | return Effect.gen(function* () { |
| 370 | const fileSystem = yield* FileSystem.FileSystem; |
| 371 | const baseDir = yield* fileSystem.makeTempDirectoryScoped({ |
| 372 | prefix: "t3-desktop-observability-test-", |
| 373 | }); |
| 374 | const layerEnvironment = layerEnvironmentFor(baseDir); |
| 375 | yield* writeObservabilitySettings(layerEnvironment, { |
| 376 | otlpLogsUrl: "https://settings.example.com/v1/logs", |
| 377 | }); |
| 378 | |
| 379 | yield* Effect.scoped( |
| 380 | Effect.logInfo("desktop resource under test").pipe( |
| 381 | Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), |
| 382 | ), |
| 383 | ); |
| 384 | |
| 385 | const body = requests.map((request) => request.body).join("\n"); |
| 386 | assert.include(body, '"key":"process.runtime.name","value":{"stringValue":"nodejs"}'); |
| 387 | assert.include( |
| 388 | body, |
| 389 | `"key":"process.runtime.version","value":{"stringValue":"${process.versions.node}"}`, |
| 390 | ); |
| 391 | assert.include(body, '"key":"t3code.desktop.mode","value":{"stringValue":"development"}'); |
| 392 | assert.notInclude(body, "service.mode"); |
| 393 | }).pipe( |
| 394 | Effect.scoped, |
| 395 | Effect.provide(Layer.mergeAll(NodeServices.layer, layerCollector(requests), layerEmptyEnv)), |
| 396 | ); |
| 397 | }); |
| 398 | }); |