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
14 changes: 14 additions & 0 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ import {
import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model";
import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
import { planningQuota } from "@t3tools/shared/planningQuota";
import { formatThreadLink } from "@t3tools/shared/threadLinks";
import { threadPullRequestUpdatedAtMs } from "@t3tools/shared/threadPullRequests";
import {
Expand Down Expand Up @@ -2683,6 +2684,19 @@ const make = Effect.gen(function* () {
parent.thread.interactionMode,
input.interactionMode,
);
if (interactionMode === "plan" && !isRetryOfAcceptedDelegation) {
const quota = planningQuota(
providers.find((provider) => provider.instanceId === target.modelSelection.instanceId),
target.modelSelection.model,
DateTime.toEpochMillis(yield* DateTime.now),
);
if (quota.kind === "limited") {
return yield* failure(
"invalid_request",
"The planning worker is near its usage limit. Stop delegation and ask the user to approve a different worker. Do not retry with another account or model on your own.",
);
}
}
let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined;
if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) {
const project = yield* requireProject(parent.thread.projectId);
Expand Down
134 changes: 134 additions & 0 deletions apps/web/src/components/ChatView.planOnly.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { createMemoryHistory } from "@tanstack/react-router";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
import type * as Context from "effect/Context";
import { expect, it, vi } from "vite-plus/test";
import { page, userEvent } from "vite-plus/test/browser";

import { AppRoot } from "~/AppRoot";
import "~/components/ChatView";
import { __setClientSettingsForTests } from "~/hooks/useSettings";
import { getRouter } from "~/router";
import {
CLAUDE_PROVIDER,
CODEX_PROVIDER,
ENVIRONMENT_ID,
dispatchedCommands,
installFakeEnvironment,
threadWithHistory,
type FakeDriver,
} from "../../test/fakeEnvironment";
import { render } from "../../test/render";

vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => {
const [actual, { fakeDriver }, Layer] = await Promise.all([
importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
import("../../test/fakeEnvironment"),
import("effect/Layer"),
]);
return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
});

it.each(["approve", "decline"] as const)(
"plan only gates a quota switch on %s",
async (decision) => {
const thread = threadWithHistory(`plan-quota-${decision}`, 1);
const checkedAt = "2026-11-18T12:00:00.000Z";
vi.setSystemTime(new Date(checkedAt));
using _clock = { [Symbol.dispose]: () => vi.useRealTimers() };
const usage = (usedPercent: number) => ({
checkedAt,
windows: [{ id: "primary", kind: "session", label: "Session limit", usedPercent }],
});
using _environment = installFakeEnvironment([thread], {
acceptCommands: true,
providers: [
{
...CLAUDE_PROVIDER,
displayName: "Lab Claude",
usageLimits: usage(96),
models: [{ ...CLAUDE_PROVIDER.models[0], slug: "claude-haiku-5-5" }],
},
{
...CODEX_PROVIDER,
usageLimits: usage(20),
models: [
...CODEX_PROVIDER.models,
{
slug: "gpt-6.2-astra",
name: "GPT‑6.2 Astra",
isCustom: false,
capabilities: {
optionDescriptors: [
{
id: "reasoningEffort",
label: "Effort",
type: "select",
options: [{ id: "max", label: "Max" }],
},
],
},
},
{
slug: "gpt-mini",
name: "GPT Mini",
isCustom: false,
capabilities: {
optionDescriptors: [
{
id: "reasoningEffort",
label: "Effort",
type: "select",
options: [{ id: "low", label: "Low" }],
},
],
},
},
],
},
],
});
__setClientSettingsForTests({
...DEFAULT_CLIENT_SETTINGS,
onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
});
const router = getRouter(
createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
);
await router.load();
await using _app = await render(<AppRoot router={router} />, { router: false });

await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
const editor = page.getByTestId("composer-editor");
await userEvent.click(editor);
await userEvent.keyboard("Plan the fixture");
await page.getByRole("button", { name: "Plan only", exact: true }).click();
await expect.element(page.getByText(/Lab Claude.*96% used/)).toBeVisible();
await expect.element(page.getByText(/Use codex.*gpt-mini/)).toBeVisible();
const sends = () =>
dispatchedCommands().filter((command) => command.type === "message.dispatch");
expect(sends()).toHaveLength(0);
if (decision === "decline") {
await page.getByRole("button", { name: "Decline switch", exact: true }).click();
await expect.element(page.getByText("Switch declined. Draft kept.")).toBeVisible();
expect(editor.element().textContent).toContain("Plan the fixture");
expect(sends()).toHaveLength(0);
return;
}
await page.getByRole("button", { name: "Approve switch and plan", exact: true }).click();
await vi.waitFor(() => expect(sends()).toHaveLength(1));
expect(dispatchedCommands()).toEqual(
expect.arrayContaining([
expect.objectContaining({ type: "thread.interaction-mode.set", interactionMode: "plan" }),
expect.objectContaining({
type: "thread.runtime-mode.set",
runtimeMode: "approval-required",
}),
]),
);
const serialized = JSON.stringify(sends()[0]);
expect(serialized).toContain("gpt-6.2-astra");
expect(serialized).toContain("gpt-mini");
expect(serialized).toContain("low");
expect(serialized).toContain("Quota switch approved for this turn");
},
);
28 changes: 15 additions & 13 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -830,8 +830,7 @@ export default function ChatView(props: ChatViewProps) {
? buildLocalDraftThread(
threadId,
draftThread,
(draftFallback ? draftFallback.selection : draftDefaultModelSelection) ??
NO_PROVIDER_MODEL_SELECTION,
draftDefaultModelSelection ?? NO_PROVIDER_MODEL_SELECTION,
)
: undefined;
const isServerThread = serverThread !== null;
Expand Down Expand Up @@ -1144,10 +1143,7 @@ export default function ChatView(props: ChatViewProps) {
const activeProjectScripts = activeProject ? resolveProjectScripts(settings, activeProject) : [];
const { projectCloneBannerItem, projectCloneSendBlockReason } =
useProjectCloneBanner(activeProjectRef);
const activeProjectDefaultModelSelection =
!isServerThread && draftFallback
? draftFallback.selection
: activeProjectSettings.settings.defaultModelSelection;
const activeProjectDefaultModelSelection = activeProjectSettings.settings.defaultModelSelection;
const handleNewThreadInActiveProject = () => {
startNewThreadForProject(activeProjectRef, handleNewThread);
};
Expand Down Expand Up @@ -2623,8 +2619,8 @@ export default function ChatView(props: ChatViewProps) {
!composerModelSelectionExplicit &&
draftFallback?.fallback &&
(!composerSelectedModelSelection ||
(composerSelectedModelSelection.instanceId === fallbackSelection?.instanceId &&
composerSelectedModelSelection.model === fallbackSelection?.model))
(composerSelectedModelSelection.instanceId === defaultSelection?.instanceId &&
composerSelectedModelSelection.model === defaultSelection?.model))
? draftFallback.fallback
: null;
const fallbackWindow = fallback
Expand All @@ -2643,13 +2639,19 @@ export default function ChatView(props: ChatViewProps) {
?.models.find((model) => model.slug === fallbackSelection.model)?.name ??
fallbackSelection.model,
defaultProviderName: fallback.provider.displayName ?? fallback.provider.driver,
defaultModelName:
fallback.provider.models.find((model) => model.slug === defaultSelection.model)
?.name ?? defaultSelection.model,
fallbackProviderName:
providerStatuses.find(
(provider) => provider.instanceId === fallbackSelection.instanceId,
)?.displayName ?? fallbackSelection.instanceId,
resetsAt: fallback.resetsAt,
timestampFormat,
onUseDefault: () =>
onProviderModelSelectStable(defaultSelection.instanceId, defaultSelection.model),
onApprove: () =>
useComposerDraftStore
.getState()
.setModelSelection(composerDraftTarget, fallbackSelection, {
explicit: true,
replaceOptions: true,
}),
onDismiss: () => setDismissedFallbackWindow(fallbackWindow),
}),
]
Expand Down
16 changes: 16 additions & 0 deletions apps/web/src/components/CommandPalette.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1699,6 +1699,22 @@ function OpenCommandPaletteDialog(props: {
},
});

actionItems.push({
kind: "action",
value: "action:workflow",
searchTerms: ["workflow", "agents", "delegation", "delivery"],
title: "Open Workflow",
icon: <ChartNoAxesColumnIcon className={ITEM_ICON_CLASS} />,
run: async () => {
const thread =
paletteRouteTarget?.kind === "server" ? paletteRouteTarget.threadRef : undefined;
await navigate({
to: "/workflow",
search: { environment: thread?.environmentId, thread: thread?.threadId, run: undefined },
});
},
});

for (const direction of [1, -1] as const) {
const title = direction === 1 ? "Focus Next Workspace Area" : "Focus Previous Workspace Area";
actionItems.push({
Expand Down
Loading
Loading