Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 83a00449c8 Add React Scan composer menu recordings
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:29:20 +00:00
Cursor AgentandJulius Marminge 669d274bf9 Format composer menu highlight helper
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:26:07 +00:00
Cursor AgentandJulius Marminge 3666f713e4 Avoid composer menu highlight sync effect
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:24:40 +00:00
8 changed files with 169 additions and 189 deletions

No files matched your search

+69 -87
View File
@@ -14,32 +14,23 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
const TraceRecordLine = Schema.Struct({
name: Schema.optional(Schema.Unknown),
traceId: Schema.optional(Schema.Unknown),
spanId: Schema.optional(Schema.Unknown),
startTimeUnixNano: Schema.optional(Schema.Unknown),
endTimeUnixNano: Schema.optional(Schema.Unknown),
durationMs: Schema.optional(Schema.Unknown),
exit: Schema.optional(Schema.Unknown),
events: Schema.optional(Schema.Array(Schema.Unknown)),
});
interface TraceRecordLike {
readonly name?: unknown;
readonly traceId?: unknown;
readonly spanId?: unknown;
readonly startTimeUnixNano?: unknown;
readonly endTimeUnixNano?: unknown;
readonly durationMs?: unknown;
readonly exit?: unknown;
readonly events?: unknown;
}
const TraceEvent = Schema.Struct({
name: Schema.optional(Schema.Unknown),
timeUnixNano: Schema.optional(Schema.Unknown),
attributes: Schema.optional(Schema.Unknown),
});
const TraceEventAttributes = Schema.Record(Schema.String, Schema.Unknown);
type TraceEventLike = typeof TraceEvent.Type;
const decodeTraceRecordLine = Schema.decodeUnknownOption(Schema.fromJsonString(TraceRecordLine));
const decodeTraceEvent = Schema.decodeUnknownOption(TraceEvent);
const decodeTraceEventAttributes = Schema.decodeUnknownOption(TraceEventAttributes);
interface TraceEventLike {
readonly name?: unknown;
readonly timeUnixNano?: unknown;
readonly attributes?: unknown;
}
export interface TraceDiagnosticsOptions {
readonly traceFilePath: string;
@@ -83,42 +74,47 @@ function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyA
return [...backups, traceFilePath];
}
function isRecordObject(value: unknown): value is Readonly<Record<string, unknown>> {
function isRecordObject(value: unknown): value is TraceRecordLike {
return typeof value === "object" && value !== null;
}
function toStringValue(value: unknown): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
function toStringValue(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
function toNumberValue(value: unknown): Option.Option<number> {
return typeof value === "number" && Number.isFinite(value) ? Option.some(value) : Option.none();
function toNumberValue(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function unixNanoToDateTime(value: unknown): Option.Option<DateTime.Utc> {
function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
const text = toStringValue(value);
if (Option.isNone(text)) return Option.none();
if (!text) return null;
try {
const millis = Number(BigInt(text.value) / 1_000_000n);
return DateTime.make(millis);
const millis = Number(BigInt(text) / 1_000_000n);
return Option.getOrNull(DateTime.make(millis));
} catch {
return Option.none();
return null;
}
}
function readExitTag(exit: unknown): Option.Option<string> {
if (!isRecordObject(exit) || !("_tag" in exit)) return Option.none();
function readExitTag(exit: unknown): string | null {
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
return toStringValue(exit._tag);
}
function readExitCause(exit: unknown): string {
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
const cause = toStringValue(exit.cause);
return Option.isSome(cause) ? cause.value.trim() : "Failure";
return toStringValue(exit.cause)?.trim() ?? "Failure";
}
function isTraceEvent(value: unknown): value is TraceEventLike {
return typeof value === "object" && value !== null;
}
function readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {
return Option.getOrElse(decodeTraceEventAttributes(event.attributes), () => ({}));
return typeof event.attributes === "object" && event.attributes !== null
? (event.attributes as Readonly<Record<string, unknown>>)
: {};
}
function makeEmptyDiagnostics(input: {
@@ -203,8 +199,8 @@ export function aggregateTraceDiagnostics(
let failureCount = 0;
let interruptionCount = 0;
let slowSpanCount = 0;
let firstSpanAt = Option.none<DateTime.Utc>();
let lastSpanAt = Option.none<DateTime.Utc>();
let firstSpanAt: DateTime.Utc | null = null;
let lastSpanAt: DateTime.Utc | null = null;
const spansByName = new Map<
string,
@@ -221,50 +217,42 @@ export function aggregateTraceDiagnostics(
for (const line of lines) {
if (line.trim().length === 0) continue;
const parsedOption = decodeTraceRecordLine(line);
if (Option.isNone(parsedOption)) {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
parseErrorCount += 1;
continue;
}
const parsed = parsedOption.value;
const nameOption = toStringValue(parsed.name);
const traceIdOption = toStringValue(parsed.traceId);
const spanIdOption = toStringValue(parsed.spanId);
const durationMsOption = toNumberValue(parsed.durationMs);
const endedAtOption = unixNanoToDateTime(parsed.endTimeUnixNano);
if (!isRecordObject(parsed)) {
parseErrorCount += 1;
continue;
}
const name = toStringValue(parsed.name);
const traceId = toStringValue(parsed.traceId);
const spanId = toStringValue(parsed.spanId);
const durationMs = toNumberValue(parsed.durationMs);
const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
if (
Option.isNone(nameOption) ||
Option.isNone(traceIdOption) ||
Option.isNone(spanIdOption) ||
Option.isNone(durationMsOption) ||
Option.isNone(endedAtOption)
) {
if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
parseErrorCount += 1;
continue;
}
const name = nameOption.value;
const traceId = traceIdOption.value;
const spanId = spanIdOption.value;
const durationMs = durationMsOption.value;
const endedAt = endedAtOption.value;
recordCount += 1;
if (
Option.isSome(startedAt) &&
(Option.isNone(firstSpanAt) || DateTime.isLessThan(startedAt.value, firstSpanAt.value))
) {
firstSpanAt = startedAt;
}
if (Option.isNone(lastSpanAt) || DateTime.isGreaterThan(endedAt, lastSpanAt.value)) {
lastSpanAt = Option.some(endedAt);
}
firstSpanAt =
startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
? startedAt
: firstSpanAt;
lastSpanAt =
lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
const exitTag = readExitTag(parsed.exit);
const isFailure = Option.isSome(exitTag) && exitTag.value === "Failure";
const isInterrupted = Option.isSome(exitTag) && exitTag.value === "Interrupted";
const isFailure = exitTag === "Failure";
const isInterrupted = exitTag === "Interrupted";
if (isFailure) failureCount += 1;
if (isInterrupted) interruptionCount += 1;
@@ -304,14 +292,11 @@ export function aggregateTraceDiagnostics(
}
if (Array.isArray(parsed.events)) {
for (const rawTraceEvent of parsed.events) {
const eventOption = decodeTraceEvent(rawTraceEvent);
if (Option.isNone(eventOption)) continue;
const event = eventOption.value;
const attributes = readEventAttributes(event);
const levelOption = toStringValue(attributes["effect.logLevel"]);
if (Option.isNone(levelOption)) continue;
const level = levelOption.value;
for (const rawEvent of parsed.events) {
if (!isTraceEvent(rawEvent)) continue;
const attributes = readEventAttributes(rawEvent);
const level = toStringValue(attributes["effect.logLevel"]);
if (!level) continue;
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
const normalizedLevel = level.toLowerCase();
@@ -324,11 +309,8 @@ export function aggregateTraceDiagnostics(
continue;
}
const seenAt = Option.getOrElse(unixNanoToDateTime(event.timeUnixNano), () => endedAt);
const message = Option.getOrElse(
Option.map(toStringValue(event.name), (value) => value.trim()),
() => "Log event",
);
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
latestWarningAndErrorLogs.push({
spanName: name,
level,
@@ -360,8 +342,8 @@ export function aggregateTraceDiagnostics(
readAt,
recordCount,
parseErrorCount,
firstSpanAt,
lastSpanAt,
firstSpanAt: Option.fromNullishOr(firstSpanAt),
lastSpanAt: Option.fromNullishOr(lastSpanAt),
failureCount,
interruptionCount,
slowSpanThresholdMs,
+1 -53
View File
@@ -4,12 +4,11 @@ import path from "node:path";
import { spawnSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/unstable/process";
import { expect } from "vitest";
@@ -189,22 +188,6 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
});
}
function makeDeterministicRandomService(seed = 0x1234_5678): {
nextIntUnsafe: () => number;
nextDoubleUnsafe: () => number;
} {
let state = seed >>> 0;
const nextIntUnsafe = (): number => {
state = (Math.imul(1_664_525, state) + 1_013_904_223) >>> 0;
return state;
};
return {
nextIntUnsafe,
nextDoubleUnsafe: () => nextIntUnsafe() / 0x1_0000_0000,
};
}
function isGitHubCliError(error: unknown): error is GitHubCliError {
return (
typeof error === "object" &&
@@ -3230,41 +3213,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("uses Effect Random for implicit progress action ids", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "random-action-id.txt"), "random action id\n");
const { manager } = yield* makeManager();
const events: GitActionProgressEvent[] = [];
const seed = 0x5eed_c0de;
const expectedActionId = yield* Random.nextUUIDv4.pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService(seed)),
);
const result = yield* runStackedAction(
manager,
{
cwd: repoDir,
action: "commit",
},
{
progressReporter: {
publish: (event) =>
Effect.sync(() => {
events.push(event);
}),
},
},
).pipe(Effect.provideService(Random.Random, makeDeterministicRandomService(seed)));
assert.equal(result.commit.status, "created");
assert.isAbove(events.length, 0);
assert.isTrue(events.every((event) => event.actionId === expectedActionId));
}),
);
it.effect("emits ordered progress events for commit hooks", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
+8 -8
View File
@@ -1,3 +1,5 @@
import { randomUUID } from "node:crypto";
import * as Arr from "effect/Array";
import * as Cache from "effect/Cache";
import * as Context from "effect/Context";
@@ -10,7 +12,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Order from "effect/Order";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import {
GitActionProgressEvent,
@@ -535,11 +536,11 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
const serverSettingsService = yield* ServerSettingsService;
const createProgressEmitter = Effect.fn("GitManager.createProgressEmitter")(function* (
const createProgressEmitter = (
input: { cwd: string; action: GitStackedAction },
options?: GitRunStackedActionOptions,
) {
const actionId = options?.actionId ?? (yield* Random.nextUUIDv4);
) => {
const actionId = options?.actionId ?? randomUUID();
const reporter = options?.progressReporter;
const emit = (event: GitActionProgressPayload) =>
@@ -556,7 +557,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
actionId,
emit,
};
});
};
const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")(
function* (
@@ -1300,8 +1301,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
modelSelection,
});
const bodyFileId = yield* Random.nextUUIDv4;
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${bodyFileId}.md`);
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
yield* fileSystem
.writeFileString(bodyFile, generated.body)
.pipe(
@@ -1591,7 +1591,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fn("runStackedAction")(
function* (input, options) {
const progress = yield* createProgressEmitter(input, options);
const progress = createProgressEmitter(input, options);
const currentPhase = yield* Ref.make<Option.Option<GitActionProgressPhase>>(Option.none());
const runAction = Effect.fn("runStackedAction.runAction")(function* (): Effect.fn.Return<
+12 -40
View File
@@ -68,7 +68,10 @@ import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
import {
resolveComposerMenuActiveItemId,
resolveComposerMenuNudgedItemId,
} from "./composerMenuHighlight";
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
import {
getComposerProviderState,
@@ -1134,35 +1137,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
composerTerminalContextsRef.current = composerTerminalContexts;
}, [composerTerminalContexts, composerTerminalContextsRef]);
// ------------------------------------------------------------------
// Composer menu highlight sync
// ------------------------------------------------------------------
useEffect(() => {
if (!composerMenuOpen) {
setComposerHighlightedItemId(null);
setComposerHighlightedSearchKey(null);
return;
}
const nextActiveItemId = resolveComposerMenuActiveItemId({
items: composerMenuItems,
highlightedItemId: composerHighlightedItemId,
currentSearchKey: composerMenuSearchKey,
highlightedSearchKey: composerHighlightedSearchKey,
});
setComposerHighlightedItemId((existing) =>
existing === nextActiveItemId ? existing : nextActiveItemId,
);
setComposerHighlightedSearchKey((existing) =>
existing === composerMenuSearchKey ? existing : composerMenuSearchKey,
);
}, [
composerHighlightedItemId,
composerHighlightedSearchKey,
composerMenuItems,
composerMenuOpen,
composerMenuSearchKey,
]);
const lastSyncedPendingInputRef = useRef<{
requestId: string | null;
questionId: string | null;
@@ -1576,18 +1550,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const nudgeComposerMenuHighlight = useCallback(
(key: "ArrowDown" | "ArrowUp") => {
if (composerMenuItems.length === 0) return;
const highlightedIndex = composerMenuItems.findIndex(
(item) => item.id === composerHighlightedItemId,
setComposerHighlightedItemId(
resolveComposerMenuNudgedItemId({
items: composerMenuItems,
activeItemId: activeComposerMenuItem?.id ?? null,
direction: key === "ArrowDown" ? "next" : "previous",
}),
);
const normalizedIndex =
highlightedIndex >= 0 ? highlightedIndex : key === "ArrowDown" ? -1 : 0;
const offset = key === "ArrowDown" ? 1 : -1;
const nextIndex =
(normalizedIndex + offset + composerMenuItems.length) % composerMenuItems.length;
const nextItem = composerMenuItems[nextIndex];
setComposerHighlightedItemId(nextItem?.id ?? null);
setComposerHighlightedSearchKey(composerMenuSearchKey);
},
[composerHighlightedItemId, composerMenuItems],
[activeComposerMenuItem?.id, composerMenuItems, composerMenuSearchKey],
);
const blurMobileComposerAfterSend = useCallback(() => {
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
import {
resolveComposerMenuActiveItemId,
resolveComposerMenuNudgedItemId,
} from "./composerMenuHighlight";
describe("resolveComposerMenuActiveItemId", () => {
const items = [{ id: "top" }, { id: "second" }, { id: "third" }] as const;
@@ -49,3 +52,61 @@ describe("resolveComposerMenuActiveItemId", () => {
).toBe("top");
});
});
describe("resolveComposerMenuNudgedItemId", () => {
const items = [{ id: "top" }, { id: "second" }, { id: "third" }] as const;
it("moves from the active item", () => {
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "second",
direction: "next",
}),
).toBe("third");
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "second",
direction: "previous",
}),
).toBe("top");
});
it("wraps around at either edge", () => {
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "third",
direction: "next",
}),
).toBe("top");
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "top",
direction: "previous",
}),
).toBe("third");
});
it("starts from the first visible item when active state is stale", () => {
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "missing",
direction: "next",
}),
).toBe("top");
expect(
resolveComposerMenuNudgedItemId({
items,
activeItemId: "missing",
direction: "previous",
}),
).toBe("third");
});
});
@@ -18,3 +18,20 @@ export function resolveComposerMenuActiveItemId(input: {
return input.items[0]?.id ?? null;
}
export function resolveComposerMenuNudgedItemId(input: {
items: ReadonlyArray<{ id: string }>;
activeItemId: string | null;
direction: "next" | "previous";
}): string | null {
if (input.items.length === 0) {
return null;
}
const activeIndex = input.items.findIndex((item) => item.id === input.activeItemId);
const normalizedIndex = activeIndex >= 0 ? activeIndex : input.direction === "next" ? -1 : 0;
const offset = input.direction === "next" ? 1 : -1;
const nextIndex = (normalizedIndex + offset + input.items.length) % input.items.length;
return input.items[nextIndex]?.id ?? null;
}