Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
485 changes: 0 additions & 485 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.fork.test.ts

This file was deleted.

This file was deleted.

4 changes: 4 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6869,6 +6869,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
? {}
: { commandKind: kept.commandKind }),
...(kept?.command === undefined ? {} : { command: kept.command }),
...(kept?.itemId === undefined ? {} : { itemId: kept.itemId }),
...(kept?.sourceThreadId === undefined
? {}
: { sourceThreadId: kept.sourceThreadId }),
startedAt: kept?.startedAt ?? now,
},
] as const;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,13 +305,13 @@ describe("CodexAdapterV2 post-settle continuation", () => {
url: "http://127.0.0.1:43123/mcp",
tool_timeout_sec: 3_900,
http_headers: { Authorization: "Bearer test-token" },
disabled_tools: ["t3_thread_wait"],
disabled_tools: ["t3_thread_wait", "delegate_task"],
},
"mcp_servers.t3-code-direct": {
url: "http://127.0.0.1:43123/mcp",
tool_timeout_sec: 3_900,
http_headers: { Authorization: "Bearer test-token" },
enabled_tools: ["t3_thread_wait"],
enabled_tools: ["t3_thread_wait", "delegate_task"],
omit_tools_from: ["code_mode", "deferred"],
},
},
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,8 +271,8 @@ export class OrchestratorDispatchError extends Schema.TaggedError<OrchestratorDi
) {
override get message(): string {
return (
this.detail ??
(typeof this.cause === "string" ? this.cause : undefined) ??
(this.detail?.trim() ? this.detail : undefined) ??
(typeof this.cause === "string" && this.cause.trim() !== "" ? this.cause : undefined) ??
`Failed to dispatch orchestration command ${this.commandType} (${this.commandId}).`
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,10 @@ function makeLocalCommandHarness(input: {
}),
Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }),
Layer.mock(ProviderAuthService.ProviderAuthService)({ tryHandlePromptCommand }),
Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),
Layer.mock(RunExecutionService.RunExecutionServiceV2)({
forkBaseline: () => Effect.succeed(Effect.void),
startRootRun,
}),
Layer.mock(RuntimePolicy.RuntimePolicyV2)({
resolve: resolveRuntimePolicy,
}),
Expand Down Expand Up @@ -526,6 +529,7 @@ effectIt.effect.each(["cleanup-first", "startup-first"])(
const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-start-" });
const physicalPath = path.join(workspaceRoot, "project", "worktree");
yield* fileSystem.makeDirectory(physicalPath, { recursive: true });
yield* fileSystem.writeFileString(path.join(physicalPath, ".git"), "");
const alias = path.join(workspaceRoot, "linked");
yield* fileSystem.symlink(path.join(workspaceRoot, "project"), alias);
const worktreePath = path.join(alias, "worktree");
Expand Down Expand Up @@ -569,7 +573,14 @@ effectIt.effect.each(["cleanup-first", "startup-first"])(
: undefined;
const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true }));
if (order === "cleanup-first") expect(harness.open).not.toHaveBeenCalled();
if (order === "startup-first") yield* Deferred.await(openEntered);
if (order === "startup-first") {
yield* Effect.raceFirst(
Deferred.await(openEntered),
Fiber.join(startup).pipe(
Effect.andThen(Effect.die("Provider startup finished before opening a session.")),
),
);
}
const laterCleanup =
order === "startup-first"
? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true }))
Expand All @@ -585,6 +596,8 @@ effectIt.effect.each(["cleanup-first", "startup-first"])(
refName: "feature/restore",
path: worktreePath,
});
} else {
expect(harness.createWorktree).not.toHaveBeenCalled();
}
expect(harness.resolveRuntimePolicy).toHaveBeenCalledWith(
expect.objectContaining({
Expand Down
60 changes: 17 additions & 43 deletions apps/server/src/orchestration-v2/runtimeLayer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import * as SqlClient from "effect/sql/SqlClient";
Expand Down Expand Up @@ -1275,39 +1274,28 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
)
: readAttachmentIds(threadId),
);
const deletionHeld = yield* Ref.make(false);
const requestsHeld = (held: Effect.Effect<boolean>) =>
Effect.all([Deferred.isDone(firstPlanned), held]).pipe(
Effect.flatMap(([planned, isHeld]) =>
planned && isHeld ? Queue.offer(blocked, undefined) : Effect.void,
),
);
const { withLock, withDeletionLock } = executor;
const observeLock: ThreadCommandExecutor.ThreadCommandExecutor["Service"]["withLock"] = (
key,
effect,
) => requestsHeld(Effect.succeed(key === first)).pipe(Effect.andThen(withLock(key, effect)));
) =>
(key === first ? Queue.offer(blocked, undefined) : Effect.void).pipe(
Effect.andThen(withLock(key, effect)),
);
const observeDeletion: ThreadCommandExecutor.ThreadCommandExecutor["Service"]["withDeletionLock"] =
(effect) =>
requestsHeld(Ref.get(deletionHeld)).pipe(
Effect.andThen(
withDeletionLock(
Ref.set(deletionHeld, true).pipe(
Effect.andThen(effect),
Effect.ensuring(Ref.set(deletionHeld, false)),
),
),
),
);
const lockSpy = vi.spyOn(executor, "withLock").mockImplementation(observeLock);
const deletionSpy = vi
.spyOn(executor, "withDeletionLock")
.mockImplementation(observeDeletion);
(effect) => Queue.offer(blocked, undefined).pipe(Effect.andThen(withDeletionLock(effect)));
const forkOfDeleted = yield* Effect.gen(function* () {
const firstFiber = yield* deleteThread(first).pipe(
Effect.forkChild({ startImmediately: true }),
);
yield* Deferred.await(firstPlanned);
yield* Effect.acquireRelease(
Effect.sync(() => [
vi.spyOn(executor, "withLock").mockImplementation(observeLock),
vi.spyOn(executor, "withDeletionLock").mockImplementation(observeDeletion),
]),
(spies) => Effect.sync(() => spies.forEach((spy) => spy.mockRestore())),
);
const forkFiber = yield* fork(first, firstRun.runId, ThreadId.make("html-fork-late")).pipe(
Effect.match({
onSuccess: () => "created",
Expand All @@ -1324,15 +1312,7 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
yield* Fiber.join(firstFiber);
yield* Fiber.join(projectFiber);
return yield* Fiber.join(forkFiber);
}).pipe(
Effect.ensuring(
Effect.sync(() => {
lockSpy.mockRestore();
deletionSpy.mockRestore();
attachmentSpy.mockRestore();
}),
),
);
}).pipe(Effect.scoped, Effect.ensuring(Effect.sync(() => attachmentSpy.mockRestore())));
assert.deepEqual(
{ afterLastForks: yield* pagesOnDisk, forkOfDeleted },
{ afterLastForks: [false, false, false], forkOfDeleted: `Thread ${first} was deleted.` },
Expand Down Expand Up @@ -2260,36 +2240,30 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => {
const busy = yield* delegate(busyThreadId);
const idle = yield* delegate(ThreadId.make("runtime-question-wake-idle"));

const order: string[] = [];
const idleWoken = yield* orchestrator.streamDomainEvents.pipe(
Stream.filter(
(event) => event.type === "message.updated" && event.payload.id === idle.wakeMessageId,
),
Stream.take(1),
Stream.runDrain,
Effect.andThen(Effect.sync(() => order.push("idle coordinator woken"))),
Effect.forkScoped,
);
// Stands in for a long send or delegated bookkeeping holding the busy coordinator's lock.
const lockHeld = yield* Deferred.make<void>();
const releaseBusy = yield* Deferred.make<void>();
const busyLock = yield* executor
.withLock(
busyThreadId,
Deferred.succeed(lockHeld, undefined).pipe(
Effect.andThen(Effect.sleep("1 minute")),
Effect.andThen(Effect.sync(() => order.push("busy coordinator's lock released"))),
),
Deferred.succeed(lockHeld, undefined).pipe(Effect.andThen(Deferred.await(releaseBusy))),
)
.pipe(Effect.forkScoped);
yield* Deferred.await(lockHeld);

yield* busy.ask;
yield* idle.ask;
yield* TestClock.adjust("1 minute");
yield* Fiber.join(busyLock);
yield* Fiber.join(idleWoken);

assert.deepEqual(order, ["idle coordinator woken", "busy coordinator's lock released"]);
yield* Deferred.succeed(releaseBusy, undefined);
yield* Fiber.join(busyLock);
}),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
{"type":"emit_inbound","label":"assistant.partial","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ste"}}}}}
{"type":"expect_outbound","label":"session.cancel","frame":{"kind":"notification","method":"session/cancel","params":{"sessionId":"grok-replay-session-1"}}}
{"type":"emit_inbound","label":"prompt.cancelled","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"cancelled"}}}
{"type":"expect_outbound","label":"session.prompt.2","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"<t3_code_instructions>\n<any>\n</t3_code_instructions>\n\n<user_request>\nActually, respond with exactly: steering fixture observed\n</user_request>"},{"type":"text","text":"<runtime_info><any>"}]}}}
{"type":"expect_outbound","label":"session.prompt.2","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"<t3_code_instructions>\n<any>\n</t3_code_instructions>\n\n<user_request>\nActually, respond with exactly: steering fixture observed\n</user_request>"}]}}}
{"type":"emit_inbound","label":"assistant.1","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"steering fixture "}}}}}
{"type":"emit_inbound","label":"assistant.2","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"observed"}}}}}
{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}}
Expand Down
12 changes: 5 additions & 7 deletions apps/server/src/preview/Manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -448,15 +448,13 @@ export const make = Effect.gen(function* PreviewManagerMake() {
);
const createdAt = yield* currentIsoTimestamp;
yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
const targets = input.tabId
? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter(
(entry): entry is PreviewSessionState => entry !== undefined,
)
: sessionsForThread(state, input.threadId);
if (targets.length === 0) {
const remainingTargets = targets.filter((target) =>
state.sessions.has(compositeKey(target.threadId, target.tabId)),
);
if (remainingTargets.length === 0) {
return Effect.succeed([undefined, state] as const);
}
const removed = removeSessions(state, targets, createdAt);
const removed = removeSessions(state, remainingTargets, createdAt);
return Effect.as(
Effect.forEach(
removed.events,
Expand Down
6 changes: 3 additions & 3 deletions apps/server/src/provider/AntigravityInstallation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst
"sh",
[
"-c",
"echo 'F1111 11:50:12.383176 page-size.cc:19] Check failed: sysconf(_SC_PAGE_SIZE) == kPageSize (16384 vs. 4096) Compile-time page size does not match runtime page size' >&2; kill -ABRT $$",
"read -r request; echo 'F1111 11:50:12.383176 page-size.cc:19] Check failed: sysconf(_SC_PAGE_SIZE) == kPageSize (16384 vs. 4096) Compile-time page size does not match runtime page size' >&2; kill -ABRT $$",
],
{ stdin: "pipe", stdout: "pipe", stderr: "pipe" },
),
Expand All @@ -695,8 +695,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst
yield* installation.start;
const state = yield* terminalState(installation);
expect(state.phase).toBe("failed");
expect(state.message).toMatch(/page/i);
}),
expect(state.message).toMatch(/4 KiB memory pages/);
}).pipe(TestClock.withLive),
);

it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
Expand Down
19 changes: 10 additions & 9 deletions apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -835,28 +835,29 @@ it.effect("a fresh-session task launches one thread, then starts each later run
it.effect("a refused dispatch records its refusal, and opaque causes stay generic", () =>
Effect.gen(function* () {
const refusal = "Thread thread:refused was stopped.";
const refused = (cause: unknown) =>
const refused = (cause: unknown, detail?: string) =>
new OrchestratorDispatchError({
commandId: CommandId.make("command:refused"),
commandType: "message.dispatch",
cause,
detail,
});
const generic = refused(undefined).message;
const cases = [
[refusal, refusal],
[" ", generic],
[new Error("private-nested-secret"), generic],
[refused(refusal), refusal],
[refused(" "), generic],
[refused(new Error("private-nested-secret")), generic],
[refused(new Error("private-nested-secret"), " "), generic],
] as const;
const failure = yield* Ref.make<unknown>(undefined);
const failure = yield* Ref.make(refused(undefined));
const layer = ScheduledTaskService.layer.pipe(
Layer.provide(
Layer.mergeAll(
ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
Layer.mock(ThreadManagementService.ThreadManagementService)({
getThreadShell: () => Effect.succeed(threadShell(ProjectId.make("project:test"))),
sendToThread: () =>
Ref.get(failure).pipe(Effect.flatMap((cause) => Effect.fail(refused(cause)))),
sendToThread: () => Ref.get(failure).pipe(Effect.flatMap(Effect.fail)),
}),
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
Expand All @@ -883,8 +884,8 @@ it.effect("a refused dispatch records its refusal, and opaque causes stay generi
runtimeMode: "full-access",
interactionMode: "default",
});
for (const [cause, expected] of cases) {
yield* Ref.set(failure, cause);
for (const [error, expected] of cases) {
yield* Ref.set(failure, error);
const result = yield* service.runNow({ id: task.id });
assert.equal(result.task.lastRunStatus, "failed");
assert.equal(result.task.lastRunError, expected);
Expand Down
6 changes: 3 additions & 3 deletions apps/server/src/terminal/Manager.fork.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import * as ProcessRunner from "../processRunner.ts";
import * as TerminalManager from "./Manager.ts";

import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
import { SpawnExecutableResolution } from "@t3tools/shared/shell";

vi.mock("effect/SynchronizedRef", async (importOriginal) => {
const original = await importOriginal<typeof SynchronizedRef>();
Expand All @@ -47,7 +48,6 @@ class FakePtyProcess implements PtyAdapter.PtyProcess {
private readonly exitListeners = new Set<(event: PtyAdapter.PtyExitEvent) => void>();
killed = false;
exitOnSubscribe: PtyAdapter.PtyExitEvent | undefined;
onKill: ((signal?: string) => void) | undefined;

constructor(pid: number) {
this.pid = pid;
Expand All @@ -70,7 +70,7 @@ class FakePtyProcess implements PtyAdapter.PtyProcess {
kill(signal?: string): void {
this.killed = true;
this.killSignals.push(signal);
this.onKill?.(signal);
this.emitExit({ exitCode: 0, signal: null });
}

onData(callback: (data: string) => void): () => void {
Expand Down Expand Up @@ -242,7 +242,7 @@ const createManager = (
managedBinaryCacheDir: options.managedBinaryCacheDir,
managedBinaryToolsDir: options.managedBinaryToolsDir,
}),
});
}).pipe(Effect.provideService(SpawnExecutableResolution, (command) => command));
const eventsRef = yield* Ref.make<ReadonlyArray<TerminalEvent>>([]);
const unsubscribe = yield* manager.subscribe((event) =>
Ref.update(eventsRef, (events) => [...events, event]),
Expand Down
4 changes: 3 additions & 1 deletion apps/web/src/components/ChatMarkdown.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,7 @@ describe("ChatMarkdown headings", () => {
describe("ChatMarkdown inline code selection", () => {
it("selects only a word on double-click in inline and fenced code", async () => {
setup();
using _writeText = vi.spyOn(navigator.clipboard, "writeText").mockResolvedValue(undefined);
await using screen = await renderText(
"Run `migration-gate --dry-run` first.\n\n```txt\nfenced-block word\n```",
);
Expand All @@ -642,7 +643,8 @@ describe("ChatMarkdown inline code selection", () => {
expect(window.getSelection()?.toString()).toBe("migration");

window.getSelection()?.removeAllRanges();
const fenced = screen.container.querySelector("pre code")!;
const fenced = screen.getByText("fenced-block word", { exact: true });
await expect.element(fenced).toBeVisible();
await userEvent.dblClick(fenced, { position: { x: 4, y: 4 } });
expect(window.getSelection()?.toString()).toBe("fenced");
});
Expand Down
6 changes: 1 addition & 5 deletions apps/web/src/components/ChatMarkdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1066,10 +1066,6 @@ function markdownHeadingRenderer(level: 1 | 2 | 3 | 4 | 5 | 6) {
};
}

function selectInlineCode(event: React.MouseEvent<HTMLElement>) {
window.getSelection()?.selectAllChildren(event.currentTarget);
}

const CHAT_MARKDOWN_COMPONENTS = {
h1: markdownHeadingRenderer(1),
h2: markdownHeadingRenderer(2),
Expand Down Expand Up @@ -1509,7 +1505,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
}
// Inside a link the click belongs to the link.
return inLink ? (
<code {...props} className={className} onDoubleClick={selectInlineCode}>
<code {...props} className={className}>
{children}
</code>
) : (
Expand Down
1 change: 0 additions & 1 deletion apps/web/src/components/chat/ForkMarkdownActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export function MarkdownInlineCode(props: React.ComponentProps<"code">) {
return (
<code
{...props}
onDoubleClick={(event) => window.getSelection()?.selectAllChildren(event.currentTarget)}
tabIndex={0}
aria-description="Copy"
data-copyable=""
Expand Down
Loading