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
3 changes: 2 additions & 1 deletion apps/server/src/fork/displayModeWrap/DisplayModeWrap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ const runCreated = (
activeAttemptId: threadId === sourceId ? attemptId : null,
status,
requestedAt: now,
startedAt: now,
// A cancelled run here is a queued turn that never started.
startedAt: status === "cancelled" ? null : now,
completedAt: status === "completed" ? now : null,
checkpointId: null,
contextHandoffId: null,
Expand Down
9 changes: 7 additions & 2 deletions apps/server/src/fork/fyi/FyiRuntimeLayer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import * as ThreadCommandExecutor from "../../orchestration-v2/ThreadCommandExec
import * as SqlitePersistence from "../../persistence/Sqlite.ts";
import * as PortScanner from "../../preview/PortScanner.ts";
import * as ProjectService from "../../project/ProjectService.ts";
import * as ProjectSetupScriptRunner from "../../project/ProjectSetupScriptRunner.ts";
import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts";
import * as ModelManifest from "../../provider/ModelManifest.ts";
import * as ProviderInstanceRegistry from "../../provider/ProviderInstanceRegistry.ts";
Expand All @@ -55,8 +56,12 @@ import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import * as FyiDelivery from "./FyiDelivery.ts";

const layerPlatformTest = Layer.merge(
Layer.mergeAll(NodeServices.layer, NodeCrypto.layer),
const layerPlatformTest = Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
runForThread: () => Effect.succeed({ status: "no-script" }),
}),
Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
resolveLink: () => Effect.die("unused title link"),
}),
Expand Down
42 changes: 40 additions & 2 deletions apps/server/src/fork/shownHistory/ShownHistory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ const LARGE = ThreadId.make("thread:shown:large");
const REWRITES = ThreadId.make("thread:shown:rewrites");
const HUGE = ThreadId.make("thread:shown:huge");
const SPLIT = ThreadId.make("thread:shown:split");
const CANCELLED = ThreadId.make("thread:shown:cancelled");

