Skip to content
Open
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
14 changes: 14 additions & 0 deletions apps/mobile/src/features/home/homeThreadList.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
import { threadVisibleInInbox } from "@t3tools/client-runtime/state/thread-inbox";
import {
buildProjectGroups,
derivePhysicalProjectKey,
Expand Down Expand Up @@ -218,8 +219,13 @@ export function buildHomeThreadGroups(input: {
readonly projectGroupingMode: SidebarProjectGroupingMode;
/** Current time used for the recency window; defaults to now. Injectable for tests. */
readonly now?: number;
/** Founder inbox. Null keeps the shared list. */
readonly inboxIdentity?: string | null;
/** Bot-to-bot threads stay hidden unless this or a search query asks for them. */
readonly showBotWork?: boolean;
}): ReadonlyArray<HomeThreadGroup> {
const now = input.now ?? Date.now();
const searching = input.searchQuery.trim().length > 0;
const groups = new Map<string, MutableHomeThreadGroup>();
const groupTitleByKey = new Map<string, string>();
const groupKeyByProjectKey = new Map<string, string>();
Expand Down Expand Up @@ -279,6 +285,14 @@ export function buildHomeThreadGroups(input: {
if (thread.archivedAt !== null) {
continue;
}
if (
!threadVisibleInInbox(thread, {
identity: input.inboxIdentity ?? null,
showBotWork: input.showBotWork ?? searching,
})
) {
continue;
}
if (input.environmentId !== null && thread.environmentId !== input.environmentId) {
continue;
}
Expand Down
10 changes: 10 additions & 0 deletions apps/mobile/src/features/threads/threadListV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { threadVisibleInInbox } from "@t3tools/client-runtime/state/thread-inbox";
import {
sortActiveThreadsByOrderKey,
resolveSettledThreadTimestamp,
Expand Down Expand Up @@ -183,6 +184,7 @@ export function getThreadListV2OrderedSection(input: {
}): EnvironmentThreadShell[] {
const threads = input.threads.filter((thread) => {
if (thread.archivedAt !== null) return false;
if (!threadVisibleInInbox(thread, { identity: null, showBotWork: false })) return false;
if (
(input.settlementEnvironmentIds?.has(thread.environmentId) ?? true) &&
thread.settledOverride === "settled" &&
Expand Down Expand Up @@ -395,6 +397,14 @@ export function buildThreadListV2Items(input: {
for (const thread of input.threads) {
// Callers pass live shells. The server stamps settledOverride for the tail.
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
if (
!threadVisibleInInbox(thread, {
identity: null,
showBotWork: query.length > 0,
})
) {
continue;
}
if (projectKeys !== null && !projectKeys.has(`${thread.environmentId}:${thread.projectId}`)) {
continue;
}
Expand Down
7 changes: 7 additions & 0 deletions apps/mobile/src/lib/projectThreadStartTurn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
type ProjectId,
type ProviderInteractionMode,
type RuntimeMode,
type ThreadInboxType,
} from "@t3tools/contracts";
import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";

Expand Down Expand Up @@ -43,6 +44,9 @@ export interface ProjectThreadStartTurnSpec {
readonly startFromOrigin: boolean;
/** Generated temp branch for worktree mode; unused for local mode. */
readonly worktreeBranchName: string;
readonly owner?: string | null;
readonly threadType?: ThreadInboxType | null;
readonly startedBy?: string | null;
}

/**
Expand Down Expand Up @@ -81,6 +85,9 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
// Coordinator gets its dedicated scratch directory from the server.
worktreePath: null,
createdAt: spec.createdAt,
...(spec.owner !== undefined ? { owner: spec.owner } : {}),
...(spec.threadType !== undefined ? { threadType: spec.threadType } : {}),
...(spec.startedBy !== undefined ? { startedBy: spec.startedBy } : {}),
},
...(isWorktree
? {
Expand Down
7 changes: 7 additions & 0 deletions apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import {
} from "./toolkits/preview/tools.ts";
import { PullRequestsToolkitHandlersLive } from "./toolkits/pullRequests/handlers.ts";
import { PullRequestsToolkit } from "./toolkits/pullRequests/tools.ts";
import { ThreadRoutingToolkitHandlersLive } from "./toolkits/threads/handlers.ts";
import { ThreadRoutingToolkit } from "./toolkits/threads/tools.ts";
import {
DeviceScreenshotToolkitHandlersLive,
DeviceStandardToolkitHandlersLive,
Expand Down Expand Up @@ -608,6 +610,10 @@ export const PullRequestsToolkitRegistrationLive = McpServer.toolkit(PullRequest
Layer.provide(PullRequestsToolkitHandlersLive),
);

export const ThreadRoutingToolkitRegistrationLive = McpServer.toolkit(ThreadRoutingToolkit).pipe(
Layer.provide(ThreadRoutingToolkitHandlersLive),
);

const DeviceStandardToolkitRegistrationLive = McpServer.toolkit(DeviceStandardToolkit).pipe(
Layer.provide(DeviceStandardToolkitHandlersLive),
);
Expand All @@ -631,5 +637,6 @@ const McpTransportLive = McpServer.layerHttp({
export const layer = Layer.mergeAll(
PreviewToolkitRegistrationLive,
PullRequestsToolkitRegistrationLive,
ThreadRoutingToolkitRegistrationLive,
DeviceToolkitRegistrationLive,
).pipe(Layer.provideMerge(McpTransportLive));
145 changes: 145 additions & 0 deletions apps/server/src/mcp/toolkits/threads/handlers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import {
EnvironmentId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationCommand,
type OrchestrationThreadShell,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import type { Tool } from "effect/unstable/ai";

import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../../../orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import { ThreadRoutingToolkitHandlersLive } from "./handlers.ts";
import { ThreadRoutingToolkit } from "./tools.ts";

const THREAD_ID = ThreadId.make("thread-1");

const testCrypto = Crypto.make({
randomBytes: (size) => new Uint8Array(size).fill(7),
digest: (_algorithm, data) => Effect.succeed(data),
});

const invocation = (): McpInvocationContext.McpInvocationScope => ({
environmentId: EnvironmentId.make("environment-1"),
threadId: THREAD_ID,
providerSessionId: "provider-session-1",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(["pull-requests"]),
issuedAt: 1,
});

function makeThread(patch: Partial<OrchestrationThreadShell> = {}): OrchestrationThreadShell {
return {
id: THREAD_ID,
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
pullRequests: [],
latestTurn: null,
createdAt: "2026-08-01T00:00:00.000Z",
updatedAt: "2026-08-20T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...patch,
};
}

const makeHarness = Effect.fn(function* (
options: { readonly thread?: OrchestrationThreadShell | null } = {},
) {
const commands = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const thread = options.thread === undefined ? makeThread() : options.thread;
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.gen(function* () {
yield* Ref.update(commands, (recorded) => [...recorded, command]);
return { sequence: 1 };
});
const dependencies = Layer.mergeAll(
Layer.mock(ProjectionSnapshotQuery)({
getThreadShellById: (threadId) =>
Effect.succeed(
thread !== null && threadId === thread.id ? Option.some(thread) : Option.none(),
),
}),
Layer.mock(OrchestrationEngineService)({
readEvents: () => Stream.empty,
dispatch,
streamDomainEvents: Stream.empty,
latestSequence: Effect.succeed(0),
}),
Layer.succeed(Crypto.Crypto, testCrypto),
);
const toolkit = yield* ThreadRoutingToolkit.pipe(
Effect.provide(ThreadRoutingToolkitHandlersLive.pipe(Layer.provide(dependencies))),
);
const call = (params: Parameters<typeof toolkit.handle<"set_thread_routing">>[1]) =>
toolkit.handle("set_thread_routing", params).pipe(
Stream.unwrap,
Stream.runCollect,
Effect.map(
(chunk) =>
chunk.at(-1)!.result as Tool.Success<
(typeof ThreadRoutingToolkit.tools)["set_thread_routing"]
>,
),
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation()),
Effect.provide(dependencies),
);
return { commands, call };
});

describe("thread routing toolkit", () => {
it.effect("tags the calling thread and leaves omitted fields alone", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
thread: makeThread({ owner: "Jeff", startedBy: "Lead" }),
});
const result = yield* harness.call({ threadType: "needs-human" });
expect(result).toEqual({
threadId: THREAD_ID,
owner: "Jeff",
threadType: "needs-human",
startedBy: "Lead",
});
expect(yield* Ref.get(harness.commands)).toMatchObject([
{
type: "thread.meta.update",
threadId: THREAD_ID,
threadType: "needs-human",
},
]);
expect((yield* Ref.get(harness.commands))[0]).not.toHaveProperty("owner");
}),
);

it.effect("rejects a call that changes nothing", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
const error = yield* harness.call({}).pipe(Effect.flip);
expect(error._tag).toBe("ThreadRoutingInvalidError");
expect(yield* Ref.get(harness.commands)).toEqual([]);
}),
);
});
79 changes: 79 additions & 0 deletions apps/server/src/mcp/toolkits/threads/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { CommandId, type OrchestrationThreadShell, type ThreadId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";

import * as OrchestrationEngine from "../../../orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import {
type SetThreadRoutingInput,
type SetThreadRoutingResult,
ThreadRoutingFailedError,
ThreadRoutingInvalidError,
ThreadRoutingNotFoundError,
ThreadRoutingToolkit,
} from "./tools.ts";

const make = Effect.gen(function* () {
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const crypto = yield* Crypto.Crypto;

const commandId = (threadId: ThreadId) =>
crypto.randomUUIDv4.pipe(
Effect.orDie,
Effect.map((uuid) => CommandId.make(`server:mcp-thread-routing:${threadId}:${uuid}`)),
);

const failRouting = <E>(cause: Cause.Cause<E>) =>
Cause.hasInterruptsOnly(cause)
? Effect.failCause(cause as Cause.Cause<never>)
: Effect.fail(new ThreadRoutingFailedError({ cause }));

return ThreadRoutingToolkit.of({
set_thread_routing: Effect.fn("ThreadRoutingToolkit.setThreadRouting")(function* (input) {
if (
input.owner === undefined &&
input.threadType === undefined &&
input.startedBy === undefined
) {
return yield* new ThreadRoutingInvalidError({});
}
const scope = yield* McpInvocationContext.McpInvocationContext;
const threadId = input.threadId ?? scope.threadId;
const thread = yield* snapshots
.getThreadShellById(threadId)
.pipe(Effect.mapError((cause) => new ThreadRoutingFailedError({ cause })));
if (Option.isNone(thread)) {
return yield* new ThreadRoutingNotFoundError({ threadId });
}
yield* engine
.dispatch({
type: "thread.meta.update",
commandId: yield* commandId(threadId),
threadId,
...(input.owner !== undefined ? { owner: input.owner } : {}),
...(input.threadType !== undefined ? { threadType: input.threadType } : {}),
...(input.startedBy !== undefined ? { startedBy: input.startedBy } : {}),
})
.pipe(Effect.catchCause(failRouting));
return routingResult(thread.value, input);
}),
});
});

function routingResult(
thread: OrchestrationThreadShell,
input: SetThreadRoutingInput,
): SetThreadRoutingResult {
return {
threadId: input.threadId ?? thread.id,
owner: input.owner !== undefined ? input.owner : (thread.owner ?? null),
threadType: input.threadType !== undefined ? input.threadType : (thread.threadType ?? null),
startedBy: input.startedBy !== undefined ? input.startedBy : (thread.startedBy ?? null),
};
}

export const ThreadRoutingToolkitHandlersLive = ThreadRoutingToolkit.toLayer(make);
Loading
Loading