@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 169 lines 6.63 KB
Raw
1 import { describe, expect, it } from "@alchemy.run/test";
2 import * as Console from "effect/Console";
3 import * as Context from "effect/Context";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Logger from "effect/Logger";
7 import * as Option from "effect/Option";
8 import { MinimumLogLevel } from "effect/References";
9 import * as Schedule from "effect/Schedule";
10 import {
11 consoleSettings,
12 lazyRunLog,
13 LogFormatFlag,
14 LogLevelFlag,
15 makeConsoleLogger,
16 } from "@/Cli/GlobalLog.ts";
17 import { emit } from "@/Events.ts";
18 import { makePlainConsoleSink } from "@/Util/ConsoleSink.ts";
19 import { jsonLogger, parseRecord } from "@/Util/LogRecord.ts";
20 import { PlatformServices } from "@/Util/PlatformServices.ts";
21 import { logResourceLine } from "@/Util/ResourceOutput.ts";
22 import { processTrace } from "@/Util/TraceParent.ts";
23
24 /**
25 * The console sink keeps an Info floor by default so the run log stays the
26 * place full Debug detail lives. `--log-level debug` has to lower that floor
27 * for the run, or the flag produces zero terminal output (#1231).
28 */
29 describe("consoleSettings", { tags: ["unit", "local"] }, () => {
30 it("defaults to Info and pretty", () => {
31 expect(consoleSettings(Context.empty())).toMatchObject({ floor: "Info", format: "pretty" });
32 });
33
34 it("reads the parsed flags", () => {
35 const context = Context.empty().pipe(
36 Context.add(LogLevelFlag, Option.some("Debug" as const)),
37 Context.add(LogFormatFlag, Option.some("json" as const)),
38 );
39 expect(consoleSettings(context)).toEqual({ floor: "Debug", format: "json" });
40 });
41 });
42
43 describe("makeConsoleLogger", { tags: ["unit", "local"] }, () => {
44 it.effect("forwards only records at or above the floor", () =>
45 Effect.gen(function* () {
46 const seen: Array<{ level: string; message: unknown }> = [];
47 const probe = Logger.make<unknown, void>((options) => {
48 seen.push({ level: options.logLevel, message: options.message });
49 });
50 const emit = Effect.gen(function* () {
51 yield* Effect.logDebug("debug");
52 yield* Effect.logInfo("info");
53 }).pipe(Effect.provideService(MinimumLogLevel, "Debug"));
54
55 yield* emit.pipe(Effect.provide(Logger.layer([makeConsoleLogger(probe)])));
56 expect(seen.map((r) => r.level)).toEqual(["Info"]);
57
58 seen.length = 0;
59 yield* emit.pipe(
60 Effect.provideService(LogLevelFlag, Option.some("Debug")),
61 Effect.provide(Logger.layer([makeConsoleLogger(probe)])),
62 );
63 expect(seen.map((r) => r.level)).toEqual(["Debug", "Info"]);
64 }),
65 );
66
67 it.effect("prints the time and level prefix without tinting the message", () => {
68 const lines: string[] = [];
69 const console = Object.assign(Object.create(globalThis.console), {
70 log: (...args: unknown[]) => lines.push(args.join(" ")),
71 });
72 return Effect.logInfo("plain message").pipe(
73 Effect.provide(Logger.layer([makeConsoleLogger()])),
74 Effect.provideService(Console.Console, console),
75 Effect.andThen(
76 Effect.sync(() => {
77 expect(lines).toHaveLength(1);
78 expect(lines[0]).toMatch(/^\[\d{2}:\d{2}:\d{2}\.\d{3}\] INFO: plain message$/);
79 expect(lines[0]).not.toContain("\x1b[");
80 }),
81 ),
82 );
83 });
84
85 it.effect("colors the prefix and leaves the message unstyled", () => {
86 const lines: string[] = [];
87 const console = Object.assign(Object.create(globalThis.console), {
88 log: (...args: unknown[]) => lines.push(args.join(" ")),
89 });
90 return Effect.logInfo("plain message").pipe(
91 Effect.provide(Logger.layer([makeConsoleLogger(makePlainConsoleSink({ colors: true }))])),
92 Effect.provideService(Console.Console, console),
93 Effect.andThen(
94 Effect.sync(() => {
95 expect(lines).toHaveLength(1);
96 expect(lines[0]).toMatch(/\x1b\[[\d;]+mINFO\x1b\[0m/);
97 expect(lines[0]).toMatch(/: plain message$/);
98 }),
99 ),
100 );
101 });
102
103 it.effect("keeps child styling only with colors and tags the resource", () => {
104 const render = (colors: boolean) => {
105 const lines: string[] = [];
106 const console = Object.assign(Object.create(globalThis.console), {
107 log: (...args: unknown[]) => lines.push(args.join(" ")),
108 });
109 return logResourceLine("Site/Web", "stdout", "\x1b[32mready\x1b[39m").pipe(
110 Effect.provide(Logger.layer([makePlainConsoleSink({ colors })])),
111 Effect.provideService(Console.Console, console),
112 Effect.as(lines),
113 );
114 };
115 return Effect.gen(function* () {
116 expect((yield* render(true))[0]).toMatch(/\x1b\[32mready\x1b\[39m$/);
117 expect((yield* render(false))[0]).toMatch(/: \[Site\/Web\] ready$/);
118 });
119 });
120
121 it.effect("writes JSON records with the text as the child wrote it", () => {
122 const lines: string[] = [];
123 return logResourceLine("Site/Web", "stderr", "\x1b[31mboom\x1b[39m").pipe(
124 Effect.provide(Logger.layer([jsonLogger((line) => lines.push(line))])),
125 Effect.andThen(
126 Effect.sync(() => {
127 const record = JSON.parse(lines[0]!);
128 expect(record).toEqual({
129 time: expect.any(Number),
130 level: "info",
131 kind: "output",
132 process: "cli",
133 scope: "project",
134 trace: processTrace,
135 attributes: { fqn: "Site/Web" },
136 data: { stream: "stderr", text: "\x1b[31mboom\x1b[39m" },
137 });
138 expect(parseRecord(lines[0]!)).toEqual(record);
139 }),
140 ),
141 );
142 });
143 });
144
145 describe("lazyRunLog", { tags: ["unit", "local"] }, () => {
146 it.live("keeps an event logged while the file is still opening", () =>
147 Effect.gen(function* () {
148 const fs = yield* FileSystem.FileSystem;
149 const dir = yield* fs.makeTempDirectoryScoped();
150 const runLog = yield* lazyRunLog(dir, "run.ndjson", "project");
151 // The first record opens the file in the background, so it is buffered.
152 yield* emit({ type: "plan.phase", phase: "importing-module" }).pipe(
153 Effect.provide(Logger.layer([runLog])),
154 );
155 const file = `${dir}/run.ndjson`;
156 const lines = yield* fs.readFileString(file).pipe(
157 Effect.map((text) => text.trim().split("\n")),
158 // Header plus the record, once the background open has flushed it.
159 Effect.filterOrFail((lines) => lines.length >= 2),
160 Effect.retry({ schedule: Schedule.spaced("20 millis"), times: 50 }),
161 );
162 expect(parseRecord(lines[0]!)).toMatchObject({ kind: "run", scope: "project" });
163 expect(parseRecord(lines[1]!)).toMatchObject({
164 kind: "event",
165 data: { type: "plan.phase", phase: "importing-module" },
166 });
167 }).pipe(Effect.scoped, Effect.provide(PlatformServices)),
168 );
169 });