const runIdOf = (threadId: ThreadId, run: number) => RunId.make(`run:${threadId}:${run}`);
const nodeIdOf = (threadId: ThreadId, run: number) => NodeId.make(`node:${threadId}:${run}`);
Expand Down Expand Up @@ -145,7 +146,8 @@ function threadCreated(
function runEvent(
threadId: ThreadId,
run: number,
status: "completed" | "failed" | "rolled_back" = "completed",
status: "completed" | "failed" | "rolled_back" | "cancelled" = "completed",
started = true,
): OrchestrationV2DomainEvent {
const runId = runIdOf(threadId, run);
return {
Expand All @@ -168,7 +170,7 @@ function runEvent(
activeAttemptId: null,
status,
requestedAt: at,
startedAt: at,
startedAt: started ? at : null,
completedAt: at,
checkpointId: null,
contextHandoffId: null,
Expand Down Expand Up @@ -664,6 +666,23 @@ const CHILDREN = [
["a child whose shown rows end on a batch boundary", CHILD_EDGE, 16, 8, PARENT],
] as const;

const queuedMessage = (threadId: ThreadId, run: number, text: string): OrchestrationV2TurnItem => ({
...base(threadId, run, 1),
...TYPED,
type: "user_message",
messageId: messageIdOf(threadId, run, 1),
inputIntent: "queued_turn",
text,
attachments: [],
});
/** Run 2 started and a restart then cancelled it; run 3 was cancelled before it started. */
const cancelledThread = () => [
userMessage(CANCELLED, 1, 1, "Fix the build."),
send(CANCELLED, 1, 2, "On it."),
queuedMessage(CANCELLED, 2, "Also check the logs."),
queuedMessage(CANCELLED, 3, "Never mind this."),
];

const runsOf = (items: ReadonlyArray<OrchestrationV2TurnItem>) => [
...new Set(items.map((item) => Number(String(item.runId).split(":").at(-1)))),
];
Expand Down Expand Up @@ -694,6 +713,7 @@ const seed = Effect.gen(function* () {
[REWRITES, rewritesThread(), threadCreated(REWRITES)],
[HUGE, hugeThread(), threadCreated(HUGE)],
[SPLIT, splitThread(), threadCreated(SPLIT)],
[CANCELLED, cancelledThread(), threadCreated(CANCELLED)],
];
for (const [threadId, items, created] of threads) {
yield* projections.apply(created);
Expand All @@ -702,6 +722,8 @@ const seed = Effect.gen(function* () {
}
yield* projections.apply(runEvent(PARENT, ROLLED_BACK_RUN, "rolled_back"));
yield* projections.apply(runEvent(GUARD, 3, "failed"));
yield* projections.apply(runEvent(CANCELLED, 2, "cancelled"));
yield* projections.apply(runEvent(CANCELLED, 3, "cancelled", false));
for (const run of range(1, 3)) yield* projections.apply(runEvent(QUIET, run, "failed"));
yield* projections.apply({
id: EventId.make("event:shown:question"),
Expand Down Expand Up @@ -1226,6 +1248,22 @@ it.layer(TestLayer)("shown-only history", (it) => {
assert.isTrue(page.items.some((row) => !isShownItem(row.item)));
}),
);
it.effect("shows a queued message whose cancelled run had started, as Normal does", () =>
Effect.gen(function* () {
const normal = visibleIds(
boundedSnapshotProjection(
yield* firstSnapshot({ threadId: CANCELLED, acceptBoundedSnapshot: true }),
),
);
const shown = visibleIds(boundedSnapshotProjection(yield* shownSnapshot(CANCELLED)));
const delivered = String(itemIdOf(CANCELLED, 2, 1));
const held = String(itemIdOf(CANCELLED, 3, 1));
assert.include(normal, delivered);
assert.notInclude(normal, held);
assert.include(shown, delivered);
assert.notInclude(shown, held);
}),
);
});

function runOrdinalOf(item: Pick<OrchestrationV2TurnItem, "ordinal">): number {
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/fork/shownHistory/ShownHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,8 @@ const segmentVisible = (sql: SqlClient.SqlClient, segment: ShownSegment) =>
? sql`(run.status IS NULL OR run.status <> 'rolled_back')
AND NOT (item.type = 'user_message'
AND json_extract(item.payload_json, '$.inputIntent') = 'queued_turn'
AND run.status IS 'cancelled')`
AND run.status IS 'cancelled'
AND json_extract(run.payload_json, '$.startedAt') IS NULL)`
: sql`(run.ordinal <= ${segment.inherited.runOrdinal}
OR (item.run_id IS NULL AND ${segment.inherited.runlessRows ? 1 : 0} = 1))`;

Expand Down
7 changes: 6 additions & 1 deletion apps/server/src/fork/subThreads/SubThreads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,12 @@ export const layerFromServices = Layer.effect(
${userTypedSql(sql)}
AND (run.status IS NULL OR run.status <> 'rolled_back')
AND NOT (
COALESCE(run.status IN ('queued', 'cancelled'), 0)
COALESCE(
run.status = 'queued' OR (
run.status = 'cancelled' AND json_extract(run.payload_json, '$.startedAt') IS NULL
),
0
)
AND json_extract(item.payload_json, '$.inputIntent') = 'queued_turn'
)
`;
Expand Down
41 changes: 40 additions & 1 deletion apps/server/src/fork/userMessageTools/SendToUser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import {
TurnItemId,
} from "@t3tools/contracts";
import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
import { shortId } from "@t3tools/shared/displayModes";
import { displayEventFromTurnItem, shortId } from "@t3tools/shared/displayModes";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
Expand Down Expand Up @@ -456,3 +457,41 @@ describe("replace_send_to_user", () => {
}).pipe(Effect.provide(layer)),
);
});

// A provider that drops MCP outputs gets each send's result back from the capture by its input.
describe("Chat sends through the MCP result capture", () => {
const captureLayer = layer.pipe(Layer.provideMerge(McpProviderSessions.layer));
const reply = {
text: "Fixed the build.",
reply_to: shortId("u1"),
user_message: "Fix the build.",
};
const recoveredEvent = Effect.gen(function* () {
const sessions = yield* McpProviderSessions.McpProviderSessions;
const output = yield* sessions.takeToolResult(chatThread, "send_to_user", reply);
return displayEventFromTurnItem({
...base("recovered"),
type: "dynamic_tool",
toolName: "mcp__t3-code__send_to_user",
input: reply,
output,
} as never)?.type;
});

it.effect("keeps a reply shown when an identical later send was refused", () =>
Effect.gen(function* () {
history = [typed("u1", "Fix the build.")];
expect((yield* answerU1(reply.text)).isError).not.toBe(true);
expect((yield* answerU1(reply.text)).isError).toBe(true);
expect(yield* recoveredEvent).toBe("sent");
}).pipe(Effect.provide(Layer.fresh(captureLayer))),
);

it.effect("shows a lone reply", () =>
Effect.gen(function* () {
history = [typed("u1", "Fix the build.")];
expect((yield* answerU1(reply.text)).isError).not.toBe(true);
expect(yield* recoveredEvent).toBe("sent");
}).pipe(Effect.provide(Layer.fresh(captureLayer))),
);
});
7 changes: 7 additions & 0 deletions apps/server/src/fork/userMessageTools/SendToUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,13 @@ const ReplaceSendToUserTool = Tool.make(REPLACE_SEND_TO_USER_TOOL_NAME, {

export const SendToUserToolkit = Toolkit.make(SendToUserTool, ReplaceSendToUserTool);

// A Chat-mode success keeps no field the MCP result capture reads. Its empty record stops an
// identical refused call's error from passing for it when a provider drops both outputs.
export const capturedSuccessFallback = (toolName: string): Record<string, never> | undefined =>
toolName === SEND_TO_USER_TOOL_NAME || toolName === REPLACE_SEND_TO_USER_TOOL_NAME
? {}
: undefined;

/** The items stored before the calling tool use, when the provider names it; else all of them. */
function itemsBefore(shown: ReadonlyArray<OrchestrationV2TurnItem>, ownItem: string | undefined) {
const ownAt =
Expand Down
3 changes: 0 additions & 3 deletions apps/server/src/git/GitManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,8 @@ import type {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
ModelSelection,
<<<<<<< origin/main
ServerSettings as ServerSettingsValue,
=======
ServerProvider,
>>>>>>> upstream/main
} from "@t3tools/contracts";

import {
Expand Down
9 changes: 3 additions & 6 deletions apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1266,7 +1266,8 @@ const withToolResultCapture = Effect.fn("McpHttpServer.withToolResultCapture")(f
}
const output =
exit._tag === "Success"
? compactT3McpToolOutput(toolName, exit.value)
? (compactT3McpToolOutput(toolName, exit.value) ??
SendToUser.capturedSuccessFallback(toolName))
: { isError: true };
return output === undefined
? Effect.void
Expand Down Expand Up @@ -1417,15 +1418,11 @@ export const layerOrchestratorToolkit = toolkitRegistration(
export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer);
const layerWorkflowToolkit = toolkitRegistration(WorkflowToolkit, WorkflowHandlers.layer);

<<<<<<< origin/main
// The fork's send_to_user replaces upstream's: display modes read its calls by name and `text`.
const layerMessageToolkit = toolkitRegistration(
export const layerMessageToolkit = toolkitRegistration(
SendToUser.SendToUserToolkit,
SendToUser.layerHandlers,
);
=======
export const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer);
>>>>>>> upstream/main

const layerWorktreeToolkitRegistration = toolkitRegistration(
WorktreeToolkit,
Expand Down
3 changes: 0 additions & 3 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,8 @@ import {
taskPrompt,
} from "./delegatedTaskModes.ts";
import { assertTargetWithinLimits, isLiveCallerShell, threadNotFound } from "./threadAccess.ts";
<<<<<<< origin/main
import { fyiRunsByThread, fyiTimelineFields, sendFyi } from "../fork/fyi/FyiMcp.ts";
=======
import { WITHHELD, withoutWebhookUrlToken } from "../scheduledTasks/webhookUrlToken.ts";
>>>>>>> upstream/main
import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as PeerForwarding from "../peer/PeerForwarding.ts";
import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
Expand Down
20 changes: 13 additions & 7 deletions apps/server/src/mcp/toolkits/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import * as SecretRequests from "../../secrets/SecretRequests.ts";
import * as RemoteDelegation from "../../peer/RemoteDelegation.ts";
import * as ScheduledTaskService from "../../scheduledTasks/ScheduledTaskService.ts";
import * as ServerSettings from "../../serverSettings.ts";
import { DisplayModeWrap } from "../../fork/displayModeWrap/DisplayModeWrap.ts";
import * as McpHttpServer from "../McpHttpServer.ts";
import * as McpInvocationContext from "../McpInvocationContext.ts";
import * as McpToolAccessTestkit from "../McpToolAccess.testkit.ts";
Expand Down Expand Up @@ -422,28 +423,28 @@ it.effect("captures send_to_user results for providers that drop MCP outputs", (
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const draft = "### Status\n\nAll checks passed.";
const result = yield* server
.callTool({ name: "send_to_user", arguments: { message: draft } })
.callTool({ name: "send_to_user", arguments: { text: draft } })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(result.isError).not.toBe(true);
expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toEqual(
{ sentMessage: draft },
);
expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toBe(
expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { text: draft })).toEqual({
sentMessage: draft,
});
expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { text: draft })).toBe(
undefined,
);

const invalid = yield* server
.callTool({ name: "send_to_user", arguments: { message: "" } })
.callTool({ name: "send_to_user", arguments: { text: "" } })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
Effect.provideService(McpSchema.McpServerClient, client),
Effect.flip,
);
expect(invalid).toMatchObject({ _tag: "InvalidParams" });
expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: "" })).toEqual({
expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { text: "" })).toEqual({
isError: true,
});
}).pipe(
Expand All @@ -452,6 +453,11 @@ it.effect("captures send_to_user results for providers that drop MCP outputs", (
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provideMerge(McpProviderSessions.layer),
Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
// The fork's send_to_user reads the thread's display mode.
Layer.provide(ServerSettings.layerTest()),
Layer.provide(
Layer.mock(DisplayModeWrap)({ forgetNotesAfterCompaction: () => (ingest) => ingest }),
),
),
),
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,13 @@ import {
ThreadId,
} from "@t3tools/contracts";
import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
<<<<<<< origin/main
import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
import * as Digest from "effect/crypto/Digest";
=======
import {
compactDynamicToolOutput,
htmlRenderFromToolItem,
previewRecordingIdFromToolItem,
sentMessageFromToolItem,
} from "@t3tools/shared/toolOutput";
>>>>>>> upstream/main
import * as Digest from "effect/crypto/Digest";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
Expand Down Expand Up @@ -1072,6 +1068,7 @@ describe("AntigravityAdapterV2 html_render pages", () => {
const unfinishedText = "Still running when turn ended.";
const adapter = yield* makeAntigravityAdapterV2({
instanceId,
profileDirectory: unusedProfileDirectory,
selfInvocation: yield* resolveSelfInvocation(),
makeRuntime: (input) =>
makeAntigravityAcpRuntime({
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13579,7 +13579,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
yield* Ref.update(input.effects, (effects) => [
...effects,
{
id: `effect:checkpoint.capture:${attempt.id}`,
id: `effect:checkpoint.capture:${run.id}`,
commandId: CommandId.make(`command:effect:checkpoint.capture:${run.id}`),
threadId: input.command.threadId,
request: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -615,13 +615,8 @@ const makeProviderAdapter = Effect.fnUntraced(function* (
resumeCount: current.resumeCount + 1,
})).pipe(Effect.as(threadInput.providerThread)),
startTurn: () => options.startTurn ?? Effect.void,
<<<<<<< origin/main
compactThread: () => Effect.void,
resumeTurn: () => Effect.void,
=======
resumeTurn: () => options.startTurn ?? Effect.void,
compactThread: () => options.startTurn ?? Effect.void,
>>>>>>> upstream/main
steerTurn: () => Effect.void,
interruptTurn: () =>
Ref.update(state, (current) => ({
Expand Down
Loading
Loading