Compare commits

..
Author SHA1 Message Date
d7839aa9ce fix(web): use blue check for selected state in runtime mode and workspace menus
Ported from #2451.

Co-authored-by: ss <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-09 16:06:41 -07:00
t3-code[bot] 04f7f32ace chore(release): prepare v0.0.27 2026-06-09 21:14:36 +00:00
Julius Marmingeandcodex a3422a9bb5 Fix Clerk browser test mock (#3013)
Co-authored-by: codex <[email protected]>
2026-06-09 20:38:20 +00:00
Julius Marmingeandcodex 22f9f3058b [codex] Rebrand T3 Cloud as T3 Connect (#3011)
Co-authored-by: codex <[email protected]>
2026-06-09 12:25:02 -07:00
t3-code[bot] 983a8c7fa6 chore(release): prepare v0.0.26 2026-06-09 17:53:22 +00:00
Julius Marmingeandcodex de58ec8e24 Add Claude Fable 5 model (#3009)
Co-authored-by: codex <[email protected]>
2026-06-09 17:39:18 +00:00
Julius Marmingeandcodex 8e6f4229da [codex] Fix main CI Effect test runtimes (#3008)
Co-authored-by: codex <[email protected]>
2026-06-09 09:43:03 -07:00
Milosz JankiewiczandJulius Marminge 38ea6d483e feat(grok): add Grok CLI provider via ACP (#2809)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-09 09:28:40 -07:00
94 changed files with 4604 additions and 823 deletions

No files matched your search

+2 -2
View File
@@ -1,5 +1,5 @@
# Optional: T3 Cloud source builds
# Leave these unset to disable optional T3 Cloud features in local source builds.
# Optional: T3 Connect source builds
# Leave these unset to disable optional T3 Connect features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
+1 -1
View File
@@ -1,4 +1,4 @@
name: Deploy T3 Cloud relay
name: Deploy T3 Connect relay
on:
push:
+1 -1
View File
@@ -167,7 +167,7 @@ jobs:
--github-output
relay_public_config:
name: Resolve T3 Cloud public config
name: Resolve T3 Connect public config
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.24",
"version": "0.0.27",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -165,7 +165,7 @@ describe("DesktopWindow", () => {
assert.isTrue(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "http://127.0.0.1:3773/settings/cloud",
navigationUrl: "http://127.0.0.1:3773/settings/connections",
}),
);
assert.isFalse(
+1 -1
View File
@@ -16,7 +16,7 @@ This app has three variants:
Run commands from `apps/mobile`.
T3 Cloud is optional and disabled in a fresh clone. Public configuration belongs in the
T3 Connect is optional and disabled in a fresh clone. Public configuration belongs in the
repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See
[`../../.env.example`](../../.env.example).
@@ -572,7 +572,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/cloud/link-proof")) {
if (String(url).endsWith("/api/connect/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
return Promise.resolve(Response.json(validLinkResponse("env-other")));
@@ -631,7 +631,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/cloud/link-proof")) {
if (String(url).endsWith("/api/connect/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
return Promise.resolve(
@@ -669,7 +669,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/cloud/link-proof")) {
if (String(url).endsWith("/api/connect/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
return Promise.resolve(
@@ -713,7 +713,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/cloud/link-proof")) {
if (String(url).endsWith("/api/connect/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
if (String(url).endsWith("/v1/client/environment-links")) {
@@ -301,7 +301,7 @@ export function linkEnvironmentToCloud(input: {
),
);
const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
const proof = yield* environmentClient.cloud
const proof = yield* environmentClient.connect
.linkProof({
headers: { authorization: `Bearer ${localBearerToken}` },
payload: {
@@ -336,7 +336,7 @@ export function linkEnvironmentToCloud(input: {
link,
});
yield* environmentClient.cloud
yield* environmentClient.connect
.relayConfig({
headers: { authorization: `Bearer ${localBearerToken}` },
payload: {
@@ -35,6 +35,7 @@ import { ProjectionCheckpointRepository } from "../src/persistence/Services/Proj
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
@@ -293,6 +294,7 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
);
const providerRegistryLayer = makeProviderRegistryLayer();
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
@@ -375,6 +377,7 @@ export const makeOrchestrationIntegrationHarness = (
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(orchestrationReactorLayer),
Layer.provideMerge(providerRegistryLayer),
Layer.provide(persistenceLayer),
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(ServerSettingsService.layerTest()),
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.24",
"version": "0.0.27",
"license": "MIT",
"repository": {
"type": "git",
+83 -3
View File
@@ -18,9 +18,15 @@ const emitInterleavedAssistantToolCalls =
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
const permissionOptionIds = {
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
rejectOnce: process.env.T3_ACP_REJECT_ONCE_OPTION_ID ?? "reject-once",
};
const sessionId = "mock-session-1";
let currentModeId = "ask";
@@ -237,6 +243,21 @@ function modeState(): AcpSchema.SessionModeState {
};
}
const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
{ modelId: "grok-build", name: "Grok Build" },
{ modelId: "grok-mock-alt", name: "Grok Mock Alt" },
];
function modelState(): AcpSchema.SessionModelState {
const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
? currentModelId
: "grok-build";
return {
currentModelId: modelId,
availableModels: grokAcpModels,
};
}
const program = Effect.gen(function* () {
const agent = yield* EffectAcpAgent.AcpAgent;
@@ -257,6 +278,7 @@ const program = Effect.gen(function* () {
Effect.succeed({
sessionId,
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
}),
);
@@ -273,11 +295,28 @@ const program = Effect.gen(function* () {
.pipe(
Effect.as({
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
}),
),
);
yield* agent.handleSetSessionModel((request) =>
Effect.gen(function* () {
if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
return yield* AcpError.AcpRequestError.invalidParams(
`Unknown mock model id: ${request.modelId}`,
{
method: "session/set_model",
params: request,
},
);
}
currentModelId = request.modelId;
return {};
}),
);
yield* agent.handleSetSessionConfigOption((request) =>
Effect.gen(function* () {
if (exitOnSetConfigOption) {
@@ -419,9 +458,13 @@ const program = Effect.gen(function* () {
],
},
options: [
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
{ optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
{
optionId: permissionOptionIds.allowAlways,
name: "Allow always",
kind: "allow_always",
},
{ optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
],
});
@@ -514,6 +557,43 @@ const program = Effect.gen(function* () {
return { stopReason: "end_turn" };
}
if (emitXAiAskUserQuestion) {
const result = yield* agent.client.extRequest("_x.ai/ask_user_question", {
method: "x.ai/ask_user_question",
params: {
sessionId: requestedSessionId,
toolCallId: "ask-user-question-tool-call-1",
questions: [
{
question: "Which scope should Grok use?",
multiSelect: null,
options: [
{ label: "Workspace", description: "Use the current workspace" },
{ label: "Session", description: "Only use this session" },
],
},
],
mode: "default",
},
});
if (typeof result !== "object" || result === null || !("outcome" in result)) {
throw new Error("Expected _x.ai/ask_user_question response outcome.");
}
if (result.outcome === "cancelled") {
return { stopReason: "end_turn" };
}
if (
result.outcome !== "accepted" ||
!("answers" in result) ||
typeof result.answers !== "object" ||
result.answers === null
) {
throw new Error("Expected accepted _x.ai/ask_user_question response answers.");
}
return { stopReason: "end_turn" };
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
+26 -24
View File
@@ -38,11 +38,11 @@ import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
const cloudCli = makeCli({ cloudEnabled: true });
const noCloudCli = makeCli({ cloudEnabled: false });
const connectCli = makeCli({ cloudEnabled: true });
const noConnectCli = makeCli({ cloudEnabled: false });
const runCli = (args: ReadonlyArray<string>, command = cli) =>
Command.runWith(command, { version: "0.0.0" })(args);
const runCloudCli = (args: ReadonlyArray<string>) => runCli(args, cloudCli);
const runConnectCli = (args: ReadonlyArray<string>) => runCli(args, connectCli);
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
runCli(args).pipe(Effect.provide(CliRuntimeLayer));
@@ -179,9 +179,9 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);
it.effect("rejects cloud commands when public cloud configuration is missing", () =>
it.effect("rejects connect commands when public configuration is missing", () =>
Effect.gen(function* () {
const error = yield* runCli(["cloud", "status"], noCloudCli).pipe(Effect.flip);
const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
@@ -189,20 +189,20 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
if (error._tag !== "ShowHelp") {
assert.fail(`Expected ShowHelp, got ${error._tag}`);
}
assert.deepEqual(error.commandPath, ["t3", "cloud"]);
assert.include(error.errors[0]?.message ?? "", "missing T3 Cloud public configuration");
assert.deepEqual(error.commandPath, ["t3", "connect"]);
assert.include(error.errors[0]?.message ?? "", "missing T3 Connect public configuration");
const output = (yield* TestConsole.errorLines).join("\n");
assert.include(output, "ERROR");
assert.include(output, "missing T3 Cloud public configuration");
assert.include(output, "missing T3 Connect public configuration");
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
);
it.effect("reports fresh headless cloud state without requiring local configuration", () =>
it.effect("reports fresh headless connect state without requiring local configuration", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-test-"));
const { output } = yield* captureStdout(
runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]),
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const status = JSON.parse(output) as {
@@ -221,21 +221,21 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);
it.effect("reports actionable human-readable headless cloud state", () =>
it.effect("reports actionable human-readable headless connect state", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-human-test-"));
const { output } = yield* captureStdout(
runCloudCli(["cloud", "status", "--base-dir", baseDir]),
runConnectCli(["connect", "status", "--base-dir", baseDir]),
);
assert.include(output, "T3 Cloud\n Exposure: disabled");
assert.include(output, "T3 Connect\n Exposure: disabled");
assert.include(output, " Authorization: missing");
assert.include(output, " Environment link: not provisioned");
assert.include(output, "Next: Run `t3 cloud link` to authorize and enable cloud exposure.");
assert.include(output, "Next: Run `t3 connect link` to authorize and enable T3 Connect.");
}),
);
it.effect("logs in to headless cloud without enabling exposure", () =>
it.effect("logs in to headless connect without enabling access", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-login-test-"));
const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
@@ -250,9 +250,11 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);
const login = yield* captureStdout(runCloudCli(["cloud", "login", "--base-dir", baseDir]));
const login = yield* captureStdout(
runConnectCli(["connect", "login", "--base-dir", baseDir]),
);
const status = yield* captureStdout(
runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]),
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const decoded = JSON.parse(status.output) as {
@@ -260,24 +262,24 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
readonly authenticated: boolean;
};
assert.equal(login.output, "Signed in to T3 Cloud.");
assert.equal(login.output, "Signed in to T3 Connect.");
assert.isFalse(decoded.desired);
assert.isTrue(decoded.authenticated);
}),
);
it.effect("disables headless cloud exposure without a running server", () =>
it.effect("disables headless connect without a running server", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-unlink-test-"));
const { output } = yield* captureStdout(
runCloudCli(["cloud", "unlink", "--base-dir", baseDir]),
runConnectCli(["connect", "unlink", "--base-dir", baseDir]),
);
assert.equal(output, "T3 Cloud exposure is disabled locally.");
assert.equal(output, "T3 Connect is disabled locally.");
}),
);
it.effect("logs out of headless cloud and removes the stored CLI authorization", () =>
it.effect("logs out of headless connect and removes the stored CLI authorization", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-logout-test-"));
const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
@@ -286,10 +288,10 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
writeFileSync(tokenPath, "invalid persisted token");
const { output } = yield* captureStdout(
runCloudCli(["cloud", "logout", "--base-dir", baseDir]),
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
);
assert.equal(output, "Signed out of T3 Cloud locally.");
assert.equal(output, "Signed out of T3 Connect locally.");
assert.isFalse(existsSync(tokenPath));
}),
);
+10 -10
View File
@@ -8,7 +8,7 @@ import * as CliError from "effect/unstable/cli/CliError";
import * as NetService from "@t3tools/shared/Net";
import packageJson from "../package.json" with { type: "json" };
import { authCommand } from "./cli/auth.ts";
import { cloudCommand } from "./cli/cloud.ts";
import { connectCommand } from "./cli/connect.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
@@ -16,23 +16,23 @@ import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
const cloudPublicConfigMissingMessage =
"T3 Cloud commands are unavailable: this build is missing T3 Cloud public configuration.";
const connectPublicConfigMissingMessage =
"T3 Connect commands are unavailable: this build is missing T3 Connect public configuration.";
class CloudPublicConfigMissingError extends CliError.UserError {
class ConnectPublicConfigMissingError extends CliError.UserError {
override get message() {
return cloudPublicConfigMissingMessage;
return connectPublicConfigMissingMessage;
}
}
const cloudUnavailableCommand = Command.make("cloud").pipe(
Command.withDescription("T3 Cloud is unavailable in builds without public cloud configuration."),
const connectUnavailableCommand = Command.make("connect").pipe(
Command.withDescription("T3 Connect is unavailable in builds without public configuration."),
Command.withHidden,
Command.withHandler(() =>
Effect.fail(
new CliError.ShowHelp({
commandPath: ["t3", "cloud"],
errors: [new CloudPublicConfigMissingError({ cause: cloudPublicConfigMissingMessage })],
commandPath: ["t3", "connect"],
errors: [new ConnectPublicConfigMissingError({ cause: connectPublicConfigMissingMessage })],
}),
),
),
@@ -47,7 +47,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
serveCommand,
authCommand,
projectCommand,
cloudEnabled ? cloudCommand : cloudUnavailableCommand,
cloudEnabled ? connectCommand : connectUnavailableCommand,
]),
);
@@ -3,7 +3,7 @@ import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { acquireRelayClientForLink } from "./cloud.ts";
import { acquireRelayClientForLink } from "./connect.ts";
const managedExecutable = {
status: "available",
@@ -89,15 +89,15 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
? "pending server startup"
: "not provisioned";
const nextStep = !status.authenticated
? "Run `t3 cloud link` to authorize and enable cloud exposure."
? "Run `t3 connect link` to authorize and enable T3 Connect."
: !status.desired
? "Run `t3 cloud link` to enable cloud exposure."
? "Run `t3 connect link` to enable T3 Connect."
: !status.linked
? "Start T3 to provision the environment link and launch its managed tunnel."
: undefined;
return [
"T3 Cloud",
"T3 Connect",
` Exposure: ${status.desired ? "enabled" : "disabled"}`,
` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
` Environment link: ${provisioned}`,
@@ -112,7 +112,7 @@ const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5);
const confirmRelayClientInstall = (version: string) =>
Prompt.run(
Prompt.confirm({
message: `The T3 relay client is required for T3 Cloud exposure. Download and install version ${version}?`,
message: `The T3 relay client is required for T3 Connect. Download and install version ${version}?`,
initial: false,
}),
);
@@ -169,7 +169,7 @@ const withCloudCliSessionToken = <A, E, R>(
environmentAuth.issueSession({
scopes: [AuthRelayWriteScope],
subject: "cloud-cli",
label: "t3 cloud cli",
label: "t3 connect cli",
}),
(issued) => run(issued.token),
(issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
@@ -194,7 +194,7 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
baseUrl: runtimeState.value.origin,
}).pipe(
Effect.flatMap((client) =>
client.cloud.unlink({ headers: { authorization: `Bearer ${token}` } }),
client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),
),
Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
),
@@ -249,24 +249,24 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
if (liveResult.status === "failed") {
yield* Console.warn(
`T3 Cloud exposure is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
`T3 Connect is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
);
} else {
yield* Console.log("T3 Cloud exposure is disabled locally.");
yield* Console.log("T3 Connect is disabled locally.");
}
if (Exit.isFailure(relayResult)) {
yield* Console.warn(
options.clearAuthorization
? `Could not revoke the relay-side environment record before signing out: ${String(relayResult.cause)}\nThe stored CLI authorization was still removed locally.`
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 cloud unlink\` again when the relay is reachable.`,
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 connect unlink\` again when the relay is reachable.`,
);
} else if (relayResult.value.status === "revoked") {
yield* Console.log("Revoked the relay-side environment record.");
}
if (options.clearAuthorization) {
yield* Console.log("Signed out of T3 Cloud locally.");
yield* Console.log("Signed out of T3 Connect locally.");
}
});
@@ -307,26 +307,26 @@ const runCloudCommand = <A, E>(
return yield* run.pipe(Effect.provide(runtimeLayer));
});
const cloudLoginCommand = Command.make("login", {
const connectLoginCommand = Command.make("login", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Authorize the T3 Cloud CLI without enabling cloud exposure."),
Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.get;
yield* Console.log("Signed in to T3 Cloud.");
yield* Console.log("Signed in to T3 Connect.");
}),
),
),
);
const cloudLinkCommand = Command.make("link", {
const connectLinkCommand = Command.make("link", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Authorize this environment for T3 Cloud and expose it on next start."),
Command.withDescription("Authorize this environment for T3 Connect on next start."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
@@ -338,7 +338,7 @@ const cloudLinkCommand = Command.make("link", {
reportRelayClientInstallProgress,
);
if (Option.isNone(installed)) {
yield* Console.log("T3 Cloud link cancelled. The relay client was not installed.");
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
return;
}
yield* Console.log(
@@ -349,18 +349,18 @@ const cloudLinkCommand = Command.make("link", {
yield* tokens.get;
yield* CliState.setCliDesiredCloudLink(true);
yield* Console.log(
"This T3 environment will be available over T3 Cloud the next time T3 starts.",
"This T3 environment will be available through T3 Connect the next time T3 starts.",
);
}),
),
),
);
const cloudStatusCommand = Command.make("status", {
const connectStatusCommand = Command.make("status", {
...projectLocationFlags,
json: jsonFlag,
}).pipe(
Command.withDescription("Show persisted T3 Cloud and relay client state."),
Command.withDescription("Show persisted T3 Connect and relay client state."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
@@ -395,31 +395,31 @@ const cloudStatusCommand = Command.make("status", {
),
);
const cloudUnlinkCommand = Command.make("unlink", {
const connectUnlinkCommand = Command.make("unlink", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Disable T3 Cloud exposure while retaining the stored authorization."),
Command.withDescription("Disable T3 Connect while retaining the stored authorization."),
Command.withHandler((flags) =>
runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })),
),
);
const cloudLogoutCommand = Command.make("logout", {
const connectLogoutCommand = Command.make("logout", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Disable T3 Cloud exposure and clear the stored CLI authorization."),
Command.withDescription("Disable T3 Connect and clear the stored CLI authorization."),
Command.withHandler((flags) =>
runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })),
),
);
export const cloudCommand = Command.make("cloud").pipe(
Command.withDescription("Manage headless T3 Cloud exposure."),
export const connectCommand = Command.make("connect").pipe(
Command.withDescription("Manage headless T3 Connect access."),
Command.withSubcommands([
cloudLoginCommand,
cloudLinkCommand,
cloudStatusCommand,
cloudUnlinkCommand,
cloudLogoutCommand,
connectLoginCommand,
connectLinkCommand,
connectStatusCommand,
connectUnlinkCommand,
connectLogoutCommand,
]),
);
+8 -8
View File
@@ -96,7 +96,7 @@ const make = Effect.gen(function* () {
const clear = secrets
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
.pipe(wrapError("Could not remove the stored T3 Cloud CLI credential."));
.pipe(wrapError("Could not remove the stored T3 Connect CLI credential."));
const read = Effect.fn("cloud.cli_token.read")(function* () {
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
@@ -146,7 +146,7 @@ const make = Effect.gen(function* () {
const url = new URL(request.originalUrl, metadata.redirectUri);
const code = url.searchParams.get("code");
if (url.searchParams.get("state") !== state || !code) {
return HttpServerResponse.text("Invalid T3 Cloud authorization callback.", {
return HttpServerResponse.text("Invalid T3 Connect authorization callback.", {
status: 400,
});
}
@@ -154,7 +154,7 @@ const make = Effect.gen(function* () {
return yield* HttpServerResponse.html`
<html>
<body style="font-family: sans-serif; text-align: center; margin-top: 50px;">
<h1>T3 Cloud authorization complete</h1>
<h1>T3 Connect authorization complete</h1>
<p>You can close this window and return to your terminal.</p>
</body>
</html>
@@ -182,13 +182,13 @@ const make = Effect.gen(function* () {
authorizationUrl.searchParams.set("state", state);
authorizationUrl.searchParams.set("code_challenge", challenge);
authorizationUrl.searchParams.set("code_challenge_method", "S256");
yield* Console.log(`Open this URL to authorize T3 Cloud:\n${authorizationUrl.toString()}\n`);
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
const code = yield* Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", () =>
Effect.fail(
new CloudCliTokenManagerError({
message: "Timed out waiting for T3 Cloud authorization.",
message: "Timed out waiting for T3 Connect authorization.",
}),
),
),
@@ -213,12 +213,12 @@ const make = Effect.gen(function* () {
});
const getExisting = semaphore.withPermits(1)(
getExistingNoLock().pipe(wrapError("Could not refresh the T3 Cloud CLI credential.")),
getExistingNoLock().pipe(wrapError("Could not refresh the T3 Connect CLI credential.")),
);
const hasCredential = semaphore.withPermits(1)(
read().pipe(
Effect.map(Option.isSome),
wrapError("Could not read the stored T3 Cloud CLI credential."),
wrapError("Could not read the stored T3 Connect CLI credential."),
),
);
const get = semaphore.withPermits(1)(
@@ -227,7 +227,7 @@ const make = Effect.gen(function* () {
return Option.isSome(token)
? token.value
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
}).pipe(wrapError("Could not authorize the T3 Cloud CLI.")),
}).pipe(wrapError("Could not authorize the T3 Connect CLI.")),
);
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
+1 -1
View File
@@ -76,7 +76,7 @@ describe("reconcileDesiredCloudLink", () => {
expect(error).toMatchObject({
_tag: "EnvironmentHttpUnauthorizedError",
message: "Run `t3 cloud link` to authorize this environment.",
message: "Run `t3 connect link` to authorize this environment.",
});
}).pipe(
Effect.provideService(
+6 -6
View File
@@ -509,7 +509,7 @@ const relayClientRequest = <A>(
Effect.mapError(
(cause) =>
new EnvironmentHttpInternalServerError({
message: `T3 Cloud relay request failed: ${String(cause)}`,
message: `T3 Connect relay request failed: ${String(cause)}`,
}),
),
);
@@ -535,7 +535,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
onNone: () =>
Effect.fail(
new EnvironmentHttpUnauthorizedError({
message: "Run `t3 cloud link` to authorize this environment.",
message: "Run `t3 connect link` to authorize this environment.",
}),
),
onSome: Effect.succeed,
@@ -595,7 +595,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
CloudCliTokenManagerError: (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
SecretStoreError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Cloud link state.",
"Could not persist desired T3 Connect link state.",
),
}),
);
@@ -874,7 +874,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
scopes: AuthStandardClientScopes,
subject: "cloud-connect",
ttl: Duration.minutes(2),
label: "T3 Cloud connect",
label: "T3 Connect connect",
proofKeyThumbprint: proof.clientProofKeyThumbprint,
});
const responsePayload = {
@@ -924,9 +924,9 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
}),
);
export const cloudHttpApiLayer = HttpApiBuilder.group(
export const connectHttpApiLayer = HttpApiBuilder.group(
EnvironmentHttpApi,
"cloud",
"connect",
Effect.fnUntraced(function* (handlers) {
const dependencies = yield* cloudHttpDependencies;
return handlers
@@ -28,6 +28,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { it as effectIt } from "@effect/vitest";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
@@ -40,6 +41,7 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { makeProviderRegistryLayer } from "../../provider/testUtils/providerRegistryMock.ts";
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
@@ -142,6 +144,7 @@ describe("ProviderCommandReactor", () => {
readonly baseDir?: string;
readonly threadModelSelection?: ModelSelection;
readonly sessionModelSwitch?: "unsupported" | "in-session";
readonly requiresNewThreadForModelChange?: boolean;
}) {
const now = "2026-01-01T00:00:00.000Z";
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
@@ -280,6 +283,14 @@ describe("ProviderCommandReactor", () => {
}),
),
);
const providerSnapshots = [
{
instanceId: modelSelection.instanceId,
...(input?.requiresNewThreadForModelChange === true
? { requiresNewThreadForModelChange: true }
: {}),
},
];
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: ProviderServiceShape = {
@@ -335,6 +346,7 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
Layer.provideMerge(Layer.succeed(ProviderService, service)),
Layer.provideMerge(makeProviderRegistryLayer(providerSnapshots as never)),
Layer.provideMerge(
Layer.mock(GitWorkflowService)({
renameBranch,
@@ -879,6 +891,80 @@ describe("ProviderCommandReactor", () => {
});
});
effectIt.effect(
"rejects changing models after start when the provider requires a new thread",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() =>
createHarness({ requiresNewThreadForModelChange: true }),
);
const now = "2026-01-01T00:00:00.000Z";
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-restricted-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-restricted-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-restricted-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-restricted-2"),
role: "user",
text: "second",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.1-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() =>
waitFor(async () => {
const readModel = await harness.readModel();
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.make("thread-1"),
);
return (
thread?.activities.some(
(activity) => activity.kind === "provider.turn.start.failed",
) ?? false
);
}),
);
expect(harness.sendTurn).toHaveBeenCalledTimes(1);
const readModel = yield* Effect.promise(() => harness.readModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining(
"cannot switch models after the conversation has started",
),
},
});
}),
);
it("starts a first turn on the requested provider instance even when it differs from the thread model", async () => {
const harness = await createHarness({
threadModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
@@ -31,6 +31,7 @@ import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
@@ -180,6 +181,7 @@ const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
const providerRegistry = yield* ProviderRegistry;
const gitWorkflow = yield* GitWorkflowService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
@@ -305,6 +307,38 @@ const make = Effect.gen(function* () {
.pipe(Effect.map(Option.getOrUndefined));
});
const rejectStartedThreadModelChangeIfRequired = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly currentModelSelection: ModelSelection;
readonly requestedModelSelection: ModelSelection | undefined;
}) {
const requestedModelSelection = input.requestedModelSelection;
if (
requestedModelSelection === undefined ||
(input.currentModelSelection.instanceId === requestedModelSelection.instanceId &&
input.currentModelSelection.model === requestedModelSelection.model)
) {
return;
}
const providers = yield* providerRegistry.getProviders;
const requiresNewThread =
providers.find((snapshot) => snapshot.instanceId === input.currentModelSelection.instanceId)
?.requiresNewThreadForModelChange === true ||
providers.find((snapshot) => snapshot.instanceId === requestedModelSelection.instanceId)
?.requiresNewThreadForModelChange === true;
if (!requiresNewThread) {
return;
}
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabelFromInstanceHint({
instanceId: String(requestedModelSelection.instanceId),
modelSelectionInstanceId: String(input.currentModelSelection.instanceId),
}),
method: "thread.turn.start",
detail: `Thread '${input.threadId}' cannot switch models after the conversation has started. Start a new thread to use '${requestedModelSelection.model}'.`,
});
});
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
threadId: ThreadId,
createdAt: string,
@@ -384,6 +418,20 @@ const make = Effect.gen(function* () {
});
}
const preferredProvider: ProviderDriverKind = desiredDriverKind;
if (thread.session !== null) {
yield* rejectStartedThreadModelChangeIfRequired({
threadId,
currentModelSelection:
activeSession?.model !== undefined
? {
...thread.modelSelection,
instanceId: currentInstanceId,
model: activeSession.model,
}
: thread.modelSelection,
requestedModelSelection,
});
}
if (
thread.session !== null &&
requestedModelSelection !== undefined &&
@@ -0,0 +1,153 @@
import { GrokSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import { makeGrokTextGeneration } from "../../textGeneration/GrokTextGeneration.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeGrokAdapter } from "../Layers/GrokAdapter.ts";
import {
buildInitialGrokProviderSnapshot,
checkGrokProviderStatus,
enrichGrokSnapshot,
} from "../Layers/GrokProvider.ts";
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
defaultProviderContinuationIdentity,
type ProviderDriver,
type ProviderInstance,
} from "../ProviderDriver.ts";
import type { ServerProviderDraft } from "../providerSnapshot.ts";
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
import {
makeManualOnlyProviderMaintenanceCapabilities,
makeStaticProviderMaintenanceResolver,
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
const DRIVER_KIND = ProviderDriverKind.make("grok");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const UPDATE = makeStaticProviderMaintenanceResolver(
makeManualOnlyProviderMaintenanceCapabilities({
provider: DRIVER_KIND,
packageName: null,
}),
);
export type GrokDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| ProviderEventLoggers
| ServerConfig;
const withInstanceIdentity =
(input: {
readonly instanceId: ProviderInstance["instanceId"];
readonly displayName: string | undefined;
readonly accentColor: string | undefined;
readonly continuationGroupKey: string;
}) =>
(snapshot: ServerProviderDraft): ServerProvider => ({
...snapshot,
instanceId: input.instanceId,
driver: DRIVER_KIND,
...(input.displayName ? { displayName: input.displayName } : {}),
...(input.accentColor ? { accentColor: input.accentColor } : {}),
continuation: { groupKey: input.continuationGroupKey },
});
export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
driverKind: DRIVER_KIND,
metadata: {
displayName: "Grok",
supportsMultipleInstances: true,
},
configSchema: GrokSettings,
defaultConfig: (): GrokSettings => decodeGrokSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const eventLoggers = yield* ProviderEventLoggers;
const processEnv = mergeProviderInstanceEnvironment(environment);
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: DRIVER_KIND,
instanceId,
});
const stampIdentity = withInstanceIdentity({
instanceId,
displayName,
accentColor,
continuationGroupKey: continuationIdentity.continuationKey,
});
const effectiveConfig = { ...config, enabled } satisfies GrokSettings;
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
binaryPath: effectiveConfig.binaryPath,
env: processEnv,
});
const adapter = yield* makeGrokAdapter(effectiveConfig, {
environment: processEnv,
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
instanceId,
});
const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe(
Effect.map(stampIdentity),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const snapshot = yield* makeManagedServerProvider<GrokSettings>({
maintenanceCapabilities,
getSettings: Effect.succeed(effectiveConfig),
streamSettings: Stream.never,
haveSettingsChanged: () => false,
initialSnapshot: (settings) =>
buildInitialGrokProviderSnapshot(settings).pipe(Effect.map(stampIdentity)),
checkProvider,
enrichSnapshot: ({ snapshot: currentSnapshot, publishSnapshot }) =>
enrichGrokSnapshot({
snapshot: currentSnapshot,
maintenanceCapabilities,
publishSnapshot,
httpClient,
}),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderDriverError({
driver: DRIVER_KIND,
instanceId,
detail: `Failed to build Grok snapshot: ${cause.message ?? String(cause)}`,
cause,
}),
),
);
return {
instanceId,
driverKind: DRIVER_KIND,
continuationIdentity,
displayName,
accentColor,
enabled,
snapshot,
adapter,
textGeneration,
} satisfies ProviderInstance;
}),
};
@@ -447,6 +447,29 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("preserves xhigh effort for Claude Fable 5", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-fable-5",
[{ id: "effort", value: "xhigh" }],
),
runtimeMode: "full-access",
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.effort, "xhigh");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -48,50 +48,42 @@ const CLAUDE_PRESENTATION = {
displayName: "Claude",
showInteractionModeToggle: true,
} as const;
const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
const CLAUDE_EFFORT_OPTIONS = {
opus48: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "xhigh", label: "Extra High" },
{ value: "max", label: "Max" },
{ value: "ultracode", label: "Ultracode" },
{ value: "ultrathink", label: "Ultrathink" },
],
opus47: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
opus46: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
sonnet46: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
opus45: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
],
} as const;
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-fable-5",
name: "Claude Fable 5",
isCustom: false,
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "xhigh", label: "Extra High" },
{ value: "max", label: "Max" },
{ value: "ultracode", label: "Ultracode" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
}),
},
{
slug: "claude-opus-4-8",
name: "Claude Opus 4.8",
@@ -101,9 +93,21 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: CLAUDE_EFFORT_OPTIONS.opus48,
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "xhigh", label: "Extra High" },
{ value: "max", label: "Max" },
{ value: "ultracode", label: "Ultracode" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildBooleanOptionDescriptor({
id: "fastMode",
label: "Fast Mode",
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
@@ -124,9 +128,20 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: CLAUDE_EFFORT_OPTIONS.opus47,
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildBooleanOptionDescriptor({
id: "fastMode",
label: "Fast Mode",
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
@@ -147,7 +162,13 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: CLAUDE_EFFORT_OPTIONS.opus46,
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildBooleanOptionDescriptor({
@@ -174,7 +195,12 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: CLAUDE_EFFORT_OPTIONS.opus45,
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
],
}),
buildBooleanOptionDescriptor({
id: "fastMode",
@@ -192,7 +218,13 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: CLAUDE_EFFORT_OPTIONS.sonnet46,
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildSelectOptionDescriptor({
@@ -221,6 +253,10 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
function supportsClaudeFable5(version: string | null | undefined): boolean {
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;
}
function supportsClaudeOpus48(version: string | null | undefined): boolean {
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_8_VERSION) >= 0 : false;
}
@@ -233,6 +269,9 @@ function getBuiltInClaudeModelsForVersion(
version: string | null | undefined,
): ReadonlyArray<ServerProviderModel> {
return BUILT_IN_MODELS.filter((model) => {
if (model.slug === "claude-fable-5") {
return supportsClaudeFable5(version);
}
if (model.slug === "claude-opus-4-8") {
return supportsClaudeOpus48(version);
}
@@ -243,6 +282,11 @@ function getBuiltInClaudeModelsForVersion(
});
}
function formatClaudeFable5UpgradeMessage(version: string | null): string {
const versionLabel = version ? `v${version}` : "the installed version";
return `Claude Code ${versionLabel} is too old for Claude Fable 5. Upgrade to v${MINIMUM_CLAUDE_FABLE_5_VERSION} or newer to access it.`;
}
function formatClaudeOpus48UpgradeMessage(version: string | null): string {
const versionLabel = version ? `v${version}` : "the installed version";
return `Claude Code ${versionLabel} is too old for Claude Opus 4.8. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_8_VERSION} or newer to access it.`;
@@ -294,7 +338,7 @@ export function normalizeClaudeCliEffort(
if (effort === "ultracode") {
return "xhigh";
}
if (effort === "xhigh" && model !== "claude-opus-4-8") {
if (effort === "xhigh" && model !== "claude-fable-5" && model !== "claude-opus-4-8") {
return "max";
}
if (effort === "max" && model === "claude-sonnet-4-6") {
@@ -688,11 +732,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
const versionUpgradeMessage = supportsClaudeOpus48(parsedVersion)
const versionUpgradeMessage = supportsClaudeFable5(parsedVersion)
? undefined
: supportsClaudeOpus47(parsedVersion)
? formatClaudeOpus48UpgradeMessage(parsedVersion)
: formatClaudeOpus47UpgradeMessage(parsedVersion);
: supportsClaudeOpus48(parsedVersion)
? formatClaudeFable5UpgradeMessage(parsedVersion)
: supportsClaudeOpus47(parsedVersion)
? formatClaudeOpus48UpgradeMessage(parsedVersion)
: formatClaudeOpus47UpgradeMessage(parsedVersion);
const capabilities = resolveCapabilities
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
@@ -0,0 +1,377 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as path from "node:path";
import * as os from "node:os";
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import {
ApprovalRequestId,
GrokSettings,
ProviderDriverKind,
ThreadId,
ProviderInstanceId,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { makeGrokAdapter } from "./GrokAdapter.ts";
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const mockAgentCommand = process.execPath;
async function makeMockGrokWrapper(extraEnv?: Record<string, string>) {
const dir = await mkdtemp(path.join(os.tmpdir(), "grok-acp-mock-"));
const wrapperPath = path.join(dir, "fake-grok.sh");
const envExports = Object.entries(extraEnv ?? {})
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
.join("\n");
const script = `#!/bin/sh
${envExports}
exec ${JSON.stringify(mockAgentCommand)} ${JSON.stringify(mockAgentPath)} "$@"
`;
await writeFile(wrapperPath, script, "utf8");
await chmod(wrapperPath, 0o755);
return wrapperPath;
}
function waitForFileContent(filePath: string, attempts = 40): Effect.Effect<string> {
const readAttempt = (remainingAttempts: number): Effect.Effect<string> =>
Effect.gen(function* () {
if (remainingAttempts <= 0) {
return yield* Effect.die(new Error(`Timed out waiting for file content at ${filePath}`));
}
const raw = yield* Effect.tryPromise(() => readFile(filePath, "utf8")).pipe(
Effect.orElseSucceed(() => ""),
);
if (raw.trim().length > 0) {
return raw;
}
yield* Effect.sleep("25 millis");
return yield* readAttempt(remainingAttempts - 1);
});
return readAttempt(attempts);
}
async function readJsonLines(filePath: string) {
const raw = await readFile(filePath, "utf8");
return raw
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as Record<string, unknown>);
}
const grokAdapterTestLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-grok-adapter-test-",
}).pipe(Layer.provideMerge(NodeServices.layer));
const makeTestAdapter = (binaryPath: string, options?: Parameters<typeof makeGrokAdapter>[1]) =>
makeGrokAdapter(decodeGrokSettings({ binaryPath }), options).pipe(Effect.orDie);
it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
it.effect("starts a session and maps mock ACP prompt flow to runtime events", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-mock-thread");
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath);
const runtimeEvents: ProviderRuntimeEvent[] = [];
const turnCompleted = yield* Deferred.make<void>();
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}).pipe(
Effect.andThen(
event.type === "turn.completed"
? Deferred.succeed(turnCompleted, undefined)
: Effect.void,
),
),
).pipe(Effect.forkChild);
const session = yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-mock-alt" },
});
assert.equal(session.provider, "grok");
assert.equal(session.model, "grok-mock-alt");
assert.deepStrictEqual(session.resumeCursor, {
schemaVersion: 1,
sessionId: "mock-session-1",
});
yield* adapter.sendTurn({
threadId,
input: "hello grok",
attachments: [],
});
yield* Deferred.await(turnCompleted);
yield* Fiber.interrupt(runtimeEventsFiber);
const types = runtimeEvents.map((e) => e.type);
assert.includeMembers(types, [
"session.started",
"session.state.changed",
"thread.started",
"turn.started",
"item.started",
"content.delta",
"turn.completed",
] as const);
const delta = runtimeEvents.find((e) => e.type === "content.delta");
assert.isDefined(delta);
if (delta?.type === "content.delta") {
assert.equal(delta.payload.delta, "hello from mock");
}
yield* adapter.stopSession(threadId);
}),
);
it.effect("closes the ACP child process when a session stops", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-stop-session-close");
const tempDir = yield* Effect.promise(() =>
mkdtemp(path.join(os.tmpdir(), "grok-adapter-exit-log-")),
);
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
yield* adapter.stopSession(threadId);
const exitLog = yield* waitForFileContent(exitLogPath);
assert.include(exitLog, "SIGTERM");
}),
);
it.effect("rejects startSession when provider mismatches", () =>
Effect.gen(function* () {
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath);
const threadId = ThreadId.make("grok-provider-mismatch");
const error = yield* Effect.flip(
adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
}),
);
assert.equal(error._tag, "ProviderAdapterValidationError");
}),
);
it.effect("rejects sendTurn with empty input and no attachments", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-empty-turn");
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
});
const error = yield* Effect.flip(
adapter.sendTurn({
threadId,
input: " ",
attachments: [],
}),
);
assert.equal(error._tag, "ProviderAdapterValidationError");
yield* adapter.stopSession(threadId);
}),
);
it.effect("responds to ACP approvals using provider-supplied option ids", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-custom-approval-option-id");
const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "grok-acp-")));
const requestLogPath = path.join(tempDir, "requests.ndjson");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
T3_ACP_EMIT_TOOL_CALLS: "1",
T3_ACP_ALLOW_ONCE_OPTION_ID: "agent-defined-approval-id",
}),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
event.type === "request.opened"
? adapter.respondToRequest(
threadId,
ApprovalRequestId.make(String(event.requestId)),
"accept",
)
: Effect.void,
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "approval-required",
});
yield* adapter.sendTurn({ threadId, input: "approve this", attachments: [] });
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
assert.isTrue(
requests.some(
(entry) =>
!("method" in entry) &&
typeof entry.result === "object" &&
entry.result !== null &&
"outcome" in entry.result &&
typeof entry.result.outcome === "object" &&
entry.result.outcome !== null &&
"optionId" in entry.result.outcome &&
entry.result.outcome.optionId === "agent-defined-approval-id",
),
);
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("handles xAI ask_user_question extension requests", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-xai-ask-user-question");
const wrapperPath = yield* Effect.promise(() =>
makeMockGrokWrapper({ T3_ACP_EMIT_XAI_ASK_USER_QUESTION: "1" }),
);
const adapter = yield* makeTestAdapter(wrapperPath);
const requested =
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "user-input.requested" }>>();
const resolved =
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "user-input.resolved" }>>();
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
if (String(event.threadId) !== String(threadId)) {
return Effect.void;
}
if (event.type === "user-input.requested") {
return Deferred.succeed(requested, event).pipe(Effect.ignore);
}
if (event.type === "user-input.resolved") {
return Deferred.succeed(resolved, event).pipe(Effect.ignore);
}
return Effect.void;
}).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
});
const sendTurnFiber = yield* adapter
.sendTurn({ threadId, input: "ask before continuing", attachments: [] })
.pipe(Effect.forkChild);
const requestedEvent = yield* Deferred.await(requested);
assert.equal(requestedEvent.payload.questions.length, 1);
assert.equal(requestedEvent.payload.questions[0]?.id, "Which scope should Grok use?");
assert.equal(requestedEvent.payload.questions[0]?.question, "Which scope should Grok use?");
assert.equal(requestedEvent.raw?.method, "_x.ai/ask_user_question");
yield* adapter.respondToUserInput(
threadId,
ApprovalRequestId.make(String(requestedEvent.requestId)),
{
"Which scope should Grok use?": "Workspace",
},
);
const resolvedEvent = yield* Deferred.await(resolved);
assert.deepEqual(resolvedEvent.payload.answers, {
"Which scope should Grok use?": "Workspace",
});
yield* Fiber.join(sendTurnFiber);
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
it.effect("continues streaming events when native notification logging fails", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-native-log-failure");
const wrapperPath = yield* Effect.promise(() => makeMockGrokWrapper());
const adapter = yield* makeTestAdapter(wrapperPath, {
nativeEventLogger: {
filePath: "memory://grok-native-events",
write: (record: unknown) =>
typeof record === "object" &&
record !== null &&
"event" in record &&
typeof record.event === "object" &&
record.event !== null &&
"kind" in record.event &&
record.event.kind === "notification"
? Effect.die(new Error("native log write failed"))
: Effect.void,
close: () => Effect.void,
},
});
const contentDelta = yield* Deferred.make<void>();
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
event.type === "content.delta" ? Deferred.succeed(contentDelta, undefined) : Effect.void,
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("grok"),
cwd: process.cwd(),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({ threadId, input: "keep streaming", attachments: [] });
yield* Deferred.await(contentDelta);
yield* Fiber.interrupt(eventsFiber);
yield* adapter.stopSession(threadId);
}),
);
});
@@ -0,0 +1,934 @@
import {
ApprovalRequestId,
type GrokSettings,
EventId,
type ProviderApprovalDecision,
type ProviderRuntimeEvent,
type ProviderSession,
type ProviderUserInputAnswers,
ProviderDriverKind,
ProviderInstanceId,
RuntimeRequestId,
type ThreadId,
TurnId,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as SynchronizedRef from "effect/SynchronizedRef";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
ProviderAdapterSessionNotFoundError,
ProviderAdapterValidationError,
} from "../Errors.ts";
import { mapAcpToAdapterError } from "../acp/AcpAdapterSupport.ts";
import { type AcpSessionRuntimeShape } from "../acp/AcpSessionRuntime.ts";
import {
makeAcpAssistantItemEvent,
makeAcpContentDeltaEvent,
makeAcpPlanUpdatedEvent,
makeAcpRequestOpenedEvent,
makeAcpRequestResolvedEvent,
makeAcpToolCallEvent,
} from "../acp/AcpCoreRuntimeEvents.ts";
import { parsePermissionRequest } from "../acp/AcpRuntimeModel.ts";
import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";
import {
applyGrokAcpModelSelection,
currentGrokModelIdFromSessionSetup,
makeGrokAcpRuntime,
resolveGrokAcpBaseModelId,
} from "../acp/GrokAcpSupport.ts";
import {
extractXAiAskUserQuestions,
makeXAiAskUserQuestionCancelledResponse,
makeXAiAskUserQuestionResponse,
XAiAskUserQuestionRequest,
} from "../acp/XAiAcpExtension.ts";
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
const PROVIDER = ProviderDriverKind.make("grok");
const GROK_RESUME_VERSION = 1 as const;
function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
const result = encodeUnknownJsonStringExit(input);
return Exit.isSuccess(result) ? result.value : undefined;
}
export interface GrokAdapterLiveOptions {
readonly environment?: NodeJS.ProcessEnv;
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: EventNdjsonLogger;
readonly instanceId?: ProviderInstanceId;
}
interface PendingApproval {
readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
}
type PendingUserInputResolution =
| { readonly _tag: "answered"; readonly answers: ProviderUserInputAnswers }
| { readonly _tag: "cancelled" };
interface PendingUserInput {
readonly resolution: Deferred.Deferred<PendingUserInputResolution>;
}
interface GrokSessionContext {
readonly threadId: ThreadId;
readonly acpSessionId: string;
session: ProviderSession;
readonly scope: Scope.Closeable;
readonly acp: AcpSessionRuntimeShape;
notificationFiber: Fiber.Fiber<void, never> | undefined;
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
turns: Array<{ id: TurnId; items: Array<unknown> }>;
lastPlanFingerprint: string | undefined;
activeTurnId: TurnId | undefined;
currentModelId: string | undefined;
stopped: boolean;
}
function settlePendingApprovalsAsCancelled(
pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,
): Effect.Effect<void> {
return Effect.forEach(
Array.from(pendingApprovals.values()),
(pending) => Deferred.succeed(pending.decision, "cancel").pipe(Effect.ignore),
{ discard: true },
);
}
function settlePendingUserInputsAsCancelled(
pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,
): Effect.Effect<void> {
return Effect.forEach(
Array.from(pendingUserInputs.values()),
(pending) => Deferred.succeed(pending.resolution, { _tag: "cancelled" }).pipe(Effect.ignore),
{ discard: true },
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function parseGrokResume(raw: unknown): { sessionId: string } | undefined {
if (!isRecord(raw)) return undefined;
if (raw.schemaVersion !== GROK_RESUME_VERSION) return undefined;
if (typeof raw.sessionId !== "string" || !raw.sessionId.trim()) return undefined;
return { sessionId: raw.sessionId.trim() };
}
function selectPermissionOptionId(
request: EffectAcpSchema.RequestPermissionRequest,
decision: Exclude<ProviderApprovalDecision, "cancel">,
): string | undefined {
const kind =
decision === "acceptForSession"
? "allow_always"
: decision === "accept"
? "allow_once"
: "reject_once";
const option = request.options.find((entry) => entry.kind === kind);
return option?.optionId.trim() || undefined;
}
function selectAutoApprovedPermissionOption(
request: EffectAcpSchema.RequestPermissionRequest,
): string | undefined {
return (
selectPermissionOptionId(request, "acceptForSession") ??
selectPermissionOptionId(request, "accept")
);
}
export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapterLiveOptions) {
return Effect.gen(function* () {
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("grok");
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native" })
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
const sessions = new Map<ThreadId, GrokSessionContext>();
const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "crypto/randomUUIDv4",
detail: "Failed to generate Grok runtime identifier.",
cause,
}),
),
);
const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));
const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
const mapAcpCallbackFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.mapError(
(cause) =>
new EffectAcpErrors.AcpTransportError({
detail: "Failed to process Grok ACP callback.",
cause,
}),
),
);
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
const getThreadSemaphore = (threadId: string) =>
SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(
current.get(threadId),
);
return Option.match(existing, {
onNone: () =>
Semaphore.make(1).pipe(
Effect.map((semaphore) => {
const next = new Map(current);
next.set(threadId, semaphore);
return [semaphore, next] as const;
}),
),
onSome: (semaphore) => Effect.succeed([semaphore, current] as const),
});
});
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
const logNative = (threadId: ThreadId, method: string, payload: unknown) =>
Effect.gen(function* () {
if (!nativeEventLogger) return;
const observedAt = yield* nowIso;
yield* nativeEventLogger.write(
{
observedAt,
event: {
id: yield* randomUUIDv4,
kind: "notification",
provider: PROVIDER,
createdAt: observedAt,
method,
threadId,
payload,
},
},
threadId,
);
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Failed to write native Grok notification log.", {
cause,
threadId,
method,
}),
),
);
const emitPlanUpdate = (
ctx: GrokSessionContext,
payload: {
readonly explanation?: string | null;
readonly plan: ReadonlyArray<{
readonly step: string;
readonly status: "pending" | "inProgress" | "completed";
}>;
},
rawPayload: unknown,
method: string,
) =>
Effect.gen(function* () {
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
if (ctx.lastPlanFingerprint === fingerprint) {
return;
}
ctx.lastPlanFingerprint = fingerprint;
yield* offerRuntimeEvent(
makeAcpPlanUpdatedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
payload,
source: "acp.jsonrpc",
method,
rawPayload,
}),
);
});
const requireSession = (
threadId: ThreadId,
): Effect.Effect<GrokSessionContext, ProviderAdapterSessionNotFoundError> => {
const ctx = sessions.get(threadId);
if (!ctx || ctx.stopped) {
return Effect.fail(
new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),
);
}
return Effect.succeed(ctx);
};
const stopSessionInternal = (ctx: GrokSessionContext) =>
Effect.gen(function* () {
if (ctx.stopped) return;
ctx.stopped = true;
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
if (ctx.notificationFiber) {
yield* Fiber.interrupt(ctx.notificationFiber);
}
yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
sessions.delete(ctx.threadId);
yield* offerRuntimeEvent({
type: "session.exited",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: ctx.threadId,
payload: { exitKind: "graceful" },
});
});
const startSession: GrokAdapterShape["startSession"] = (input) =>
withThreadLock(
input.threadId,
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== PROVIDER) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
});
}
if (!input.cwd?.trim()) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: "cwd is required and must be non-empty.",
});
}
const cwd = path.resolve(input.cwd.trim());
const grokModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const existing = sessions.get(input.threadId);
if (existing && !existing.stopped) {
yield* stopSessionInternal(existing);
}
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
const sessionScope = yield* Scope.make("sequential");
let sessionScopeTransferred = false;
yield* Effect.addFinalizer(() =>
sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
);
const resumeSessionId = parseGrokResume(input.resumeCursor)?.sessionId;
const acpNativeLoggers = makeAcpNativeLoggers({
nativeEventLogger,
provider: PROVIDER,
threadId: input.threadId,
});
const acp = yield* makeGrokAcpRuntime({
grokSettings,
...(options?.environment ? { environment: options.environment } : {}),
childProcessSpawner,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
...acpNativeLoggers,
}).pipe(
Effect.provideService(Scope.Scope, sessionScope),
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: cause.message,
cause,
}),
),
);
const started = yield* Effect.gen(function* () {
yield* Effect.forEach(
["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,
(method) =>
acp.handleExtRequest(method, XAiAskUserQuestionRequest, (params) =>
mapAcpCallbackFailure(
Effect.gen(function* () {
yield* logNative(input.threadId, method, params);
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const resolution = yield* Deferred.make<PendingUserInputResolution>();
pendingUserInputs.set(requestId, { resolution });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractXAiAskUserQuestions(params) },
raw: {
source: "acp.grok.extension",
method,
payload: params,
},
});
const resolved = yield* Deferred.await(resolution);
pendingUserInputs.delete(requestId);
const resolvedAnswers = resolved._tag === "answered" ? resolved.answers : {};
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolvedAnswers },
raw: {
source: "acp.grok.extension",
method,
payload: params,
},
});
switch (resolved._tag) {
case "answered":
return makeXAiAskUserQuestionResponse(params, resolved.answers);
case "cancelled":
return makeXAiAskUserQuestionCancelledResponse();
}
}),
),
),
{ discard: true },
);
yield* acp.handleRequestPermission((params) =>
mapAcpCallbackFailure(
Effect.gen(function* () {
yield* logNative(input.threadId, "session/request_permission", params);
if (input.runtimeMode === "full-access") {
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
if (autoApprovedOptionId !== undefined) {
return {
outcome: {
outcome: "selected" as const,
optionId: autoApprovedOptionId,
},
};
}
}
const permissionRequest = parsePermissionRequest(params);
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
pendingApprovals.set(requestId, { decision });
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail:
permissionRequest.detail ??
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
"[unserializable params]",
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: sessions.get(input.threadId)?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
const selectedOptionId =
resolved === "cancel" ? undefined : selectPermissionOptionId(params, resolved);
return {
outcome: selectedOptionId
? {
outcome: "selected" as const,
optionId: selectedOptionId,
}
: ({ outcome: "cancelled" } as const),
};
}),
),
);
return yield* acp.start();
}).pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
),
);
const requestedStartModelId = grokModelSelection?.model
? resolveGrokAcpBaseModelId(grokModelSelection.model)
: undefined;
const boundModelId = yield* applyGrokAcpModelSelection({
runtime: acp,
currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),
requestedModelId: requestedStartModelId,
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
const now = yield* nowIso;
const session: ProviderSession = {
provider: PROVIDER,
providerInstanceId: boundInstanceId,
status: "ready",
runtimeMode: input.runtimeMode,
cwd,
...(boundModelId ? { model: resolveGrokAcpBaseModelId(boundModelId) } : {}),
threadId: input.threadId,
resumeCursor: {
schemaVersion: GROK_RESUME_VERSION,
sessionId: started.sessionId,
},
createdAt: now,
updatedAt: now,
};
const ctx: GrokSessionContext = {
threadId: input.threadId,
acpSessionId: started.sessionId,
session,
scope: sessionScope,
acp,
notificationFiber: undefined,
pendingApprovals,
pendingUserInputs,
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
currentModelId: boundModelId,
stopped: false,
};
const nf = yield* Stream.runDrain(
Stream.mapEffect(acp.getEvents(), (event) =>
Effect.gen(function* () {
switch (event._tag) {
case "AssistantItemStarted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.started",
}),
);
return;
case "AssistantItemCompleted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.completed",
}),
);
return;
case "PlanUpdated":
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* emitPlanUpdate(ctx, event.payload, event.rawPayload, "session/update");
return;
case "ToolCallUpdated":
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* offerRuntimeEvent(
makeAcpToolCallEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
toolCall: event.toolCall,
rawPayload: event.rawPayload,
}),
);
return;
case "ContentDelta":
yield* logNative(ctx.threadId, "session/update", event.rawPayload);
yield* offerRuntimeEvent(
makeAcpContentDeltaEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
...(event.itemId ? { itemId: event.itemId } : {}),
text: event.text,
rawPayload: event.rawPayload,
}),
);
return;
}
}),
),
).pipe(
Effect.catch((cause) =>
Effect.logError("Failed to process Grok runtime notification.", { cause }),
),
Effect.forkChild,
);
ctx.notificationFiber = nf;
sessions.set(input.threadId, ctx);
sessionScopeTransferred = true;
yield* offerRuntimeEvent({
type: "session.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { resume: started.initializeResult },
});
yield* offerRuntimeEvent({
type: "session.state.changed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { state: "ready", reason: "Grok ACP session ready" },
});
yield* offerRuntimeEvent({
type: "thread.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { providerThreadId: started.sessionId },
});
return session;
}).pipe(Effect.scoped),
);
const sendTurn: GrokAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
const prepared = yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
const turnId = TurnId.make(yield* randomUUIDv4);
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId
? input.modelSelection
: undefined;
const requestedTurnModelId = turnModelSelection?.model
? resolveGrokAcpBaseModelId(turnModelSelection.model)
: undefined;
const currentModelId = yield* applyGrokAcpModelSelection({
runtime: ctx.acp,
currentModelId: ctx.currentModelId,
requestedModelId: requestedTurnModelId,
mapError: (cause) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
});
const text = input.input?.trim();
const imagePromptParts = yield* Effect.forEach(input.attachments ?? [], (attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: cause.message,
cause,
}),
),
);
return {
type: "image",
data: Buffer.from(bytes).toString("base64"),
mimeType: attachment.mimeType,
} satisfies EffectAcpSchema.ContentBlock;
}),
);
const promptParts: Array<EffectAcpSchema.ContentBlock> = [
...(text ? [{ type: "text" as const, text }] : []),
...imagePromptParts,
];
if (promptParts.length === 0) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "sendTurn",
issue: "Turn requires non-empty text or attachments.",
});
}
ctx.currentModelId = currentModelId;
const displayModel = currentModelId
? resolveGrokAcpBaseModelId(currentModelId)
: undefined;
ctx.activeTurnId = turnId;
ctx.lastPlanFingerprint = undefined;
ctx.session = {
...ctx.session,
activeTurnId: turnId,
updatedAt: yield* nowIso,
...(displayModel ? { model: displayModel } : {}),
};
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId,
payload: displayModel ? { model: displayModel } : {},
});
return {
acp: ctx.acp,
acpSessionId: ctx.acpSessionId,
displayModel,
promptParts,
turnId,
};
}),
);
const result = yield* prepared.acp
.prompt({
prompt: prepared.promptParts,
})
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
),
);
return yield* withThreadLock(
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
if (ctx.acpSessionId !== prepared.acpSessionId) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/prompt",
detail: "Grok session changed before the turn completed.",
});
}
ctx.turns = [
...ctx.turns,
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
];
ctx.session = {
...ctx.session,
activeTurnId: prepared.turnId,
updatedAt: yield* nowIso,
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
};
yield* offerRuntimeEvent({
type: "turn.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: prepared.turnId,
payload: {
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
stopReason: result.stopReason ?? null,
},
});
return {
threadId: input.threadId,
turnId: prepared.turnId,
resumeCursor: ctx.session.resumeCursor,
};
}),
);
});
const interruptTurn: GrokAdapterShape["interruptTurn"] = (threadId) =>
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
yield* Effect.ignore(
ctx.acp.cancel.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error),
),
),
);
});
const respondToRequest: GrokAdapterShape["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
const pending = ctx.pendingApprovals.get(requestId);
if (!pending) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "session/request_permission",
detail: `Unknown pending approval request: ${requestId}`,
});
}
yield* Deferred.succeed(pending.decision, decision);
});
const respondToUserInput: GrokAdapterShape["respondToUserInput"] = (
threadId,
requestId,
answers,
) =>
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
const pending = ctx.pendingUserInputs.get(requestId);
if (!pending) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "_x.ai/ask_user_question",
detail: `Unknown pending user-input request: ${requestId}`,
});
}
yield* Deferred.succeed(pending.resolution, { _tag: "answered", answers });
});
const readThread: GrokAdapterShape["readThread"] = (threadId) =>
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
return { threadId, turns: ctx.turns };
});
const rollbackThread: GrokAdapterShape["rollbackThread"] = (threadId, numTurns) =>
Effect.gen(function* () {
yield* requireSession(threadId);
if (!Number.isInteger(numTurns) || numTurns < 1) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "rollbackThread",
issue: "numTurns must be an integer >= 1.",
});
}
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "thread/rollback",
detail: "Grok ACP sessions do not support provider-side rollback yet.",
});
});
const stopSession: GrokAdapterShape["stopSession"] = (threadId) =>
withThreadLock(
threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
yield* stopSessionInternal(ctx);
}),
);
const listSessions: GrokAdapterShape["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));
const hasSession: GrokAdapterShape["hasSession"] = (threadId) =>
Effect.sync(() => {
const c = sessions.get(threadId);
return c !== undefined && !c.stopped;
});
const stopAll: GrokAdapterShape["stopAll"] = () =>
Effect.forEach(Array.from(sessions.values()), stopSessionInternal, { discard: true });
yield* Effect.addFinalizer(() =>
Effect.ignore(stopAll()).pipe(
Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
),
);
const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
return {
provider: PROVIDER,
capabilities: { sessionModelSwitch: "in-session" },
startSession,
sendTurn,
interruptTurn,
readThread,
rollbackThread,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
stopAll,
streamEvents,
} satisfies GrokAdapterShape;
});
}
@@ -0,0 +1,108 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { GrokSettings } from "@t3tools/contracts";
import { buildInitialGrokProviderSnapshot, checkGrokProviderStatus } from "./GrokProvider.ts";
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
describe("buildInitialGrokProviderSnapshot", () => {
it.effect("returns a disabled snapshot when settings.enabled is false", () =>
Effect.gen(function* () {
const snapshot = yield* buildInitialGrokProviderSnapshot(
decodeGrokSettings({ enabled: false }),
);
expect(snapshot.enabled).toBe(false);
expect(snapshot.status).toBe("disabled");
expect(snapshot.installed).toBe(false);
expect(snapshot.message).toContain("disabled");
}),
);
it.effect("returns a pending snapshot by default", () =>
Effect.gen(function* () {
const snapshot = yield* buildInitialGrokProviderSnapshot(decodeGrokSettings({}));
expect(snapshot.enabled).toBe(true);
expect(snapshot.installed).toBe(true);
expect(snapshot.status).toBe("warning");
expect(snapshot.version).toBeNull();
expect(snapshot.message).toContain("Checking Grok");
expect(snapshot.requiresNewThreadForModelChange).toBe(true);
}),
);
});
it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
it.effect("reports the binary as missing when the binary path does not resolve", () =>
Effect.gen(function* () {
const snapshot = yield* checkGrokProviderStatus(
decodeGrokSettings({
enabled: true,
binaryPath: "/definitely/not/installed/grok-binary",
}),
);
expect(snapshot.enabled).toBe(true);
expect(snapshot.installed).toBe(false);
expect(snapshot.status).toBe("error");
expect(snapshot.message).toMatch(/not installed|not on PATH|Failed to execute/);
}),
);
it.effect("reports an installed CLI as unhealthy when --version exits non-zero", () =>
Effect.gen(function* () {
const snapshot = yield* Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-version-" });
const grokPath = path.join(dir, "grok");
yield* fs.writeFileString(
grokPath,
["#!/bin/sh", 'printf "%s\\n" "broken grok install" >&2', "exit 2", ""].join("\n"),
);
yield* fs.chmod(grokPath, 0o755);
return yield* checkGrokProviderStatus(
decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
);
}),
);
expect(snapshot.enabled).toBe(true);
expect(snapshot.installed).toBe(true);
expect(snapshot.status).toBe("error");
expect(snapshot.message).toContain("broken grok install");
}),
);
it.effect("reports an error when ACP model discovery is unavailable", () =>
Effect.gen(function* () {
const snapshot = yield* Effect.scoped(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-success-" });
const grokPath = path.join(dir, "grok");
yield* fs.writeFileString(
grokPath,
["#!/bin/sh", 'printf "grok-cli 0.0.99\\n"', "exit 0", ""].join("\n"),
);
yield* fs.chmod(grokPath, 0o755);
return yield* checkGrokProviderStatus(
decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
);
}),
);
expect(snapshot.status).toBe("error");
expect(snapshot.installed).toBe(true);
expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-build"]);
expect(snapshot.message).toContain("ACP startup failed");
}),
);
});
@@ -0,0 +1,324 @@
import {
type GrokSettings,
type ModelCapabilities,
ProviderDriverKind,
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import { HttpClient } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { createModelCapabilities } from "@t3tools/shared/model";
import {
buildServerProvider,
detailFromResult,
isCommandMissingCause,
parseGenericCliVersion,
providerModelsFromSettings,
spawnAndCollect,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import {
enrichProviderSnapshotWithVersionAdvisory,
type ProviderMaintenanceCapabilities,
} from "../providerMaintenance.ts";
import { makeGrokAcpRuntime, resolveGrokAcpBaseModelId } from "../acp/GrokAcpSupport.ts";
const GROK_PRESENTATION = {
displayName: "Grok",
badgeLabel: "Early Access",
showInteractionModeToggle: false,
requiresNewThreadForModelChange: true,
} as const;
const PROVIDER = ProviderDriverKind.make("grok");
const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
optionDescriptors: [],
});
const VERSION_PROBE_TIMEOUT_MS = 4_000;
const GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
const GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "grok-build",
name: "Grok Build",
isCustom: false,
capabilities: EMPTY_CAPABILITIES,
},
];
export function buildInitialGrokProviderSnapshot(
grokSettings: GrokSettings,
): Effect.Effect<ServerProviderDraft> {
return Effect.gen(function* () {
const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
const models = grokModelsFromSettings(grokSettings.customModels);
if (!grokSettings.enabled) {
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Grok is disabled in T3 Code settings.",
},
});
}
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: true,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Checking Grok CLI availability...",
},
});
});
}
function grokModelsFromSettings(
customModels: ReadonlyArray<string> | undefined,
builtInModels: ReadonlyArray<ServerProviderModel> = GROK_BUILT_IN_MODELS,
): ReadonlyArray<ServerProviderModel> {
return providerModelsFromSettings(
builtInModels,
PROVIDER,
customModels ?? [],
EMPTY_CAPABILITIES,
);
}
function buildGrokDiscoveredModelsFromSessionModelState(
modelState: EffectAcpSchema.SessionModelState | null | undefined,
): ReadonlyArray<ServerProviderModel> {
if (!modelState || modelState.availableModels.length === 0) {
return [];
}
const seen = new Set<string>();
return modelState.availableModels
.map((model): ServerProviderModel | undefined => {
const slug = resolveGrokAcpBaseModelId(model.modelId);
if (!slug || seen.has(slug)) {
return undefined;
}
seen.add(slug);
return {
slug,
name: model.name.trim() || slug,
isCustom: false,
capabilities: EMPTY_CAPABILITIES,
};
})
.filter((model): model is ServerProviderModel => model !== undefined);
}
const discoverGrokModelsViaAcp = (
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
) =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const acp = yield* makeGrokAcpRuntime({
grokSettings,
environment,
childProcessSpawner,
cwd: process.cwd(),
clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
});
const started = yield* acp.start();
return buildGrokDiscoveredModelsFromSessionModelState(started.sessionSetupResult.models);
}).pipe(Effect.scoped);
const runGrokVersionCommand = (
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
) => {
const command = grokSettings.binaryPath || "grok";
return spawnAndCollect(
command,
ChildProcess.make(command, ["--version"], {
env: environment,
shell: process.platform === "win32",
}),
);
};
export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const fallbackModels = grokModelsFromSettings(grokSettings.customModels);
if (!grokSettings.enabled) {
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: false,
checkedAt,
models: fallbackModels,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Grok is disabled in T3 Code settings.",
},
});
}
const versionResult = yield* runGrokVersionCommand(grokSettings, environment).pipe(
Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionResult)) {
const error = versionResult.failure;
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Grok CLI (`grok`) is not installed or not on PATH."
: `Failed to execute Grok CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionResult.success)) {
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Grok CLI is installed but timed out while running `grok --version`.",
},
});
}
const versionOutput = versionResult.success.value;
const version = parseGenericCliVersion(`${versionOutput.stdout}\n${versionOutput.stderr}`);
if (versionOutput.code !== 0) {
const detail = detailFromResult(versionOutput);
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: detail
? `Grok CLI is installed but failed to run. ${detail}`
: "Grok CLI is installed but failed to run.",
},
});
}
const discoveryExit = yield* discoverGrokModelsViaAcp(grokSettings, environment).pipe(
Effect.timeoutOption(GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
Effect.exit,
);
if (Exit.isFailure(discoveryExit)) {
const detail = Cause.pretty(discoveryExit.cause);
yield* Effect.logWarning("Grok ACP model discovery failed", { cause: detail });
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: `Grok CLI is installed but ACP startup failed. ${detail}`,
},
});
}
if (Option.isNone(discoveryExit.value)) {
yield* Effect.logWarning(
`Grok ACP model discovery timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,
);
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models: fallbackModels,
probe: {
installed: true,
version,
status: "error",
auth: { status: "unknown" },
message: `Grok CLI is installed but ACP startup timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,
},
});
}
const discoveredModels = discoveryExit.value.value;
const models =
discoveredModels.length > 0
? grokModelsFromSettings(grokSettings.customModels, discoveredModels)
: fallbackModels;
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version,
status: "ready",
auth: { status: "unknown" },
},
});
});
export const enrichGrokSnapshot = (input: {
readonly snapshot: ServerProvider;
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
readonly httpClient: HttpClient.HttpClient;
}): Effect.Effect<void> => {
const { snapshot, publishSnapshot } = input;
return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities).pipe(
Effect.provideService(HttpClient.HttpClient, input.httpClient),
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
Effect.catchCause((cause) =>
Effect.logWarning("Grok version advisory enrichment failed", {
cause: Cause.pretty(cause),
}),
),
Effect.asVoid,
);
};
@@ -10,7 +10,7 @@
*
* 2. **Many drivers, one registry** — the "all drivers slice" describe
* block below configures one instance of every shipped driver
* (`codex`, `claudeAgent`, `cursor`, `opencode`) in a single
* (`codex`, `claudeAgent`, `cursor`, `grok`, `opencode`) in a single
* `ProviderInstanceConfigMap` and asserts the registry boots them all
* without cross-contamination. This proves the driver SPI is uniform
* across every provider — any driver plugs into the registry through
@@ -18,7 +18,7 @@
*
* Every instance in these tests is configured with `enabled: false` so the
* provider-status checks short-circuit to pending/disabled snapshots
* without trying to spawn real `codex` / `claude` / `agent` / `opencode`
* without trying to spawn real `codex` / `claude` / `agent` / `grok` / `opencode`
* binaries. That keeps the assertions focused on registry routing
* behaviour rather than the runtime details of each provider.
*/
@@ -28,6 +28,7 @@ import {
type ClaudeSettings,
type CodexSettings,
type CursorSettings,
type GrokSettings,
type OpenCodeSettings,
ProviderDriverKind,
type ProviderInstanceConfigMap,
@@ -41,6 +42,7 @@ import { ServerConfig } from "../../config.ts";
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
import { CodexDriver } from "../Drivers/CodexDriver.ts";
import { CursorDriver } from "../Drivers/CursorDriver.ts";
import { GrokDriver } from "../Drivers/GrokDriver.ts";
import { OpenCodeDriver } from "../Drivers/OpenCodeDriver.ts";
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts";
@@ -79,6 +81,13 @@ const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings =>
...overrides,
});
const makeGrokConfig = (overrides: Partial<GrokSettings>): GrokSettings => ({
enabled: false,
binaryPath: "grok",
customModels: [],
...overrides,
});
const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
enabled: false,
binaryPath: "opencode",
@@ -218,7 +227,7 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
});
describe("ProviderInstanceRegistryLive — all drivers slice", () => {
// All four drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
// All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
// Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
// at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
// `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
@@ -244,11 +253,13 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
const codexId = ProviderInstanceId.make("codex_default");
const claudeId = ProviderInstanceId.make("claude_default");
const cursorId = ProviderInstanceId.make("cursor_default");
const grokId = ProviderInstanceId.make("grok_default");
const openCodeId = ProviderInstanceId.make("opencode_default");
const codexDriverKind = ProviderDriverKind.make("codex");
const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
const cursorDriverKind = ProviderDriverKind.make("cursor");
const grokDriverKind = ProviderDriverKind.make("grok");
const openCodeDriverKind = ProviderDriverKind.make("opencode");
const configMap: ProviderInstanceConfigMap = {
@@ -273,6 +284,12 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
enabled: false,
config: makeCursorConfig({}),
},
[grokId]: {
driver: grokDriverKind,
displayName: "Grok",
enabled: false,
config: makeGrokConfig({}),
},
[openCodeId]: {
driver: openCodeDriverKind,
displayName: "OpenCode",
@@ -282,7 +299,7 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
};
const { registry } = yield* makeProviderInstanceRegistry({
drivers: [CodexDriver, ClaudeDriver, CursorDriver, OpenCodeDriver],
drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
configMap,
});
@@ -292,9 +309,9 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
expect(unavailable).toEqual([]);
const instances = yield* registry.listInstances;
expect(instances).toHaveLength(4);
expect(instances).toHaveLength(5);
expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
[codexId, claudeId, cursorId, openCodeId].toSorted(),
[codexId, claudeId, cursorId, grokId, openCodeId].toSorted(),
);
// Instance lookup by id resolves each instance to its own bundle —
@@ -303,14 +320,17 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
const codex = yield* registry.getInstance(codexId);
const claude = yield* registry.getInstance(claudeId);
const cursor = yield* registry.getInstance(cursorId);
const grok = yield* registry.getInstance(grokId);
const openCode = yield* registry.getInstance(openCodeId);
expect(codex?.driverKind).toBe(codexDriverKind);
expect(claude?.driverKind).toBe(claudeDriverKind);
expect(cursor?.driverKind).toBe(cursorDriverKind);
expect(grok?.driverKind).toBe(grokDriverKind);
expect(openCode?.driverKind).toBe(openCodeDriverKind);
expect(codex?.displayName).toBe("Codex");
expect(claude?.displayName).toBe("Claude");
expect(cursor?.displayName).toBe("Cursor");
expect(grok?.displayName).toBe("Grok");
expect(openCode?.displayName).toBe("OpenCode");
// Every instance owns its own set of closures — no sharing across
@@ -318,16 +338,29 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
// distinct references even when two instances happen to share a
// trait (e.g. Cursor + others all use a stub-or-real
// `textGeneration`; they must still be different object values).
const adapters = [codex!.adapter, claude!.adapter, cursor!.adapter, openCode!.adapter];
const adapters = [
codex!.adapter,
claude!.adapter,
cursor!.adapter,
grok!.adapter,
openCode!.adapter,
];
expect(new Set(adapters).size).toBe(adapters.length);
const textGenerations = [
codex!.textGeneration,
claude!.textGeneration,
cursor!.textGeneration,
grok!.textGeneration,
openCode!.textGeneration,
];
expect(new Set(textGenerations).size).toBe(textGenerations.length);
const snapshots = [codex!.snapshot, claude!.snapshot, cursor!.snapshot, openCode!.snapshot];
const snapshots = [
codex!.snapshot,
claude!.snapshot,
cursor!.snapshot,
grok!.snapshot,
openCode!.snapshot,
];
expect(new Set(snapshots).size).toBe(snapshots.length);
// Snapshots identify themselves by `instanceId` + `driver` so
@@ -356,6 +389,12 @@ describe("ProviderInstanceRegistryLive — all drivers slice", () => {
`${cursorDriverKind}:instance:${cursorId}`,
);
const grokSnapshot = yield* grok!.snapshot.getSnapshot;
expect(grokSnapshot.instanceId).toBe(grokId);
expect(grokSnapshot.driver).toBe(grokDriverKind);
expect(grokSnapshot.enabled).toBe(false);
expect(grokSnapshot.continuation?.groupKey).toBe(`${grokDriverKind}:instance:${grokId}`);
const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
expect(openCodeSnapshot.instanceId).toBe(openCodeId);
expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
@@ -992,6 +992,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
codex: { enabled: false },
claudeAgent: { enabled: false },
cursor: { enabled: false },
grok: { enabled: false },
opencode: { enabled: false },
},
// `providerInstances` keys are branded `ProviderInstanceId`;
@@ -1086,6 +1087,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
codex: { enabled: true, binaryPath: firstMissing },
claudeAgent: { enabled: false },
cursor: { enabled: false },
grok: { enabled: false },
opencode: { enabled: false },
},
}),
@@ -1186,6 +1188,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
codex: { enabled: false },
claudeAgent: { enabled: false },
cursor: { enabled: false },
grok: { enabled: false },
opencode: { enabled: false },
},
providerInstances: {
@@ -1245,6 +1248,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
cursor: {
enabled: false,
},
grok: {
enabled: false,
},
},
}),
),
@@ -1305,6 +1311,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
"claudeAgent",
"codex",
"cursor",
"grok",
"opencode",
]);
assert.strictEqual(cursorProvider?.enabled, false);
@@ -1360,6 +1367,62 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
),
);
it.effect("includes Claude Fable 5 on supported Claude Code versions", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(
defaultClaudeSettings,
claudeCapabilities(),
);
const fable5 = status.models.find((model) => model.slug === "claude-fable-5");
assert.strictEqual(fable5?.name, "Claude Fable 5");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.169\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("hides Claude Fable 5 on older Claude Code versions", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus(
defaultClaudeSettings,
claudeCapabilities(),
);
assert.strictEqual(
status.models.some((model) => model.slug === "claude-fable-5"),
false,
);
assert.strictEqual(
status.message,
"Claude Code v2.1.168 is too old for Claude Fable 5. Upgrade to v2.1.169 or newer to access it.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "2.1.168\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect(
"includes Claude Opus 4.7 with xhigh as the default effort on supported versions",
() =>
@@ -0,0 +1,16 @@
/**
* GrokAdapter — shape type for the Grok provider adapter.
*
* The driver model ({@link ../Drivers/GrokDriver}) bundles one adapter per
* instance as a captured closure, so this module only retains the shape
* interface as a naming anchor for the driver bundle.
*
* @module GrokAdapter
*/
import type { ProviderAdapterError } from "../Errors.ts";
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
/**
* GrokAdapterShape — per-instance Grok adapter contract.
*/
export interface GrokAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {}
@@ -105,6 +105,9 @@ export interface AcpSessionRuntimeShape {
value: string | boolean,
) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly setSessionModel: (
modelId: string,
) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;
readonly request: (
method: string,
payload: unknown,
@@ -546,6 +549,20 @@ const makeAcpSessionRuntime = (
Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
Effect.asVoid,
),
setSessionModel: (modelId) =>
getStartedState.pipe(
Effect.flatMap((started) => {
const requestPayload = {
sessionId: started.sessionId,
modelId,
} satisfies EffectAcpSchema.SetSessionModelRequest;
return runLoggedRequest(
"session/set_model",
requestPayload,
acp.agent.setSessionModel(requestPayload),
);
}),
),
request: (method, payload) =>
runLoggedRequest(method, payload, acp.raw.request(method, payload)),
notify: acp.raw.notify,
@@ -0,0 +1,69 @@
/**
* Optional integration check against a real `grok agent stdio` install.
* Enable with: T3_GROK_ACP_PROBE=1 bun run test GrokAcpCliProbe
*
* The probe assumes either `XAI_API_KEY` is set in the environment or
* the user has previously run `grok login`. Without credentials the
* agent's `authenticate` request will fail and the test will surface
* the error.
*/
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { describe, expect } from "vite-plus/test";
import { makeGrokAcpRuntime } from "./GrokAcpSupport.ts";
const makeProbeRuntime = Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return yield* makeGrokAcpRuntime({
grokSettings: { binaryPath: "grok" },
environment: process.env,
childProcessSpawner,
cwd: process.cwd(),
clientInfo: { name: "t3-grok-probe", version: "0.0.0" },
});
});
describe.runIf(process.env.T3_GROK_ACP_PROBE === "1")("Grok ACP CLI probe", () => {
it.effect("initialize and authenticate against real grok agent stdio", () =>
Effect.gen(function* () {
const runtime = yield* makeProbeRuntime;
const started = yield* runtime.start();
expect(started.initializeResult).toBeDefined();
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("session/new advertises typed SessionModelState with at least one model", () =>
Effect.gen(function* () {
const runtime = yield* makeProbeRuntime;
const started = yield* runtime.start();
const result = started.sessionSetupResult;
expect(typeof started.sessionId).toBe("string");
// Modern grok-shell advertises models through the typed
// `SessionModelState` field, not via a `configOptions` entry.
// If this assertion fails the upstream surface has regressed.
const models = result.models;
expect(models).toBeDefined();
expect(typeof models?.currentModelId).toBe("string");
expect(models?.availableModels.length ?? 0).toBeGreaterThan(0);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("session/set_model accepts a no-op switch to the current model", () =>
Effect.gen(function* () {
const runtime = yield* makeProbeRuntime;
const started = yield* runtime.start();
const currentModelId = started.sessionSetupResult.models?.currentModelId?.trim();
expect(currentModelId).toBeDefined();
if (!currentModelId) return;
// No-op switch — selecting the model the session already runs on must
// succeed against every Grok build that implements `session/set_model`.
yield* runtime.setSessionModel(currentModelId);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
@@ -0,0 +1,109 @@
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as EffectAcpErrors from "effect-acp/errors";
import {
applyGrokAcpModelSelection,
buildGrokAcpSpawnInput,
resolveGrokAcpBaseModelId,
} from "./GrokAcpSupport.ts";
describe("resolveGrokAcpBaseModelId", () => {
it("normalizes empty and custom Grok model ids", () => {
expect(resolveGrokAcpBaseModelId(undefined)).toBe("grok-build");
expect(resolveGrokAcpBaseModelId(" ")).toBe("grok-build");
expect(resolveGrokAcpBaseModelId(" grok-test-custom-model ")).toBe("grok-test-custom-model");
});
});
describe("buildGrokAcpSpawnInput", () => {
it("passes the T3 Code referrer through Grok OAuth env", () => {
const spawn = buildGrokAcpSpawnInput({ binaryPath: "/usr/local/bin/grok" }, "/tmp/project", {
XAI_API_KEY: "secret",
GROK_OAUTH2_REFERRER: "other-client",
});
expect(spawn).toEqual({
command: "/usr/local/bin/grok",
args: ["agent", "stdio"],
cwd: "/tmp/project",
env: {
XAI_API_KEY: "secret",
GROK_OAUTH2_REFERRER: "t3code",
},
});
});
});
describe("applyGrokAcpModelSelection", () => {
const makeRecordingRuntime = (failure?: EffectAcpErrors.AcpError) => {
const modelCalls: Array<string> = [];
const runtime = {
setSessionModel: (modelId: string) =>
Effect.gen(function* () {
modelCalls.push(modelId);
if (failure) return yield* failure;
return {};
}),
};
return { runtime, modelCalls };
};
it.effect("calls session/set_model when the requested model differs from current", () =>
Effect.gen(function* () {
const { runtime, modelCalls } = makeRecordingRuntime();
const result = yield* applyGrokAcpModelSelection({
runtime,
currentModelId: "grok-build",
requestedModelId: "grok-mock-alt",
mapError: (cause) => cause.message,
});
expect(modelCalls).toEqual(["grok-mock-alt"]);
expect(result).toBe("grok-mock-alt");
}),
);
it.effect("skips set_model when requested matches current", () =>
Effect.gen(function* () {
const { runtime, modelCalls } = makeRecordingRuntime();
const result = yield* applyGrokAcpModelSelection({
runtime,
currentModelId: "grok-build",
requestedModelId: "grok-build",
mapError: (cause) => cause.message,
});
expect(modelCalls).toEqual([]);
expect(result).toBe("grok-build");
}),
);
it.effect("skips set_model when no model is requested", () =>
Effect.gen(function* () {
const { runtime, modelCalls } = makeRecordingRuntime();
const result = yield* applyGrokAcpModelSelection({
runtime,
currentModelId: "grok-build",
requestedModelId: undefined,
mapError: (cause) => cause.message,
});
expect(modelCalls).toEqual([]);
expect(result).toBe("grok-build");
}),
);
it.effect("propagates session/set_model failures via mapError", () =>
Effect.gen(function* () {
const failure = EffectAcpErrors.AcpRequestError.invalidParams("session id not known");
const { runtime } = makeRecordingRuntime(failure);
const error = yield* Effect.flip(
applyGrokAcpModelSelection({
runtime,
currentModelId: "grok-build",
requestedModelId: "grok-mock-alt",
mapError: (cause) => cause.message,
}),
);
expect(error).toBe(failure.message);
}),
);
});
@@ -0,0 +1,104 @@
import { type GrokSettings, ProviderDriverKind } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpSchema from "effect-acp/schema";
import { normalizeModelSlug } from "@t3tools/shared/model";
import {
AcpSessionRuntime,
type AcpSessionRuntimeOptions,
type AcpSessionRuntimeShape,
type AcpSpawnInput,
} from "./AcpSessionRuntime.ts";
const GROK_API_KEY_ENV = "XAI_API_KEY";
const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER";
const T3_CODE_OAUTH_REFERRER = "t3code";
const GROK_AUTH_METHOD_API_KEY = "xai.api_key";
const GROK_AUTH_METHOD_CACHED_TOKEN = "cached_token";
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
type GrokAcpRuntimeGrokSettings = Pick<GrokSettings, "binaryPath">;
interface GrokAcpRuntimeInput extends Omit<
AcpSessionRuntimeOptions,
"authMethodId" | "clientCapabilities" | "spawn"
> {
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
readonly grokSettings: GrokAcpRuntimeGrokSettings | null | undefined;
readonly environment?: NodeJS.ProcessEnv;
}
export function buildGrokAcpSpawnInput(
grokSettings: GrokAcpRuntimeGrokSettings | null | undefined,
cwd: string,
environment?: NodeJS.ProcessEnv,
): AcpSpawnInput {
return {
command: grokSettings?.binaryPath || "grok",
args: ["agent", "stdio"],
cwd,
env: {
...environment,
[GROK_OAUTH2_REFERRER_ENV]: T3_CODE_OAUTH_REFERRER,
},
};
}
function resolveGrokAuthMethodId(environment: NodeJS.ProcessEnv | undefined): string {
return environment?.[GROK_API_KEY_ENV]?.trim()
? GROK_AUTH_METHOD_API_KEY
: GROK_AUTH_METHOD_CACHED_TOKEN;
}
export const makeGrokAcpRuntime = (
input: GrokAcpRuntimeInput,
): Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError, Scope.Scope> =>
Effect.gen(function* () {
const acpContext = yield* Layer.build(
AcpSessionRuntime.layer({
...input,
spawn: buildGrokAcpSpawnInput(input.grokSettings, input.cwd, input.environment),
authMethodId: resolveGrokAuthMethodId(input.environment),
}).pipe(
Layer.provide(
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
),
),
);
return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(acpContext));
});
export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
const trimmed = model?.trim();
const base = trimmed && trimmed.length > 0 ? trimmed : "grok-build";
return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? "grok-build";
}
export function currentGrokModelIdFromSessionSetup(
sessionSetupResult:
| EffectAcpSchema.LoadSessionResponse
| EffectAcpSchema.NewSessionResponse
| EffectAcpSchema.ResumeSessionResponse,
): string | undefined {
return sessionSetupResult.models?.currentModelId?.trim() || undefined;
}
export function applyGrokAcpModelSelection<E>(input: {
readonly runtime: Pick<AcpSessionRuntimeShape, "setSessionModel">;
readonly currentModelId: string | undefined;
readonly requestedModelId: string | undefined;
readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
}): Effect.Effect<string | undefined, E> {
const shouldSwitchModel =
input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;
if (!shouldSwitchModel) {
return Effect.succeed(input.currentModelId);
}
return input.runtime
.setSessionModel(input.requestedModelId)
.pipe(Effect.mapError(input.mapError), Effect.as(input.requestedModelId));
}
@@ -0,0 +1,250 @@
import { describe, expect, it } from "vite-plus/test";
import * as Schema from "effect/Schema";
import {
extractXAiAskUserQuestions,
makeXAiAskUserQuestionCancelledResponse,
makeXAiAskUserQuestionResponse,
XAiAskUserQuestionRequest,
} from "./XAiAcpExtension.ts";
const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);
describe("XAiAcpExtension", () => {
it("extracts questions from the real xAI ask_user_question payload shape", () => {
const questions = extractXAiAskUserQuestions({
sessionId: "session-1",
toolCallId: "tool-call-1",
mode: "default",
questions: [
{
id: "scope",
question: "Which scope should Grok use?",
options: [
{ label: "Workspace", description: "Use the current workspace" },
{ label: "Session", description: "Only use this session" },
],
},
],
});
expect(questions).toEqual([
{
id: "scope",
header: "Question",
question: "Which scope should Grok use?",
multiSelect: false,
options: [
{ label: "Workspace", description: "Use the current workspace" },
{ label: "Session", description: "Only use this session" },
],
},
]);
});
it("extracts questions from wrapped _x.ai extension payloads", () => {
const payload = {
method: "_x.ai/ask_user_question",
params: {
sessionId: "session-1",
toolCallId: "tool-call-1",
mode: "plan",
questions: [
{
question: "Which changes should be included?",
multiSelect: true,
options: [{ label: "Tests" }, { label: "Docs" }],
},
],
},
};
const decoded = decodeXAiAskUserQuestionRequest(payload);
const questions = extractXAiAskUserQuestions(decoded);
expect(questions).toEqual([
{
id: "Which changes should be included?",
header: "Question",
question: "Which changes should be included?",
multiSelect: true,
options: [
{ label: "Tests", description: "Tests" },
{ label: "Docs", description: "Docs" },
],
},
]);
});
it("treats nullable multiSelect from Grok as single-select", () => {
const questions = extractXAiAskUserQuestions({
sessionId: "session-1",
toolCallId: "tool-call-1",
mode: "default",
questions: [
{
question: "Which label should Grok use?",
multiSelect: null,
options: [
{ label: "Alpha", description: "Use the Alpha label" },
{ label: "Beta", description: "Use the Beta label" },
{ label: "Other", description: "Use the Other label" },
],
},
],
});
expect(questions).toEqual([
{
id: "Which label should Grok use?",
header: "Question",
question: "Which label should Grok use?",
multiSelect: false,
options: [
{ label: "Alpha", description: "Use the Alpha label" },
{ label: "Beta", description: "Use the Beta label" },
{ label: "Other", description: "Use the Other label" },
],
},
]);
});
it("maps UI question ids back to xAI question text in accepted responses", () => {
const response = makeXAiAskUserQuestionResponse(
{
sessionId: "session-1",
toolCallId: "tool-call-1",
mode: "default",
questions: [
{
id: "scope",
question: "Which scope should Grok use?",
options: [
{ label: "workspace", description: "Use the current workspace" },
{ label: "session", description: "Only use this session" },
],
},
],
},
{ scope: "workspace" },
);
expect(response).toEqual({
outcome: "accepted",
answers: {
"Which scope should Grok use?": ["workspace"],
},
});
});
it("orders accepted answers by the original xAI question order", () => {
const response = makeXAiAskUserQuestionResponse(
{
sessionId: "session-1",
toolCallId: "tool-call-1",
mode: "default",
questions: [
{
id: "first",
question: "First question?",
options: [{ label: "A", description: "A" }],
},
{
id: "second",
question: "Second question?",
options: [{ label: "B", description: "B" }],
},
],
},
{
second: "B",
first: "A",
},
);
expect(Object.keys(response.answers)).toEqual(["First question?", "Second question?"]);
expect(response).toMatchObject({
outcome: "accepted",
answers: {
"First question?": ["A"],
"Second question?": ["B"],
},
});
});
it("encodes typed custom answers as xAI Other annotations", () => {
const response = makeXAiAskUserQuestionResponse(
{
method: "x.ai/ask_user_question",
params: {
sessionId: "session-1",
toolCallId: "tool-call-1",
mode: "default",
questions: [
{
question: "Which ice cream flavor?",
options: [
{ label: "vanilla", description: "Vanilla flavor" },
{ label: "chocolate", description: "Chocolate flavor" },
],
},
],
},
},
{ "Which ice cream flavor?": "pistachio" },
);
expect(response).toEqual({
outcome: "accepted",
answers: {
"Which ice cream flavor?": ["Other"],
},
annotations: {
"Which ice cream flavor?": {
notes: "pistachio",
},
},
});
});
it("encodes interrupted dialogs as xAI cancelled responses", () => {
expect(makeXAiAskUserQuestionCancelledResponse()).toEqual({
outcome: "cancelled",
});
});
it("does not echo preview annotations for multi-select answers", () => {
const response = makeXAiAskUserQuestionResponse(
{
sessionId: "session-1",
toolCallId: "tool-call-1",
mode: "default",
questions: [
{
question: "Which files should Grok touch?",
multiSelect: true,
options: [
{
label: "Tests",
description: "Update tests",
preview: "test preview",
},
{
label: "Docs",
description: "Update docs",
preview: "docs preview",
},
],
},
],
},
{ "Which files should Grok touch?": ["Tests", "Docs"] },
);
expect(response).toEqual({
outcome: "accepted",
answers: {
"Which files should Grok touch?": ["Tests", "Docs"],
},
});
});
});
@@ -0,0 +1,173 @@
import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
const XAiAskUserQuestionOption = Schema.Struct({
label: Schema.String,
description: Schema.optional(Schema.String),
preview: Schema.optional(Schema.String),
id: Schema.optional(Schema.String),
});
const XAiAskUserQuestion = Schema.Struct({
id: Schema.optional(Schema.String),
question: Schema.String,
options: Schema.Array(XAiAskUserQuestionOption),
multiSelect: Schema.optional(Schema.NullOr(Schema.Boolean)),
});
const XAiAskUserQuestionParams = Schema.Struct({
sessionId: Schema.String,
toolCallId: Schema.String,
questions: Schema.Array(XAiAskUserQuestion),
mode: Schema.Literals(["default", "plan"]),
});
const XAiWrappedAskUserQuestionParams = Schema.Struct({
method: Schema.Literals(["x.ai/ask_user_question", "_x.ai/ask_user_question"]),
params: XAiAskUserQuestionParams,
});
export const XAiAskUserQuestionRequest = Schema.Union([
XAiAskUserQuestionParams,
XAiWrappedAskUserQuestionParams,
]);
type XAiAskUserQuestionRequestParams = typeof XAiAskUserQuestionParams.Type;
type XAiAskUserQuestionRequest = typeof XAiAskUserQuestionRequest.Type;
function trimmed(value: string | undefined): string | undefined {
const text = value?.trim();
return text && text.length > 0 ? text : undefined;
}
function unwrapAskUserQuestionParams(
params: XAiAskUserQuestionRequest,
): XAiAskUserQuestionRequestParams {
return "params" in params ? params.params : params;
}
export function extractXAiAskUserQuestions(
params: XAiAskUserQuestionRequest,
): ReadonlyArray<UserInputQuestion> {
return unwrapAskUserQuestionParams(params).questions.map((question) => ({
id: question.id ?? question.question,
header: "Question",
question: question.question,
multiSelect: question.multiSelect === true,
options:
question.options.length > 0
? question.options.map((option) => ({
label: option.label,
description: option.description ?? option.label,
}))
: [{ label: "OK", description: "Continue" }],
}));
}
interface XAiAskUserQuestionAnnotation {
readonly preview?: string;
readonly notes?: string;
}
interface XAiAskUserQuestionAcceptedResponse {
readonly outcome: "accepted";
readonly answers: Record<string, ReadonlyArray<string>>;
readonly annotations?: Record<string, XAiAskUserQuestionAnnotation>;
}
interface XAiAskUserQuestionCancelledResponse {
readonly outcome: "cancelled";
}
export type XAiAskUserQuestionResponse =
| XAiAskUserQuestionAcceptedResponse
| XAiAskUserQuestionCancelledResponse;
interface NormalizedXAiAnswer {
readonly questionText: string;
readonly selectedLabels: ReadonlyArray<string>;
readonly annotation?: XAiAskUserQuestionAnnotation;
}
function answerValues(answer: unknown): ReadonlyArray<string> {
if (Array.isArray(answer)) {
return answer.flatMap((entry) => {
const text = typeof entry === "string" ? trimmed(entry) : undefined;
return text ? [text] : [];
});
}
const text = typeof answer === "string" ? trimmed(answer) : undefined;
return text ? [text] : [];
}
function normalizeAnswerForXAi(
question: XAiAskUserQuestionRequestParams["questions"][number],
answer: unknown,
): NormalizedXAiAnswer | undefined {
const values = answerValues(answer);
if (values.length === 0) {
return undefined;
}
const optionByLabel = new Map(question.options.map((option) => [option.label, option]));
const resolvedValues = values.map((value) => ({
value,
option: optionByLabel.get(value),
}));
const selectedLabels = resolvedValues.flatMap(({ option }) => (option ? [option.label] : []));
const notes = resolvedValues.flatMap(({ option, value }) => (option ? [] : [value]));
const preview =
question.multiSelect === true
? undefined
: resolvedValues.map(({ option }) => trimmed(option?.preview)).find((value) => value);
const annotation =
preview || notes.length > 0
? {
...(preview ? { preview } : {}),
...(notes.length > 0 ? { notes: notes.join("\n") } : {}),
}
: undefined;
return {
questionText: question.question,
selectedLabels: selectedLabels.length > 0 ? selectedLabels : ["Other"],
...(annotation ? { annotation } : {}),
};
}
function findQuestionAnswer(
answers: ProviderUserInputAnswers,
question: XAiAskUserQuestionRequestParams["questions"][number],
): unknown {
const key = question.id ?? question.question;
return answers[key] ?? answers[question.question];
}
export function makeXAiAskUserQuestionResponse(
params: XAiAskUserQuestionRequest,
answers: ProviderUserInputAnswers,
): XAiAskUserQuestionAcceptedResponse {
const questions = unwrapAskUserQuestionParams(params).questions;
const normalized = questions.flatMap((question) => {
const entry = normalizeAnswerForXAi(question, findQuestionAnswer(answers, question));
return entry ? [entry] : [];
});
const annotations = Object.fromEntries(
normalized.flatMap((entry) =>
entry.annotation ? [[entry.questionText, entry.annotation] as const] : [],
),
);
return {
outcome: "accepted",
answers: Object.fromEntries(
normalized.map((entry) => [entry.questionText, entry.selectedLabels]),
),
...(Object.keys(annotations).length > 0 ? { annotations } : {}),
};
}
export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse {
return { outcome: "cancelled" };
}
@@ -23,6 +23,7 @@
import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts";
import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts";
import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts";
import { GrokDriver, type GrokDriverEnv } from "./Drivers/GrokDriver.ts";
import { OpenCodeDriver, type OpenCodeDriverEnv } from "./Drivers/OpenCodeDriver.ts";
import type { AnyProviderDriver } from "./ProviderDriver.ts";
@@ -35,6 +36,7 @@ export type BuiltInDriversEnv =
| ClaudeDriverEnv
| CodexDriverEnv
| CursorDriverEnv
| GrokDriverEnv
| OpenCodeDriverEnv;
/**
@@ -46,5 +48,6 @@ export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv
CodexDriver,
ClaudeDriver,
CursorDriver,
GrokDriver,
OpenCodeDriver,
];
@@ -45,6 +45,7 @@ export interface ServerProviderPresentation {
readonly displayName: string;
readonly badgeLabel?: string;
readonly showInteractionModeToggle?: boolean;
readonly requiresNewThreadForModelChange?: boolean;
}
export type ServerProviderDraft = Omit<ServerProvider, "instanceId" | "driver">;
@@ -214,6 +215,9 @@ export function buildServerProvider(input: {
...(typeof input.presentation.showInteractionModeToggle === "boolean"
? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }
: {}),
...(typeof input.presentation.requiresNewThreadForModelChange === "boolean"
? { requiresNewThreadForModelChange: input.presentation.requiresNewThreadForModelChange }
: {}),
enabled: input.enabled,
installed: input.probe.installed,
version: input.probe.version,
@@ -0,0 +1,21 @@
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
import type { ServerProvider } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
export const makeProviderRegistryMock = (
providers: ReadonlyArray<ServerProvider> = [],
): ProviderRegistryShape => ({
getProviders: Effect.succeed(providers),
refresh: () => Effect.succeed(providers),
refreshInstance: () => Effect.succeed(providers),
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
Effect.succeed(makeManualOnlyProviderMaintenanceCapabilities({ provider, packageName: null })),
setProviderMaintenanceActionState: () => Effect.succeed(providers),
streamChanges: Stream.empty,
});
export const makeProviderRegistryLayer = (providers: ReadonlyArray<ServerProvider> = []) =>
Layer.succeed(ProviderRegistry, makeProviderRegistryMock(providers));
+3 -3
View File
@@ -303,7 +303,7 @@ const make = Effect.gen(function* () {
}
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
if (!relayConfig) {
yield* Effect.logDebug("agent activity publish skipped; T3 Cloud config missing", {
yield* Effect.logDebug("agent activity publish skipped; T3 Connect config missing", {
threadId,
});
return;
@@ -421,7 +421,7 @@ const make = Effect.gen(function* () {
}
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
if (!relayConfig) {
yield* Effect.logDebug("agent activity snapshot skipped; T3 Cloud config missing");
yield* Effect.logDebug("agent activity snapshot skipped; T3 Connect config missing");
return false;
}
const environmentId = yield* serverEnvironment.getEnvironmentId;
@@ -459,7 +459,7 @@ const make = Effect.gen(function* () {
function* () {
const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));
if (!relayConfig) {
yield* Effect.logInfo("agent activity publishing standby; T3 Cloud config missing");
yield* Effect.logInfo("agent activity publishing standby; T3 Connect config missing");
} else {
yield* Effect.logInfo("agent activity publishing enabled", {
relayUrl: relayConfig.url,
+50 -50
View File
@@ -782,7 +782,7 @@ const buildAppUnderTest = (options?: {
),
Layer.provide(
Layer.mock(CloudCliTokenManager.CloudCliTokenManager)({
get: Effect.die(new Error("Unexpected T3 Cloud CLI authorization request.")),
get: Effect.die(new Error("Unexpected T3 Connect CLI authorization request.")),
getExisting: Effect.succeed(Option.none()),
hasCredential: Effect.succeed(false),
clear: Effect.void,
@@ -1713,7 +1713,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest();
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
const linkProofResponse = yield* fetchEffect(linkProofUrl, {
method: "POST",
headers: {
@@ -1750,7 +1750,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest();
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
const serverPort = Number(new URL(linkProofUrl).port);
const linkProofResponse = yield* fetchEffect(linkProofUrl, {
method: "POST",
@@ -1762,10 +1762,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
challenge: "relay-link-challenge",
relayIssuer: "https://relay.example.test",
endpoint: {
httpBaseUrl: linkProofUrl.replace("/api/cloud/link-proof", ""),
httpBaseUrl: linkProofUrl.replace("/api/connect/link-proof", ""),
wsBaseUrl: linkProofUrl
.replace("http://", "ws://")
.replace("/api/cloud/link-proof", "/ws"),
.replace("/api/connect/link-proof", "/ws"),
providerKind: "manual",
},
origin: {
@@ -1789,9 +1789,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
Effect.gen(function* () {
yield* buildAppUnderTest();
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
const serverPort = Number(new URL(linkProofUrl).port);
const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", {
const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", {
headers: {
cookie: yield* getAuthenticatedSessionCookieHeader(),
"content-type": "application/json",
@@ -1833,9 +1833,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
Effect.gen(function* () {
yield* buildAppUnderTest();
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
const serverPort = Number(new URL(linkProofUrl).port);
const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", {
const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", {
headers: {
cookie: yield* getAuthenticatedSessionCookieHeader(),
"content-type": "application/json",
@@ -1875,9 +1875,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
Effect.gen(function* () {
yield* buildAppUnderTest();
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
const serverPort = Number(new URL(linkProofUrl).port);
const linkProofResponse = yield* HttpClient.post("/api/cloud/link-proof", {
const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", {
headers: {
cookie: yield* getAuthenticatedSessionCookieHeader(),
"content-type": "application/json",
@@ -1918,7 +1918,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest();
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
const serverPort = Number(new URL(linkProofUrl).port);
const linkProofResponse = yield* fetchEffect(linkProofUrl, {
method: "POST",
@@ -1962,7 +1962,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
});
const credential = (yield* credentialResponse.json) as { readonly credential: string };
const pairedCookie = yield* getAuthenticatedSessionCookieHeader(credential.credential);
const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state");
const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state");
const response = yield* fetchEffect(linkStateUrl, {
headers: { cookie: pairedCookie },
});
@@ -2028,7 +2028,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest();
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const preferencesUrl = yield* getHttpServerUrl("/api/cloud/preferences");
const preferencesUrl = yield* getHttpServerUrl("/api/connect/preferences");
const ownerResponse = yield* fetchEffect(preferencesUrl, {
method: "POST",
headers: {
@@ -2072,7 +2072,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest();
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -2107,7 +2107,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const postRelayConfig = (body: {
readonly relayUrl: string;
readonly relayIssuer?: string;
@@ -2184,7 +2184,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const postRelayConfig = (cloudUserId: string, environmentCredential: string) =>
fetchEffect(relayConfigUrl, {
method: "POST",
@@ -2227,8 +2227,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state");
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const initialResponse = yield* fetchEffect(linkStateUrl, {
headers: {
@@ -2284,7 +2284,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
Effect.gen(function* () {
yield* buildAppUnderTest();
const reconcileUrl = yield* getHttpServerUrl("/api/cloud/reconcile");
const reconcileUrl = yield* getHttpServerUrl("/api/connect/reconcile");
const response = yield* fetchEffect(reconcileUrl, {
method: "POST",
});
@@ -2321,9 +2321,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const unlinkUrl = yield* getHttpServerUrl("/api/cloud/unlink");
const linkStateUrl = yield* getHttpServerUrl("/api/cloud/link-state");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const unlinkUrl = yield* getHttpServerUrl("/api/connect/unlink");
const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
@@ -2398,7 +2398,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -2424,7 +2424,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
issuedAt: DateTime.formatIso(now),
expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),
});
const mintUrl = yield* getHttpServerUrl("/api/cloud/mint-credential");
const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential");
const postMint = () =>
fetchEffect(mintUrl, {
method: "POST",
@@ -2448,7 +2448,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("serves the documented T3 Cloud mint credential endpoint", () =>
it.effect("serves the documented T3 Connect mint credential endpoint", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
@@ -2457,7 +2457,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -2484,7 +2484,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
issuedAt: DateTime.formatIso(now),
expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),
});
const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential");
const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");
const response = yield* fetchEffect(mintUrl, {
method: "POST",
headers: {
@@ -2507,7 +2507,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("serves signed T3 Cloud environment health checks", () =>
it.effect("serves signed T3 Connect environment health checks", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
@@ -2516,7 +2516,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -2542,7 +2542,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
issuedAt: DateTime.formatIso(now),
expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),
});
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
const response = yield* fetchEffect(healthUrl, {
method: "POST",
headers: {
@@ -2576,7 +2576,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -2602,7 +2602,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
issuedAt: DateTime.formatIso(now),
expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),
});
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
const postHealth = () =>
fetchEffect(healthUrl, {
method: "POST",
@@ -2637,7 +2637,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -2656,7 +2656,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.equal(relayConfigResponse.status, 200);
const now = yield* DateTime.now;
const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential");
const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");
const postMint = (request: ReturnType<typeof makeCloudMintCredentialRequest>) =>
fetchEffect(mintUrl, {
method: "POST",
@@ -2717,7 +2717,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -2756,7 +2756,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
issuedAt: DateTime.formatIso(now),
expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),
});
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
const healthResponse = yield* fetchEffect(healthUrl, {
method: "POST",
headers: {
@@ -2786,7 +2786,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -2804,7 +2804,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.equal(relayConfigResponse.status, 200);
const now = yield* DateTime.now;
const mintUrl = yield* getHttpServerUrl("/api/cloud/mint-credential");
const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential");
const postMint = (request: ReturnType<typeof makeCloudMintCredentialRequest>) =>
fetchEffect(mintUrl, {
method: "POST",
@@ -2853,7 +2853,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -2871,7 +2871,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.equal(relayConfigResponse.status, 200);
const now = yield* DateTime.now;
const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential");
const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");
const response = yield* fetchEffect(mintUrl, {
method: "POST",
headers: {
@@ -2904,7 +2904,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -2922,7 +2922,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.equal(relayConfigResponse.status, 200);
const now = yield* DateTime.now;
const mintUrl = yield* getHttpServerUrl("/api/t3-cloud/mint-credential");
const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");
const response = yield* fetchEffect(mintUrl, {
method: "POST",
headers: {
@@ -2955,7 +2955,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -2973,7 +2973,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.equal(relayConfigResponse.status, 200);
const now = yield* DateTime.now;
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
const postHealth = (request: ReturnType<typeof makeCloudEnvironmentHealthRequest>) =>
fetchEffect(healthUrl, {
method: "POST",
@@ -3020,7 +3020,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -3038,7 +3038,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.equal(relayConfigResponse.status, 200);
const now = yield* DateTime.now;
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
const response = yield* fetchEffect(healthUrl, {
method: "POST",
headers: {
@@ -3070,7 +3070,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
publicKeyEncoding: { format: "pem", type: "spki" },
});
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const relayConfigUrl = yield* getHttpServerUrl("/api/cloud/relay-config");
const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");
const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {
method: "POST",
headers: {
@@ -3088,7 +3088,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
assert.equal(relayConfigResponse.status, 200);
const now = yield* DateTime.now;
const healthUrl = yield* getHttpServerUrl("/api/t3-cloud/health");
const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");
const response = yield* fetchEffect(healthUrl, {
method: "POST",
headers: {
@@ -3280,7 +3280,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
config: { devUrl: new URL(crossOriginClientOrigin) },
});
const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof");
const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");
const response = yield* fetchEffect(linkProofUrl, {
method: "OPTIONS",
headers: {
+4 -4
View File
@@ -69,7 +69,7 @@ import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts
import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { cloudHttpApiLayer, reconcileDesiredCloudLink } from "./cloud/http.ts";
import { connectHttpApiLayer, reconcileDesiredCloudLink } from "./cloud/http.ts";
import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
import * as CloudCliState from "./cloud/CliState.ts";
@@ -321,7 +321,7 @@ const RuntimeServicesLive = ServerRuntimeStartupLive.pipe(
export const makeRoutesLayer = Layer.mergeAll(
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
Layer.provide(authHttpApiLayer),
Layer.provide(cloudHttpApiLayer),
Layer.provide(connectHttpApiLayer),
Layer.provide(orchestrationHttpApiLayer),
Layer.provide(serverEnvironmentHttpApiLayer),
Layer.provide(environmentAuthenticatedAuthLayer),
@@ -429,9 +429,9 @@ export const makeServerLayer = Layer.unwrap(
Effect.sleep("250 millis").pipe(
Effect.andThen(reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`)),
Effect.retry({ times: 4 }),
Effect.tap(() => Effect.logInfo("T3 Cloud desired link reconciled on startup")),
Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
Effect.catch((cause) =>
Effect.logWarning("Failed to reconcile T3 Cloud desired link on startup", {
Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
cause,
}),
),
+2
View File
@@ -13,6 +13,7 @@
import {
DEFAULT_GIT_TEXT_GENERATION_MODEL,
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_SERVER_SETTINGS,
isProviderDriverKind,
type ModelSelection,
@@ -207,6 +208,7 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
instanceId: ProviderInstanceId.make(fallback),
model:
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
DEFAULT_MODEL_BY_PROVIDER[fallback] ??
DEFAULT_GIT_TEXT_GENERATION_MODEL,
} satisfies ModelSelection,
};
@@ -0,0 +1,234 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as path from "node:path";
import * as os from "node:os";
import { fileURLToPath } from "node:url";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vite-plus/test";
import { GrokSettings, ProviderInstanceId } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { makeGrokTextGeneration } from "./GrokTextGeneration.ts";
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../scripts/acp-mock-agent.ts");
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
const GrokTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-grok-text-generation-test-",
}).pipe(Layer.provideMerge(NodeServices.layer));
function makeAcpGrokWrapper(dir: string, env: Record<string, string>): string {
const binDir = path.join(dir, "bin");
const grokPath = path.join(binDir, "grok");
mkdirSync(binDir, { recursive: true });
writeFileSync(
grokPath,
[
"#!/bin/sh",
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
'if [ "$1" != "agent" ] || [ "$2" != "stdio" ]; then',
' printf "%s\\n" "unexpected args: $*" >&2',
" exit 11",
"fi",
`exec ${JSON.stringify(process.execPath)} ${JSON.stringify(mockAgentPath)}`,
"",
].join("\n"),
"utf8",
);
chmodSync(grokPath, 0o755);
return grokPath;
}
function withFakeAcpGrok<A, E, R>(
env: Record<string, string>,
effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,
) {
return Effect.gen(function* () {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-grok-text-acp-"));
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
rmSync(tempDir, { recursive: true, force: true });
}),
);
const binaryPath = makeAcpGrokWrapper(tempDir, env);
const config = decodeGrokSettings({ binaryPath });
const textGeneration = yield* makeGrokTextGeneration(config);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
}
function readJsonRpcRequests(
filePath: string,
): ReadonlyArray<{ readonly method?: string; readonly params?: Record<string, unknown> }> {
return readFileSync(filePath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
}
it.layer(GrokTextGenerationTestLayer)("GrokTextGeneration", (it) => {
it.effect("uses ACP with disabled tool capabilities and forwards the requested model id", () => {
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-grok-text-log-"));
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
return withFakeAcpGrok(
{
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Add Grok provider",
body: "Wire up the ACP runtime and headless text generation path.",
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/grok",
stagedSummary: "M apps/server/src/provider/Drivers/GrokDriver.ts",
stagedPatch: "diff --git a/.../GrokDriver.ts b/.../GrokDriver.ts",
modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-mock-alt"),
});
expect(generated.subject).toBe("Add Grok provider");
expect(generated.body).toBe("Wire up the ACP runtime and headless text generation path.");
const requests = readJsonRpcRequests(requestLogPath);
expect(
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
).toMatchObject({
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
});
expect(
requests.some(
(request) =>
request.method === "session/set_model" &&
request.params?.modelId === "grok-mock-alt",
),
).toBe(true);
}),
);
});
it.effect("extracts the JSON object when Grok wraps it in conversational text", () =>
withFakeAcpGrok(
{
T3_ACP_PROMPT_RESPONSE_TEXT:
"Sure! Here's a thread title:\n\n" +
JSON.stringify({ title: "Investigate failing CI" }) +
"\n\nLet me know if you need anything else.",
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "the lint job is red",
modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-mock-alt"),
});
expect(generated.title).toBe("Investigate failing CI");
}),
),
);
it.effect("surfaces ACP request failures as text generation errors", () =>
withFakeAcpGrok(
{
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ branch: "unreachable" }),
},
(textGeneration) =>
Effect.gen(function* () {
const error = yield* Effect.flip(
textGeneration.generateBranchName({
cwd: process.cwd(),
message: "wire up grok",
modelSelection: createModelSelection(
ProviderInstanceId.make("grok"),
"missing-grok-model",
),
}),
);
expect(error._tag).toBe("TextGenerationError");
expect(error.detail).toContain("Grok ACP base model");
}),
),
);
it.effect("fails with TextGenerationError when output is empty", () =>
withFakeAcpGrok(
{
T3_ACP_PROMPT_RESPONSE_TEXT: " \n ",
},
(textGeneration) =>
Effect.gen(function* () {
const error = yield* Effect.flip(
textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "anything",
modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
}),
);
expect(error._tag).toBe("TextGenerationError");
expect(error.detail).toMatch(/empty/i);
}),
),
);
it.effect("decodes a structured PR title + body", () =>
withFakeAcpGrok(
{
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
title: "feat(grok): wire up session/set_model",
body: "## Summary\n- Replace `-m` spawn flag with the typed ACP `session/set_model`.\n- Translate `MODEL_SWITCH_INCOMPATIBLE_AGENT` into a validation error.",
}),
},
(textGeneration) =>
Effect.gen(function* () {
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feat/grok-provider",
commitSummary: "feat: add grok provider",
diffSummary: "M apps/server/src/provider/Drivers/GrokDriver.ts",
diffPatch: "diff --git a/.../GrokDriver.ts b/.../GrokDriver.ts",
modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
});
expect(generated.title).toBe("feat(grok): wire up session/set_model");
expect(generated.body).toContain("Translate `MODEL_SWITCH_INCOMPATIBLE_AGENT`");
}),
),
);
it.effect("fails with TextGenerationError when output is unparseable JSON", () =>
withFakeAcpGrok(
{
T3_ACP_PROMPT_RESPONSE_TEXT: "totally not json output from a confused model",
},
(textGeneration) =>
Effect.gen(function* () {
const error = yield* Effect.flip(
textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "anything",
modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"),
}),
);
expect(error._tag).toBe("TextGenerationError");
expect(error.detail).toMatch(/invalid structured output/i);
}),
),
);
});
@@ -0,0 +1,272 @@
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import { ChildProcessSpawner } from "effect/unstable/process";
import type * as EffectAcpErrors from "effect-acp/errors";
import { type GrokSettings, type ModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { extractJsonObject } from "@t3tools/shared/schemaJson";
import { TextGenerationError } from "@t3tools/contracts";
import { type ThreadTitleGenerationResult, type TextGenerationShape } from "./TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import {
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
} from "./TextGenerationUtils.ts";
import {
applyGrokAcpModelSelection,
currentGrokModelIdFromSessionSetup,
makeGrokAcpRuntime,
resolveGrokAcpBaseModelId,
} from "../provider/acp/GrokAcpSupport.ts";
const GROK_TIMEOUT_MS = 180_000;
function mapGrokAcpError(
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
detail: string,
cause: unknown,
): TextGenerationError {
return new TextGenerationError({
operation,
detail,
...(cause !== undefined ? { cause } : {}),
});
}
function isTextGenerationError(error: unknown): error is TextGenerationError {
return (
typeof error === "object" &&
error !== null &&
"_tag" in error &&
error._tag === "TextGenerationError"
);
}
export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(function* (
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
) {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runGrokJson = <S extends Schema.Top>({
operation,
cwd,
prompt,
outputSchemaJson,
modelSelection,
}: {
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
cwd: string;
prompt: string;
outputSchemaJson: S;
modelSelection: ModelSelection;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const resolvedModel = resolveGrokAcpBaseModelId(modelSelection.model);
const outputRef = yield* Ref.make("");
const runtime = yield* makeGrokAcpRuntime({
grokSettings,
environment,
childProcessSpawner: commandSpawner,
cwd,
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
});
yield* runtime.handleSessionUpdate((notification) => {
const update = notification.update;
if (update.sessionUpdate !== "agent_message_chunk") {
return Effect.void;
}
const content = update.content;
if (content.type !== "text") {
return Effect.void;
}
return Ref.update(outputRef, (current) => current + content.text);
});
const promptResult = yield* Effect.gen(function* () {
const started = yield* runtime.start();
yield* applyGrokAcpModelSelection({
runtime,
currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),
requestedModelId: resolvedModel,
mapError: (cause) =>
mapGrokAcpError(
operation,
"Failed to set Grok ACP base model for text generation.",
cause,
),
});
return yield* runtime.prompt({
prompt: [{ type: "text", text: prompt }],
});
}).pipe(
Effect.timeoutOption(GROK_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Grok ACP request timed out." }),
),
onSome: (value) => Effect.succeed(value),
}),
),
Effect.mapError((cause: EffectAcpErrors.AcpError | TextGenerationError) =>
isTextGenerationError(cause)
? cause
: mapGrokAcpError(operation, "Grok ACP request failed.", cause),
),
);
const trimmed = (yield* Ref.get(outputRef)).trim();
if (!trimmed) {
return yield* new TextGenerationError({
operation,
detail:
promptResult.stopReason === "cancelled"
? "Grok ACP request was cancelled."
: "Grok Agent returned empty output.",
});
}
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
return yield* decodeOutput(extractJsonObject(trimmed)).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Grok Agent returned invalid structured output.",
cause,
}),
),
),
);
}).pipe(
Effect.mapError((cause) =>
isTextGenerationError(cause)
? cause
: mapGrokAcpError(operation, "Grok ACP text generation failed.", cause),
),
Effect.scoped,
);
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"GrokTextGeneration.generateCommitMessage",
)(function* (input) {
const { prompt, outputSchema } = buildCommitMessagePrompt({
branch: input.branch,
stagedSummary: input.stagedSummary,
stagedPatch: input.stagedPatch,
includeBranch: input.includeBranch === true,
});
const generated = yield* runGrokJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
};
});
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
"GrokTextGeneration.generatePrContent",
)(function* (input) {
const { prompt, outputSchema } = buildPrContentPrompt({
baseBranch: input.baseBranch,
headBranch: input.headBranch,
commitSummary: input.commitSummary,
diffSummary: input.diffSummary,
diffPatch: input.diffPatch,
});
const generated = yield* runGrokJson({
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
});
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
"GrokTextGeneration.generateBranchName",
)(function* (input) {
const { prompt, outputSchema } = buildBranchNamePrompt({
message: input.message,
attachments: input.attachments,
});
const generated = yield* runGrokJson({
operation: "generateBranchName",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
branch: sanitizeBranchFragment(generated.branch),
};
});
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
"GrokTextGeneration.generateThreadTitle",
)(function* (input) {
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
attachments: input.attachments,
});
const generated = yield* runGrokJson({
operation: "generateThreadTitle",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizeThreadTitle(generated.title),
} satisfies ThreadTitleGenerationResult;
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
} satisfies TextGenerationShape;
});
@@ -10,7 +10,7 @@ import {
} from "../provider/Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "grok" | "opencode";
export interface CommitMessageGenerationInput {
cwd: string;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.24",
"version": "0.0.27",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -184,7 +184,7 @@ export function writeBrowserSavedEnvironmentSecret(
return record;
}
found = true;
const nextRecord = {
const nextRecord: BrowserSavedEnvironmentRecord = {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
+5 -5
View File
@@ -514,7 +514,7 @@ describe("web cloud link environment client", () => {
expect(fetchMock.mock.calls[0]?.[1]?.credentials).not.toBe("include");
expect(String(fetchMock.mock.calls[1]?.[0])).toBe(
"http://127.0.0.1:3000/api/cloud/link-proof",
"http://127.0.0.1:3000/api/connect/link-proof",
);
expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({
method: "POST",
@@ -553,7 +553,7 @@ describe("web cloud link environment client", () => {
});
expect(String(fetchMock.mock.calls[3]?.[0])).toBe(
"http://127.0.0.1:3000/api/cloud/relay-config",
"http://127.0.0.1:3000/api/connect/relay-config",
);
expect(fetchMock.mock.calls[3]?.[1]).toMatchObject({
method: "POST",
@@ -615,7 +615,7 @@ describe("web cloud link environment client", () => {
publishAgentActivity: false,
});
expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
"http://127.0.0.1:3000/api/cloud/link-state",
"http://127.0.0.1:3000/api/connect/link-state",
);
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
method: "GET",
@@ -654,7 +654,7 @@ describe("web cloud link environment client", () => {
}),
);
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink");
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
method: "POST",
credentials: "include",
@@ -698,7 +698,7 @@ describe("web cloud link environment client", () => {
);
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/cloud/unlink");
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
method: "POST",
credentials: "include",
+7 -7
View File
@@ -451,7 +451,7 @@ export function readPrimaryCloudLinkState(): Effect.Effect<
return null;
}
const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"));
return yield* client.cloud
return yield* client.connect
.linkState({ headers: {} })
.pipe(
withPrimaryEnvironmentRequestInit,
@@ -465,7 +465,7 @@ export function updatePrimaryCloudPreferences(input: {
}): Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> {
return Effect.gen(function* () {
const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"));
return yield* client.cloud
return yield* client.connect
.preferences({
headers: {},
payload: input,
@@ -488,7 +488,7 @@ export function unlinkPrimaryEnvironmentFromCloud(input: {
});
}
const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"));
yield* client.cloud
yield* client.connect
.unlink({ headers: {} })
.pipe(
withPrimaryEnvironmentRequestInit,
@@ -568,7 +568,7 @@ export function linkEnvironmentToCloud(input: {
),
),
);
const proof = yield* environmentClient.cloud
const proof = yield* environmentClient.connect
.linkProof({
headers,
payload: {
@@ -604,7 +604,7 @@ export function linkEnvironmentToCloud(input: {
link,
});
yield* environmentClient.cloud
yield* environmentClient.connect
.relayConfig({
headers,
payload: {
@@ -656,7 +656,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
),
),
);
const proof = yield* environmentClient.cloud
const proof = yield* environmentClient.connect
.linkProof({
headers: {},
payload: {
@@ -695,7 +695,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
link,
});
yield* environmentClient.cloud
yield* environmentClient.connect
.relayConfig({
headers: {},
payload: {
+1 -1
View File
@@ -55,7 +55,7 @@ export function usePrimaryCloudLinkState() {
let error: string | null = null;
if (result._tag === "Failure") {
const cause = Cause.squash(result.cause);
error = cause instanceof Error ? cause.message : "Could not read T3 Cloud link state.";
error = cause instanceof Error ? cause.message : "Could not read T3 Connect link state.";
}
return {
+32 -15
View File
@@ -25,6 +25,7 @@ import {
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
import { SelectedModelBadge } from "./chat/SelectedModelBadge";
import { Button } from "./ui/button";
import {
Menu,
@@ -164,23 +165,39 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
value={effectiveEnvMode}
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
>
<MenuRadioItem disabled={envModeLocked} value="local">
<span className="flex min-w-0 items-center gap-1.5">
{activeWorktreePath ? (
<FolderGitIcon className="size-3" />
) : (
<FolderIcon className="size-3" />
)}
<span className="min-w-0 truncate">
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
<MenuRadioItem
disabled={envModeLocked}
value="local"
hideIndicator
className="ps-2 pe-2"
>
<div className="flex w-full min-w-0 items-center justify-between gap-2">
<span className="inline-flex min-w-0 flex-1 items-center gap-1.5">
{activeWorktreePath ? (
<FolderGitIcon className="size-3 shrink-0" />
) : (
<FolderIcon className="size-3 shrink-0" />
)}
<span className="min-w-0 truncate">
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
</span>
</span>
</span>
{effectiveEnvMode === "local" ? <SelectedModelBadge /> : null}
</div>
</MenuRadioItem>
<MenuRadioItem disabled={envModeLocked} value="worktree">
<span className="flex min-w-0 items-center gap-1.5">
<FolderGit2Icon className="size-3" />
<span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
</span>
<MenuRadioItem
disabled={envModeLocked}
value="worktree"
hideIndicator
className="ps-2 pe-2"
>
<div className="flex w-full min-w-0 items-center justify-between gap-2">
<span className="inline-flex min-w-0 flex-1 items-center gap-1.5">
<FolderGit2Icon className="size-3 shrink-0" />
<span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
</span>
{effectiveEnvMode === "worktree" ? <SelectedModelBadge /> : null}
</div>
</MenuRadioItem>
</MenuRadioGroup>
</MenuGroup>
@@ -7,6 +7,7 @@ import {
resolveLockedWorkspaceLabel,
type EnvMode,
} from "./BranchToolbar.logic";
import { SelectedModelBadge } from "./chat/SelectedModelBadge";
import {
Select,
SelectGroup,
@@ -43,13 +44,13 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeWorktreePath ? (
<>
<FolderGitIcon className="size-3" />
{resolveLockedWorkspaceLabel(activeWorktreePath)}
<FolderGitIcon className="size-3 shrink-0" />
<span>{resolveLockedWorkspaceLabel(activeWorktreePath)}</span>
</>
) : (
<>
<FolderIcon className="size-3" />
{resolveLockedWorkspaceLabel(activeWorktreePath)}
<FolderIcon className="size-3 shrink-0" />
<span>{resolveLockedWorkspaceLabel(activeWorktreePath)}</span>
</>
)}
</span>
@@ -65,32 +66,40 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
>
<SelectTrigger variant="ghost" size="xs" className="font-medium" aria-label="Workspace">
{effectiveEnvMode === "worktree" ? (
<FolderGit2Icon className="size-3" />
<FolderGit2Icon className="size-3 shrink-0" />
) : activeWorktreePath ? (
<FolderGitIcon className="size-3" />
<FolderGitIcon className="size-3 shrink-0" />
) : (
<FolderIcon className="size-3" />
<FolderIcon className="size-3 shrink-0" />
)}
<SelectValue />
</SelectTrigger>
<SelectPopup>
<SelectGroup>
<SelectGroupLabel>Workspace</SelectGroupLabel>
<SelectItem value="local">
<span className="inline-flex items-center gap-1.5">
{activeWorktreePath ? (
<FolderGitIcon className="size-3" />
) : (
<FolderIcon className="size-3" />
)}
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
</span>
<SelectItem value="local" hideIndicator className="ps-2 pe-2">
<div className="flex w-full min-w-0 items-center justify-between gap-2">
<span className="inline-flex min-w-0 flex-1 items-center gap-1.5">
{activeWorktreePath ? (
<FolderGitIcon className="size-3 shrink-0" />
) : (
<FolderIcon className="size-3 shrink-0" />
)}
<span className="min-w-0 truncate">
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
</span>
</span>
{effectiveEnvMode === "local" ? <SelectedModelBadge /> : null}
</div>
</SelectItem>
<SelectItem value="worktree">
<span className="inline-flex items-center gap-1.5">
<FolderGit2Icon className="size-3" />
{resolveEnvModeLabel("worktree")}
</span>
<SelectItem value="worktree" hideIndicator className="ps-2 pe-2">
<div className="flex w-full min-w-0 items-center justify-between gap-2">
<span className="inline-flex min-w-0 flex-1 items-center gap-1.5">
<FolderGit2Icon className="size-3 shrink-0" />
<span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
</span>
{effectiveEnvMode === "worktree" ? <SelectedModelBadge /> : null}
</div>
</SelectItem>
</SelectGroup>
</SelectPopup>
@@ -16,6 +16,7 @@ import {
buildExpiredTerminalContextToastCopy,
createLocalDispatchSnapshot,
deriveComposerSendState,
getStartedThreadModelChangeBlockReason,
hasServerAcknowledgedLocalDispatch,
reconcileMountedTerminalThreadIds,
resolveSendEnvMode,
@@ -90,6 +91,73 @@ describe("buildExpiredTerminalContextToastCopy", () => {
});
});
describe("getStartedThreadModelChangeBlockReason", () => {
const providers = [
{
instanceId: ProviderInstanceId.make("codex"),
},
{
instanceId: ProviderInstanceId.make("grok"),
requiresNewThreadForModelChange: true,
},
];
it("allows model changes before a provider session has started", () => {
expect(
getStartedThreadModelChangeBlockReason({
providers,
hasStartedSession: false,
currentModelSelection: {
instanceId: ProviderInstanceId.make("grok"),
model: "grok-build",
},
nextModelSelection: {
instanceId: ProviderInstanceId.make("grok"),
model: "grok-other",
},
}),
).toBeNull();
});
it("allows unchanged model selections for restricted providers", () => {
expect(
getStartedThreadModelChangeBlockReason({
providers,
hasStartedSession: true,
currentModelSelection: {
instanceId: ProviderInstanceId.make("grok"),
model: "grok-build",
},
nextModelSelection: {
instanceId: ProviderInstanceId.make("grok"),
model: "grok-build",
},
}),
).toBeNull();
});
it("blocks started-session model changes when either provider requires a new thread", () => {
expect(
getStartedThreadModelChangeBlockReason({
providers,
hasStartedSession: true,
currentModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
nextModelSelection: {
instanceId: ProviderInstanceId.make("grok"),
model: "grok-build",
},
}),
).toEqual({
title: "Start a new chat to change models",
description:
"This provider does not allow switching models after a conversation has started.",
});
});
});
describe("resolveSendEnvMode", () => {
it("keeps worktree mode for git repositories", () => {
expect(resolveSendEnvMode({ requestedEnvMode: "worktree", isGitRepo: true })).toBe("worktree");
+39
View File
@@ -4,6 +4,7 @@ import {
ProjectId,
type ModelSelection,
type ProviderDriverKind,
type ServerProvider,
type ScopedThreadRef,
type ThreadId,
type TurnId,
@@ -262,6 +263,44 @@ export function deriveLockedProvider(input: {
return narrowedThreadProvider ?? narrowedSelectedProvider ?? null;
}
export function getStartedThreadModelChangeBlockReason(input: {
providers: ReadonlyArray<Pick<ServerProvider, "instanceId" | "requiresNewThreadForModelChange">>;
hasStartedSession: boolean;
currentModelSelection: ModelSelection;
currentProviderInstanceId?: ModelSelection["instanceId"] | null | undefined;
nextModelSelection: ModelSelection;
}): { title: string; description: string } | null {
if (!input.hasStartedSession) {
return null;
}
const currentModelSelection = {
...input.currentModelSelection,
instanceId: input.currentProviderInstanceId ?? input.currentModelSelection.instanceId,
};
if (
currentModelSelection.instanceId === input.nextModelSelection.instanceId &&
currentModelSelection.model === input.nextModelSelection.model
) {
return null;
}
const currentProvider = input.providers.find(
(snapshot) => snapshot.instanceId === currentModelSelection.instanceId,
);
const nextProvider = input.providers.find(
(snapshot) => snapshot.instanceId === input.nextModelSelection.instanceId,
);
if (
currentProvider?.requiresNewThreadForModelChange !== true &&
nextProvider?.requiresNewThreadForModelChange !== true
) {
return null;
}
return {
title: "Start a new chat to change models",
description: "This provider does not allow switching models after a conversation has started.",
};
}
export async function waitForStartedServerThread(
threadRef: ScopedThreadRef,
timeoutMs = 1_000,
+150 -137
View File
@@ -163,6 +163,7 @@ import {
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
getStartedThreadModelChangeBlockReason,
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
LastInvokedScriptByProjectSchema,
type LocalDispatchSnapshot,
@@ -209,131 +210,118 @@ type EnvironmentUnavailableState = {
};
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
type ThreadPlanCatalogStoreState = ReturnType<typeof useStore.getState>;
interface ThreadPlanCatalogCacheEntry {
shell: object | null;
proposedPlanIds: readonly string[] | undefined;
proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
entry: ThreadPlanCatalogEntry;
}
function createThreadPlanCatalogSelector(threadIds: readonly ThreadId[]) {
let previousThreadIds: readonly ThreadId[] = [];
let previousResult: ThreadPlanCatalogEntry[] = [];
let previousEntries = new Map<ThreadId, ThreadPlanCatalogCacheEntry>();
return (state: ThreadPlanCatalogStoreState): ThreadPlanCatalogEntry[] => {
const sameThreadIds =
previousThreadIds.length === threadIds.length &&
previousThreadIds.every((id, index) => id === threadIds[index]);
const nextEntries = new Map<ThreadId, ThreadPlanCatalogCacheEntry>();
const nextResult: ThreadPlanCatalogEntry[] = [];
let changed = !sameThreadIds;
for (const threadId of threadIds) {
let shell: object | undefined;
let proposedPlanIds: readonly string[] | undefined;
let proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
for (const environmentState of Object.values(state.environmentStateById)) {
const matchedShell = environmentState.threadShellById[threadId];
if (!matchedShell) {
continue;
}
shell = matchedShell;
proposedPlanIds = environmentState.proposedPlanIdsByThreadId[threadId];
proposedPlansById = environmentState.proposedPlanByThreadId[threadId] as
| Record<string, Thread["proposedPlans"][number]>
| undefined;
break;
}
if (!shell) {
const previous = previousEntries.get(threadId);
if (
previous &&
previous.shell === null &&
previous.proposedPlanIds === undefined &&
previous.proposedPlansById === undefined
) {
nextEntries.set(threadId, previous);
continue;
}
changed = true;
nextEntries.set(threadId, {
shell: null,
proposedPlanIds: undefined,
proposedPlansById: undefined,
entry: { id: threadId, proposedPlans: EMPTY_PROPOSED_PLANS },
});
continue;
}
const previous = previousEntries.get(threadId);
if (
previous &&
previous.shell === shell &&
previous.proposedPlanIds === proposedPlanIds &&
previous.proposedPlansById === proposedPlansById
) {
nextEntries.set(threadId, previous);
nextResult.push(previous.entry);
continue;
}
changed = true;
const proposedPlans =
proposedPlanIds && proposedPlanIds.length > 0 && proposedPlansById
? proposedPlanIds.flatMap((planId) => {
const proposedPlan = proposedPlansById?.[planId];
return proposedPlan ? [proposedPlan] : [];
})
: EMPTY_PROPOSED_PLANS;
const entry = { id: threadId, proposedPlans };
nextEntries.set(threadId, {
shell,
proposedPlanIds,
proposedPlansById,
entry,
});
nextResult.push(entry);
}
if (!changed && previousResult.length === nextResult.length) {
return previousResult;
}
previousThreadIds = threadIds;
previousEntries = nextEntries;
previousResult = nextResult;
return nextResult;
};
}
function deriveThreadPlanCatalogThreadIds(input: {
activeThreadId: ThreadId | null;
sourceProposedPlanThreadId: ThreadId | null;
}): readonly ThreadId[] {
const threadIds: ThreadId[] = [];
if (input.activeThreadId) {
threadIds.push(input.activeThreadId);
}
if (
input.sourceProposedPlanThreadId &&
input.sourceProposedPlanThreadId !== input.activeThreadId
) {
threadIds.push(input.sourceProposedPlanThreadId);
}
return threadIds;
}
function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] {
const selectThreadPlanCatalog = useMemo(
() => createThreadPlanCatalogSelector(threadIds),
[threadIds],
return useStore(
useMemo(() => {
let previousThreadIds: readonly ThreadId[] = [];
let previousResult: ThreadPlanCatalogEntry[] = [];
let previousEntries = new Map<
ThreadId,
{
shell: object | null;
proposedPlanIds: readonly string[] | undefined;
proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
entry: ThreadPlanCatalogEntry;
}
>();
return (state) => {
const sameThreadIds =
previousThreadIds.length === threadIds.length &&
previousThreadIds.every((id, index) => id === threadIds[index]);
const nextEntries = new Map<
ThreadId,
{
shell: object | null;
proposedPlanIds: readonly string[] | undefined;
proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
entry: ThreadPlanCatalogEntry;
}
>();
const nextResult: ThreadPlanCatalogEntry[] = [];
let changed = !sameThreadIds;
for (const threadId of threadIds) {
let shell: object | undefined;
let proposedPlanIds: readonly string[] | undefined;
let proposedPlansById: Record<string, Thread["proposedPlans"][number]> | undefined;
for (const environmentState of Object.values(state.environmentStateById)) {
const matchedShell = environmentState.threadShellById[threadId];
if (!matchedShell) {
continue;
}
shell = matchedShell;
proposedPlanIds = environmentState.proposedPlanIdsByThreadId[threadId];
proposedPlansById = environmentState.proposedPlanByThreadId[threadId] as
| Record<string, Thread["proposedPlans"][number]>
| undefined;
break;
}
if (!shell) {
const previous = previousEntries.get(threadId);
if (
previous &&
previous.shell === null &&
previous.proposedPlanIds === undefined &&
previous.proposedPlansById === undefined
) {
nextEntries.set(threadId, previous);
continue;
}
changed = true;
nextEntries.set(threadId, {
shell: null,
proposedPlanIds: undefined,
proposedPlansById: undefined,
entry: { id: threadId, proposedPlans: EMPTY_PROPOSED_PLANS },
});
continue;
}
const previous = previousEntries.get(threadId);
if (
previous &&
previous.shell === shell &&
previous.proposedPlanIds === proposedPlanIds &&
previous.proposedPlansById === proposedPlansById
) {
nextEntries.set(threadId, previous);
nextResult.push(previous.entry);
continue;
}
changed = true;
const proposedPlans =
proposedPlanIds && proposedPlanIds.length > 0 && proposedPlansById
? proposedPlanIds.flatMap((planId) => {
const proposedPlan = proposedPlansById?.[planId];
return proposedPlan ? [proposedPlan] : [];
})
: EMPTY_PROPOSED_PLANS;
const entry = { id: threadId, proposedPlans };
nextEntries.set(threadId, {
shell,
proposedPlanIds,
proposedPlansById,
entry,
});
nextResult.push(entry);
}
if (!changed && previousResult.length === nextResult.length) {
return previousResult;
}
previousThreadIds = threadIds;
previousEntries = nextEntries;
previousResult = nextResult;
return nextResult;
};
}, [threadIds]),
);
return useStore(selectThreadPlanCatalog);
}
function formatOutgoingPrompt(params: {
@@ -1041,16 +1029,19 @@ export default function ChatView(props: ChatViewProps) {
return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));
}, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]);
const activeLatestTurn = activeThread?.latestTurn ?? null;
const sourceProposedPlanThreadId = activeLatestTurn?.sourceProposedPlan?.threadId ?? null;
const threadPlanCatalogThreadIds = useMemo(
() =>
deriveThreadPlanCatalogThreadIds({
activeThreadId,
sourceProposedPlanThreadId,
}),
[activeThreadId, sourceProposedPlanThreadId],
const threadPlanCatalog = useThreadPlanCatalog(
useMemo(() => {
const threadIds: ThreadId[] = [];
if (activeThread?.id) {
threadIds.push(activeThread.id);
}
const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId;
if (sourceThreadId && sourceThreadId !== activeThread?.id) {
threadIds.push(sourceThreadId);
}
return threadIds;
}, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]),
);
const threadPlanCatalog = useThreadPlanCatalog(threadPlanCatalogThreadIds);
useEffect(() => {
setMountedTerminalThreadKeys((currentThreadIds) => {
const nextThreadIds = reconcileMountedTerminalThreadIds({
@@ -1994,15 +1985,18 @@ export default function ChatView(props: ChatViewProps) {
const focusComposer = useCallback(() => {
composerRef.current?.focusAtEnd();
}, []);
}, [composerRef]);
const scheduleComposerFocus = useCallback(() => {
window.requestAnimationFrame(() => {
focusComposer();
});
}, [focusComposer]);
const addTerminalContextToDraft = useCallback((selection: TerminalContextSelection) => {
composerRef.current?.addTerminalContext(selection);
}, []);
const addTerminalContextToDraft = useCallback(
(selection: TerminalContextSelection) => {
composerRef.current?.addTerminalContext(selection);
},
[composerRef],
);
const setTerminalOpen = useCallback(
(open: boolean) => {
if (!activeThreadRef) return;
@@ -2781,6 +2775,7 @@ export default function ChatView(props: ChatViewProps) {
keybindings,
onToggleDiff,
toggleTerminalVisibility,
composerRef,
]);
const onRevertToTurnCount = useCallback(
@@ -3255,7 +3250,7 @@ export default function ChatView(props: ChatViewProps) {
promptRef.current = "";
composerRef.current?.resetCursorState({ cursor: 0 });
},
[activePendingProgress?.activeQuestion, activePendingUserInput],
[activePendingProgress?.activeQuestion, activePendingUserInput, composerRef],
);
const onChangeActivePendingUserInputCustomAnswer = useCallback(
@@ -3289,7 +3284,7 @@ export default function ChatView(props: ChatViewProps) {
composerRef.current?.focusAt(nextCursor);
}
},
[activePendingUserInput],
[activePendingUserInput, composerRef],
);
const onAdvanceActivePendingUserInput = useCallback(() => {
@@ -3461,6 +3456,7 @@ export default function ChatView(props: ChatViewProps) {
setThreadError,
autoOpenPlanSidebar,
environmentId,
composerRef,
],
);
@@ -3598,6 +3594,7 @@ export default function ChatView(props: ChatViewProps) {
runtimeMode,
autoOpenPlanSidebar,
environmentId,
composerRef,
]);
const onProviderModelSelect = useCallback(
@@ -3643,6 +3640,22 @@ export default function ChatView(props: ChatViewProps) {
instanceId,
model: resolvedModel,
};
const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({
providers: providerStatuses,
hasStartedSession: activeThread.session !== null,
currentModelSelection: activeThread.modelSelection,
currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null,
nextModelSelection,
});
if (modelChangeBlockReason) {
toastManager.add({
type: "warning",
title: modelChangeBlockReason.title,
description: modelChangeBlockReason.description,
});
scheduleComposerFocus();
return;
}
setComposerDraftModelSelection(
scopeThreadRef(activeThread.environmentId, activeThread.id),
nextModelSelection,
+12
View File
@@ -199,6 +199,18 @@ export const CursorIcon: Icon = ({ className, ...props }) => (
</svg>
);
export const GrokIcon: Icon = ({ className, ...props }) => (
<svg
{...props}
viewBox="0 0 24 24"
fill="none"
className={cn("fill-[#0F0F0F] dark:fill-[#F5F5F5]", className)}
>
<path d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861" />
<path d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257" />
</svg>
);
export const TraeIcon: Icon = (props) => (
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
{/* Back rectangle: left strip + bottom strip drawn separately — empty bottom-left corner is the gap between them */}
@@ -158,6 +158,7 @@ function createBaseServerConfig(): ServerConfig {
launchArgs: "",
},
cursor: { enabled: true, binaryPath: "", apiEndpoint: "", customModels: [] },
grok: { enabled: true, binaryPath: "", customModels: [] },
opencode: {
enabled: true,
binaryPath: "",
@@ -59,6 +59,7 @@ import {
} from "../composerFooterLayout";
import { type ComposerPromptEditorHandle, ComposerPromptEditor } from "../ComposerPromptEditor";
import { ProviderModelPicker } from "./ProviderModelPicker";
import { SelectedModelBadge } from "./SelectedModelBadge";
import { type ComposerCommandItem, ComposerCommandMenu } from "./ComposerCommandMenu";
import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
@@ -231,15 +232,17 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
<SelectValue>{runtimeModeOption.label}</SelectValue>
</SelectTrigger>
<SelectPopup alignItemWithTrigger={false}>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Permissions</div>
{runtimeModeOptions.map((mode) => {
const option = runtimeModeConfig[mode];
const OptionIcon = option.icon;
return (
<SelectItem key={mode} value={mode} className="min-w-64 py-2">
<SelectItem key={mode} value={mode} className="min-w-64 py-2" hideIndicator>
<div className="grid min-w-0 gap-0.5">
<span className="inline-flex items-center gap-1.5 font-medium text-foreground">
<OptionIcon className="size-3.5 shrink-0 text-muted-foreground" />
{option.label}
{mode === props.runtimeMode ? <SelectedModelBadge /> : null}
</span>
<span className="text-muted-foreground text-xs leading-4">
{option.description}
@@ -11,6 +11,15 @@ import {
MenuSeparator as MenuDivider,
MenuTrigger,
} from "../ui/menu";
import { SelectedModelBadge } from "./SelectedModelBadge";
const runtimeModeLabels: Record<RuntimeMode, string> = {
"approval-required": "Supervised",
"auto-accept-edits": "Auto-accept edits",
"full-access": "Full access",
};
const runtimeModeOptions = Object.keys(runtimeModeLabels) as RuntimeMode[];
export const CompactComposerControlsMenu = memo(function CompactComposerControlsMenu(props: {
activePlan: boolean;
@@ -69,9 +78,14 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
props.onRuntimeModeChange(value as RuntimeMode);
}}
>
<MenuRadioItem value="approval-required">Supervised</MenuRadioItem>
<MenuRadioItem value="auto-accept-edits">Auto-accept edits</MenuRadioItem>
<MenuRadioItem value="full-access">Full access</MenuRadioItem>
{runtimeModeOptions.map((mode) => (
<MenuRadioItem key={mode} value={mode} hideIndicator>
<span className="inline-flex items-center gap-1.5">
{runtimeModeLabels[mode]}
{mode === props.runtimeMode ? <SelectedModelBadge /> : null}
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
{props.activePlan ? (
<>
@@ -0,0 +1,18 @@
import { CheckIcon } from "lucide-react";
import { Badge } from "../ui/badge";
export function SelectedModelBadge() {
return <CheckIcon className="size-3.5 shrink-0 text-blue-400" />;
}
export function DefaultBadge() {
return (
<Badge
variant="outline"
className="inline-flex h-4 w-fit min-w-0 items-center justify-center gap-0 ps-1.5 pe-1.5 py-0 text-[10px] font-semibold leading-none border-border/70 bg-muted/60 text-muted-foreground sm:h-4"
>
Default
</Badge>
);
}
@@ -1,5 +1,5 @@
import { ProviderDriverKind } from "@t3tools/contracts";
import { ClaudeAI, CursorIcon, Icon, OpenAI, OpenCodeIcon } from "../Icons";
import { ClaudeAI, CursorIcon, GrokIcon, Icon, OpenAI, OpenCodeIcon } from "../Icons";
import { PROVIDER_OPTIONS } from "../../session-logic";
export const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>> = {
@@ -7,6 +7,7 @@ export const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>
[ProviderDriverKind.make("claudeAgent")]: ClaudeAI,
[ProviderDriverKind.make("opencode")]: OpenCodeIcon,
[ProviderDriverKind.make("cursor")]: CursorIcon,
[ProviderDriverKind.make("grok")]: GrokIcon,
};
function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is {
@@ -0,0 +1,60 @@
import { UserButton, useAuth } from "@clerk/react";
import { LogInIcon } from "lucide-react";
import { hasCloudPublicConfig } from "../../cloud/publicConfig";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar";
import { useT3ConnectAuthPrompt } from "./useT3ConnectAuthPrompt";
export function T3ConnectSidebarSignIn() {
if (!hasCloudPublicConfig()) return null;
return <ConfiguredT3ConnectSidebarSignIn />;
}
export function T3ConnectSidebarAvatar() {
if (!hasCloudPublicConfig()) return null;
return <ConfiguredT3ConnectSidebarAvatar />;
}
function ConfiguredT3ConnectSidebarAvatar() {
const { isLoaded, isSignedIn } = useAuth();
if (!isLoaded || !isSignedIn) return null;
return (
<UserButton
appearance={{
elements: {
avatarBox: "size-7",
userButtonTrigger: "rounded-lg p-1 hover:bg-sidebar-accent",
},
}}
/>
);
}
function ConfiguredT3ConnectSidebarSignIn() {
const { isLoaded, isSignedIn } = useAuth();
const { authPrompt, openAuthPrompt } = useT3ConnectAuthPrompt();
if (!isLoaded || isSignedIn) return null;
return (
<>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
onClick={openAuthPrompt}
>
<LogInIcon className="size-4" />
<span>Sign in to T3 Connect</span>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
{authPrompt}
</>
);
}
@@ -0,0 +1,29 @@
import { useClerk } from "@clerk/react";
import { useState } from "react";
import { isElectron } from "../../env";
import { Dialog, DialogPopup } from "../ui/dialog";
import { DesktopClerkWaitlist } from "./DesktopClerkWaitlist";
export function useT3ConnectAuthPrompt() {
const clerk = useClerk();
const [desktopAuthOpen, setDesktopAuthOpen] = useState(false);
const openAuthPrompt = () => {
if (isElectron) {
setDesktopAuthOpen(true);
return;
}
clerk.openWaitlist();
};
const authPrompt = isElectron ? (
<Dialog open={desktopAuthOpen} onOpenChange={setDesktopAuthOpen}>
<DialogPopup className="max-w-md border-0 bg-transparent shadow-none" showCloseButton={false}>
<DesktopClerkWaitlist />
</DialogPopup>
</Dialog>
) : null;
return { authPrompt, openAuthPrompt };
}
@@ -69,8 +69,8 @@ export function RelayClientInstallDialog() {
</DialogTitle>
<DialogDescription>
{isInstalling
? "T3 Code is preparing this environment for secure access through T3 Cloud."
: "T3 Code needs the relay client to make this environment available through T3 Cloud."}
? "T3 Code is preparing this environment for secure access through T3 Connect."
: "T3 Code needs the relay client to make this environment available through T3 Connect."}
</DialogDescription>
</DialogHeader>
<DialogPanel scrollFade={false}>
@@ -1,197 +0,0 @@
import { UserButton, Waitlist, useAuth } from "@clerk/react";
import { AuthRelayWriteScope } from "@t3tools/contracts";
import { CloudIcon, RefreshCwIcon, SmartphoneIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { updatePrimaryCloudPreferences } from "../../cloud/linkEnvironment";
import { hasCloudPublicConfig } from "../../cloud/publicConfig";
import { useManagedRelayDevices } from "../../cloud/managedRelayState";
import { usePrimaryCloudLinkState } from "../../cloud/primaryCloudLinkState";
import { isElectron } from "../../env";
import { usePrimarySessionState } from "../../environments/primary";
import { webRuntime } from "../../lib/runtime";
import { cn } from "../../lib/utils";
import { DesktopClerkWaitlist } from "../clerk/DesktopClerkWaitlist";
import { Button } from "../ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
import { Skeleton } from "../ui/skeleton";
import { Switch } from "../ui/switch";
import { toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
const NOTIFICATION_DEVICE_SKELETON_ROWS = ["primary", "secondary"] as const;
function NotificationDevicesSkeleton() {
return NOTIFICATION_DEVICE_SKELETON_ROWS.map((row) => (
<div key={row} className="border-t border-border/60 px-4 py-3.5 first:border-t-0 sm:px-5">
<div className="space-y-2">
<Skeleton className="h-4 w-32 rounded-full" />
<Skeleton className="h-3 w-44 rounded-full" />
<Skeleton className="h-3 w-56 rounded-full" />
</div>
</div>
));
}
function EmptyNotificationDevices() {
return (
<Empty className="min-h-52">
<EmptyMedia variant="icon">
<SmartphoneIcon />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle>No notification devices</EmptyTitle>
<EmptyDescription>
Sign in on the mobile app to register a device for account-level notifications.
</EmptyDescription>
</EmptyHeader>
</Empty>
);
}
function cloudErrorMessage(error: unknown, fallback: string): string {
return error instanceof Error ? error.message : fallback;
}
export function CloudSettingsPanel() {
if (!hasCloudPublicConfig()) return null;
return <ConfiguredCloudSettingsPanel />;
}
function ConfiguredCloudSettingsPanel() {
const { isLoaded, isSignedIn } = useAuth();
if (!isLoaded) {
return null;
}
return isSignedIn ? <CloudSettingsPanelInner /> : <CloudWaitlistPanel />;
}
function CloudWaitlistPanel() {
return (
<SettingsPageContainer className="min-h-full items-center justify-center">
{isElectron ? <DesktopClerkWaitlist /> : <Waitlist />}
</SettingsPageContainer>
);
}
function CloudSettingsPanelInner() {
const primaryLinkState = usePrimaryCloudLinkState();
const primarySessionState = usePrimarySessionState();
const devicesState = useManagedRelayDevices();
const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
const devices = devicesState.data ?? [];
const canManageRelay =
primarySessionState.data?.authenticated === true &&
Boolean(primarySessionState.data.scopes?.includes(AuthRelayWriteScope));
useEffect(() => {
if (devicesState.error) {
toastManager.add({
type: "error",
title: "Cloud devices unavailable",
description: devicesState.error,
});
}
}, [devicesState.error]);
const updatePublishAgentActivity = async (enabled: boolean) => {
setIsUpdatingPreference(true);
try {
await webRuntime.runPromise(updatePrimaryCloudPreferences({ publishAgentActivity: enabled }));
primaryLinkState.refresh();
toastManager.add({
type: "success",
title: enabled ? "Agent activity enabled" : "Agent activity disabled",
description: enabled
? "This environment can publish agent activity to your notification devices."
: "This environment will stop publishing agent activity.",
});
} catch (error) {
toastManager.add({
type: "error",
title: "Cloud preference update failed",
description: cloudErrorMessage(error, "Could not update cloud preferences."),
});
} finally {
setIsUpdatingPreference(false);
}
};
return (
<SettingsPageContainer>
<SettingsSection title="T3 Cloud" icon={<CloudIcon className="size-3.5" />}>
<SettingsRow
title="Cloud account"
description="Manage your private-beta T3 Cloud session."
control={<UserButton />}
/>
</SettingsSection>
<SettingsSection title="Preferences">
<SettingsRow
title="Publish agent activity"
description="Allow this environment to send agent activity to your notification devices."
status={
!primaryLinkState.data?.linked ? "Link this environment from Connections first." : null
}
control={
<Switch
aria-label="Publish agent activity"
checked={primaryLinkState.data?.publishAgentActivity ?? false}
disabled={!primaryLinkState.data?.linked || !canManageRelay || isUpdatingPreference}
onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}
/>
}
/>
</SettingsSection>
<SettingsSection
title="Notification devices"
headerAction={
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-xs"
variant="ghost"
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
disabled={devicesState.isPending}
onClick={devicesState.refresh}
aria-label="Refresh notification devices"
>
<RefreshCwIcon
className={cn("size-3", devicesState.isPending && "animate-spin")}
/>
</Button>
}
/>
<TooltipPopup side="top">Refresh notification devices</TooltipPopup>
</Tooltip>
}
>
{devicesState.data === null ? (
<NotificationDevicesSkeleton />
) : devices.length > 0 ? (
devices.map((device) => (
<SettingsRow
key={device.deviceId}
title={device.label}
description={`iOS ${device.iosMajorVersion}${device.appVersion ? ` · T3 Code ${device.appVersion}` : ""}`}
status={
device.notifications.enabled
? device.liveActivities.enabled
? "Notifications and Live Activities enabled"
: "Notifications enabled · Live Activities disabled"
: "Notifications disabled on device"
}
/>
))
) : (
<EmptyNotificationDevices />
)}
</SettingsSection>
</SettingsPageContainer>
);
}
@@ -76,6 +76,7 @@ import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { Button } from "../ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
import { Group, GroupSeparator } from "../ui/group";
import { AnimatedHeight } from "../AnimatedHeight";
import {
@@ -121,6 +122,7 @@ import {
connectManagedCloudEnvironment,
linkPrimaryEnvironmentToCloud,
unlinkPrimaryEnvironmentFromCloud,
updatePrimaryCloudPreferences,
} from "~/cloud/linkEnvironment";
import {
refreshManagedRelayEnvironments,
@@ -1614,7 +1616,7 @@ function CloudLinkSwitch({
}) {
const control = (
<Switch
aria-label="Enable T3 Cloud"
aria-label="Enable T3 Connect"
checked={checked}
disabled={disabled}
{...(onCheckedChange ? { onCheckedChange } : {})}
@@ -1632,9 +1634,11 @@ function CloudLinkSwitch({
function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {
const { getToken, isSignedIn } = useAuth();
const { authPrompt, openAuthPrompt } = useT3ConnectAuthPrompt();
const primaryCloudLinkState = usePrimaryCloudLinkState();
const [operationError, setOperationError] = useState<string | null>(null);
const [isUpdating, setIsUpdating] = useState(false);
const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
const updateLink = async (enabled: boolean) => {
setIsUpdating(true);
@@ -1643,7 +1647,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
const clerkToken = await getToken(resolveRelayClerkTokenOptions());
if (enabled) {
if (!clerkToken) {
throw new Error("Sign in from T3 Cloud settings before linking this environment.");
throw new Error("Sign in to T3 Connect before linking this environment.");
}
await webRuntime.runPromise(linkPrimaryEnvironmentToCloud({ clerkToken }));
} else {
@@ -1655,48 +1659,103 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
refreshManagedRelayEnvironments();
toastManager.add({
type: "success",
title: enabled ? "T3 Cloud linked" : "T3 Cloud unlinked",
title: enabled ? "T3 Connect linked" : "T3 Connect unlinked",
description: enabled
? "This environment is available through T3 Cloud."
: "This environment is no longer available through T3 Cloud.",
? "This environment is available through T3 Connect."
: "This environment is no longer available through T3 Connect.",
});
} catch (cause) {
const message = cause instanceof Error ? cause.message : "Could not update T3 Cloud access.";
const message =
cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
setOperationError(message);
toastManager.add({
type: "error",
title: "Could not update T3 Cloud",
title: "Could not update T3 Connect",
description: message,
});
} finally {
setIsUpdating(false);
}
};
const updatePublishAgentActivity = async (enabled: boolean) => {
setIsUpdatingPreference(true);
try {
await webRuntime.runPromise(updatePrimaryCloudPreferences({ publishAgentActivity: enabled }));
primaryCloudLinkState.refresh();
toastManager.add({
type: "success",
title: enabled ? "Agent activity enabled" : "Agent activity disabled",
description: enabled
? "This environment can publish agent activity to your notification devices."
: "This environment will stop publishing agent activity.",
});
} catch (cause) {
toastManager.add({
type: "error",
title: "Could not update T3 Connect preferences",
description:
cause instanceof Error ? cause.message : "Could not update agent activity publishing.",
});
} finally {
setIsUpdatingPreference(false);
}
};
const disabledReason = !isSignedIn
? "Sign in from T3 Cloud settings to manage this environment."
? "Sign in to T3 Connect"
: !canManageRelay
? "Your session does not have permission to manage T3 Cloud access."
? "Your session does not have permission to manage T3 Connect access."
: null;
const linked = primaryCloudLinkState.data?.linked ?? false;
return (
<SettingsRow
title="T3 Cloud"
description={
linked
? "This environment is available to your other devices through T3 Cloud."
: "Make this environment available to your other devices through T3 Cloud."
}
status={operationError ?? primaryCloudLinkState.error}
control={
<CloudLinkSwitch
checked={linked}
disabled={!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isUpdating}
disabledReason={disabledReason}
onCheckedChange={(enabled) => void updateLink(enabled)}
<>
<SettingsRow
title="T3 Connect"
description={
linked
? "This environment is available to your other devices through T3 Connect."
: "Make this environment available to your other devices through T3 Connect."
}
status={operationError ?? primaryCloudLinkState.error}
control={
<CloudLinkSwitch
checked={linked}
disabled={
(isSignedIn && !canManageRelay) || primaryCloudLinkState.isPending || isUpdating
}
disabledReason={disabledReason}
onCheckedChange={(enabled) => {
if (!isSignedIn) {
openAuthPrompt();
return;
}
void updateLink(enabled);
}}
/>
}
/>
{linked ? (
<SettingsRow
title="Publish agent activity"
description="Send agent activity from this environment to your notification devices."
className="bg-muted/20 pl-7 sm:pl-8"
control={
<Switch
aria-label="Publish agent activity"
checked={primaryCloudLinkState.data?.publishAgentActivity ?? false}
disabled={
!canManageRelay ||
!isSignedIn ||
primaryCloudLinkState.isPending ||
isUpdatingPreference
}
onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}
/>
}
/>
}
/>
) : null}
{authPrompt}
</>
);
}
@@ -1704,7 +1763,13 @@ function CloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean })
return hasCloudPublicConfig() ? <ConfiguredCloudLinkRow canManageRelay={canManageRelay} /> : null;
}
function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnabled?: boolean }) {
function EmptyRemoteEnvironments({
cloudEnabled = true,
onConnectFromCloud,
}: {
readonly cloudEnabled?: boolean;
readonly onConnectFromCloud?: () => void;
}) {
return (
<Empty className="min-h-52">
<EmptyMedia variant="icon">
@@ -1713,9 +1778,24 @@ function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnable
<EmptyHeader>
<EmptyTitle>No saved remote environments</EmptyTitle>
<EmptyDescription>
{cloudEnabled
? "Click “Add environment” to pair another environment, or connect one from T3 Cloud."
: "Click “Add environment” to pair another environment."}
Click “Add environment” to pair another environment
{cloudEnabled ? (
<>
, or connect one from{" "}
{onConnectFromCloud ? (
<button
type="button"
className="border-b border-dotted border-current text-foreground/80 hover:text-foreground"
onClick={onConnectFromCloud}
>
T3 Connect
</button>
) : (
"T3 Connect"
)}
</>
) : null}
.
</EmptyDescription>
</EmptyHeader>
</Empty>
@@ -1743,7 +1823,8 @@ function ConfiguredCloudRemoteEnvironmentRows({
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
}) {
const { getToken } = useAuth();
const { getToken, isSignedIn } = useAuth();
const { authPrompt, openAuthPrompt } = useT3ConnectAuthPrompt();
const environmentsState = useManagedRelayEnvironments();
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
null,
@@ -1755,7 +1836,7 @@ function ConfiguredCloudRemoteEnvironmentRows({
try {
const clerkToken = await getToken(resolveRelayClerkTokenOptions());
if (!clerkToken) {
throw new Error("Sign in from T3 Cloud settings before connecting this environment.");
throw new Error("Sign in to T3 Connect before connecting this environment.");
}
const connection = await webRuntime.runPromise(
connectManagedCloudEnvironment({ clerkToken, environment }),
@@ -1764,14 +1845,14 @@ function ConfiguredCloudRemoteEnvironmentRows({
toastManager.add({
type: "success",
title: "Environment connected",
description: `${connection.label} is available through T3 Cloud.`,
description: `${connection.label} is available through T3 Connect.`,
});
} catch (cause) {
toastManager.add({
type: "error",
title: "Could not connect environment",
description:
cause instanceof Error ? cause.message : "Could not connect the T3 Cloud environment.",
cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.",
});
} finally {
setConnectingEnvironmentId(null);
@@ -1789,7 +1870,12 @@ function ConfiguredCloudRemoteEnvironmentRows({
}
if (savedEnvironmentIds.length === 0 && connectableEnvironments.length === 0) {
return <EmptyRemoteEnvironments />;
return (
<>
<EmptyRemoteEnvironments {...(!isSignedIn ? { onConnectFromCloud: openAuthPrompt } : {})} />
{authPrompt}
</>
);
}
return connectableEnvironments.map((environment) => (
@@ -1799,11 +1885,11 @@ function ConfiguredCloudRemoteEnvironmentRows({
<div className="flex items-center gap-2">
<ConnectionStatusDot
dotClassName="bg-muted-foreground/35"
tooltipText="Available through T3 Cloud"
tooltipText="Available through T3 Connect"
/>
<p className="truncate text-sm font-medium">{environment.label}</p>
</div>
<p className="mt-1 truncate text-xs text-muted-foreground">T3 Cloud</p>
<p className="mt-1 truncate text-xs text-muted-foreground">T3 Connect</p>
</div>
<Button
size="sm"
@@ -149,12 +149,16 @@ const authAccessHarness = vi.hoisted(() => {
const mockConnectDesktopSshEnvironment = vi.hoisted(() => vi.fn());
const mockGetClerkToken = vi.hoisted(() => vi.fn(async () => null));
const mockOpenClerkWaitlist = vi.hoisted(() => vi.fn());
vi.mock("@clerk/react", () => ({
useAuth: () => ({
getToken: mockGetClerkToken,
isSignedIn: false,
}),
useClerk: () => ({
openWaitlist: mockOpenClerkWaitlist,
}),
}));
vi.mock("../../environments/runtime", () => {
@@ -3,7 +3,6 @@ import {
ArchiveIcon,
ArrowLeftIcon,
BotIcon,
CloudIcon,
GitBranchIcon,
KeyboardIcon,
Link2Icon,
@@ -21,15 +20,13 @@ import {
SidebarSeparator,
useSidebar,
} from "../ui/sidebar";
import { Badge } from "../ui/badge";
import { hasCloudPublicConfig } from "../../cloud/publicConfig";
import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn";
export type SettingsSectionPath =
| "/settings/general"
| "/settings/keybindings"
| "/settings/providers"
| "/settings/source-control"
| "/settings/cloud"
| "/settings/connections"
| "/settings/archived";
@@ -37,13 +34,11 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
label: string;
to: SettingsSectionPath;
icon: ComponentType<{ className?: string }>;
badgeLabel?: string;
}> = [
{ label: "General", to: "/settings/general", icon: Settings2Icon },
{ label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon },
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
{ label: "T3 Cloud", to: "/settings/cloud", icon: CloudIcon, badgeLabel: "Private Beta" },
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
];
@@ -77,9 +72,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
<SidebarContent className="overflow-x-hidden">
<SidebarGroup className="px-2 py-3">
<SidebarMenu>
{SETTINGS_NAV_ITEMS.filter(
(item) => item.to !== "/settings/cloud" || hasCloudPublicConfig(),
).map((item) => {
{SETTINGS_NAV_ITEMS.map((item) => {
const Icon = item.icon;
const isActive = pathname === item.to;
return (
@@ -102,11 +95,6 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
}
/>
<span className="truncate">{item.label}</span>
{item.badgeLabel ? (
<Badge variant="warning" size="sm" className="ml-auto">
{item.badgeLabel}
</Badge>
) : null}
</SidebarMenuButton>
</SidebarMenuItem>
);
@@ -117,18 +105,22 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
<SidebarSeparator />
<SidebarFooter className="p-2">
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
onClick={handleBackClick}
>
<ArrowLeftIcon className="size-4" />
<span>Back</span>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
<T3ConnectSidebarSignIn />
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
<SidebarMenu className="min-w-0">
<SidebarMenuItem>
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-2 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
onClick={handleBackClick}
>
<ArrowLeftIcon className="size-4" />
<span>Back</span>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
<T3ConnectSidebarAvatar />
</div>
</SidebarFooter>
</>
);
@@ -2,11 +2,12 @@ import {
ClaudeSettings,
CodexSettings,
CursorSettings,
GrokSettings,
OpenCodeSettings,
ProviderDriverKind,
} from "@t3tools/contracts";
import type * as Schema from "effect/Schema";
import { ClaudeAI, CursorIcon, type Icon, OpenAI, OpenCodeIcon } from "../Icons";
import { ClaudeAI, CursorIcon, GrokIcon, type Icon, OpenAI, OpenCodeIcon } from "../Icons";
type ProviderSettingsSchema = {
readonly fields: Readonly<Record<string, Schema.Top>>;
@@ -53,6 +54,13 @@ export const PROVIDER_CLIENT_DEFINITIONS: readonly ProviderClientDefinition[] =
badgeLabel: "Early Access",
settingsSchema: CursorSettings,
},
{
value: ProviderDriverKind.make("grok"),
label: "Grok",
icon: GrokIcon,
badgeLabel: "Early Access",
settingsSchema: GrokSettings,
},
{
value: ProviderDriverKind.make("opencode"),
label: "OpenCode",
+28 -18
View File
@@ -147,32 +147,42 @@ function MenuRadioGroup(props: MenuPrimitive.RadioGroup.Props) {
return <MenuPrimitive.RadioGroup data-slot="menu-radio-group" {...props} />;
}
function MenuRadioItem({ className, children, ...props }: MenuPrimitive.RadioItem.Props) {
function MenuRadioItem({
className,
children,
hideIndicator = false,
...props
}: MenuPrimitive.RadioItem.Props & {
hideIndicator?: boolean;
}) {
return (
<MenuPrimitive.RadioItem
className={cn(
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default items-center gap-2 rounded-sm py-1 text-base text-foreground outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
hideIndicator ? "grid-cols-[1fr] ps-3 pe-3" : "grid-cols-[1rem_1fr] ps-2 pe-4",
className,
)}
data-slot="menu-radio-item"
{...props}
>
<MenuPrimitive.RadioItemIndicator className="col-start-1">
<svg
fill="none"
height="24"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
</svg>
</MenuPrimitive.RadioItemIndicator>
<span className="col-start-2">{children}</span>
{hideIndicator ? null : (
<MenuPrimitive.RadioItemIndicator className="col-start-1">
<svg
fill="none"
height="24"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
viewBox="0 0 24 24"
width="24"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
</svg>
</MenuPrimitive.RadioItemIndicator>
)}
<span className={hideIndicator ? "col-start-1" : "col-start-2"}>{children}</span>
</MenuPrimitive.RadioItem>
);
}
@@ -15,6 +15,10 @@ import {
writeSavedEnvironmentCredential,
} from "./catalog";
let resolveRegistryRead: () => void = () => {
throw new Error("Registry read resolver was not initialized.");
};
describe("environment runtime catalog stores", () => {
beforeEach(async () => {
vi.stubGlobal("window", {
@@ -138,7 +142,7 @@ describe("environment runtime catalog stores", () => {
});
it("does not let stale hydration overwrite records added while hydration is in flight", async () => {
let resolveRegistryRead: () => void = () => {
resolveRegistryRead = () => {
throw new Error("Registry read resolver was not initialized.");
};
+1 -1
View File
@@ -1582,7 +1582,7 @@ async function ensureSavedEnvironmentConnection(
await removeSavedEnvironmentBearerToken(activeRecord.environmentId);
throw new Error(
activeCredential.current.method === "dpop"
? "Managed tunnel credential expired. Connect it again from T3 Cloud."
? "Managed tunnel credential expired. Connect it again from T3 Connect."
: "Saved environment credential expired. Pair it again.",
{
cause: error,
+1 -2
View File
@@ -27,7 +27,6 @@ if (isElectron) {
document.title = APP_DISPLAY_NAME;
const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined;
const cloudWaitlistUrl = "/settings/cloud";
const app = <RouterProvider router={router} />;
@@ -39,7 +38,7 @@ ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
</DesktopClerkProvider>
) : (
<ClerkProvider publishableKey={clerkPublishableKey} waitlistUrl={cloudWaitlistUrl}>
<ClerkProvider publishableKey={clerkPublishableKey}>
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
</ClerkProvider>
)
+21
View File
@@ -101,6 +101,27 @@ describe("instance-scoped model selection", () => {
).toBe("openai/gpt-5.5");
});
it("includes Grok custom models from the selected provider instance", () => {
const providers = [provider({ provider: ProviderDriverKind.make("grok"), instanceId: "grok" })];
const settings: UnifiedSettings = {
...settingsWithProviderInstances(),
providerInstances: {
...settingsWithProviderInstances().providerInstances,
[ProviderInstanceId.make("grok")]: {
driver: ProviderDriverKind.make("grok"),
config: { customModels: ["grok-test-custom-model"] },
},
},
};
const grok = deriveProviderInstanceEntries(providers).find(
(entry) => entry.instanceId === "grok",
)!;
expect(getAppModelOptionsForInstance(settings, grok).map((option) => option.slug)).toContain(
"grok-test-custom-model",
);
});
it("does not inject an unknown selected slug into the stock instance list", () => {
const providers = [
provider({
-21
View File
@@ -19,7 +19,6 @@ import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybi
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsCloudRouteImport } from './routes/settings.cloud'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
@@ -73,11 +72,6 @@ const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({
path: '/connections',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsCloudRoute = SettingsCloudRouteImport.update({
id: '/cloud',
path: '/cloud',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
id: '/archived',
path: '/archived',
@@ -100,7 +94,6 @@ export interface FileRoutesByFullPath {
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/settings/archived': typeof SettingsArchivedRoute
'/settings/cloud': typeof SettingsCloudRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -114,7 +107,6 @@ export interface FileRoutesByTo {
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/settings/archived': typeof SettingsArchivedRoute
'/settings/cloud': typeof SettingsCloudRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -131,7 +123,6 @@ export interface FileRoutesById {
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
'/settings/archived': typeof SettingsArchivedRoute
'/settings/cloud': typeof SettingsCloudRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -149,7 +140,6 @@ export interface FileRouteTypes {
| '/pair'
| '/settings'
| '/settings/archived'
| '/settings/cloud'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -163,7 +153,6 @@ export interface FileRouteTypes {
| '/pair'
| '/settings'
| '/settings/archived'
| '/settings/cloud'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -179,7 +168,6 @@ export interface FileRouteTypes {
| '/pair'
| '/settings'
| '/settings/archived'
| '/settings/cloud'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -269,13 +257,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsConnectionsRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/cloud': {
id: '/settings/cloud'
path: '/cloud'
fullPath: '/settings/cloud'
preLoaderRoute: typeof SettingsCloudRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/archived': {
id: '/settings/archived'
path: '/archived'
@@ -316,7 +297,6 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
interface SettingsRouteChildren {
SettingsArchivedRoute: typeof SettingsArchivedRoute
SettingsCloudRoute: typeof SettingsCloudRoute
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
@@ -327,7 +307,6 @@ interface SettingsRouteChildren {
const SettingsRouteChildren: SettingsRouteChildren = {
SettingsArchivedRoute: SettingsArchivedRoute,
SettingsCloudRoute: SettingsCloudRoute,
SettingsConnectionsRoute: SettingsConnectionsRoute,
SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
+4 -7
View File
@@ -1,4 +1,4 @@
import { createFileRoute } from "@tanstack/react-router";
import { createFileRoute, Link } from "@tanstack/react-router";
import { LinkIcon, PlusIcon } from "lucide-react";
import { NoActiveThreadState } from "../components/NoActiveThreadState";
@@ -52,16 +52,13 @@ function HostedStaticOnboardingState() {
</EmptyTitle>
<EmptyDescription className="mt-2 text-sm leading-relaxed text-muted-foreground/78">
{cloudEnabled
? "Sign in to T3 Cloud to connect a linked environment through its managed tunnel, or add a reachable backend manually."
? "Sign in to T3 Connect to connect a linked environment through its managed tunnel, or add a reachable backend manually."
: "Add a reachable backend manually to start working from this browser."}
</EmptyDescription>
<div className="mt-6 flex justify-center">
<Button
render={<a href={cloudEnabled ? "/settings/cloud" : "/settings/connections"} />}
size="sm"
>
<Button render={<Link to="/settings/connections" />} size="sm">
<PlusIcon className="size-4" />
{cloudEnabled ? "Open T3 Cloud" : "Add environment"}
{cloudEnabled ? "Open Connections" : "Add environment"}
</Button>
</div>
</EmptyHeader>
-13
View File
@@ -1,13 +0,0 @@
import { createFileRoute, redirect } from "@tanstack/react-router";
import { CloudSettingsPanel } from "../components/settings/CloudSettings";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
export const Route = createFileRoute("/settings/cloud")({
beforeLoad: () => {
if (!hasCloudPublicConfig()) {
throw redirect({ to: "/settings/general", replace: true });
}
},
component: CloudSettingsPanel,
});
+6
View File
@@ -45,6 +45,12 @@ export const PROVIDER_OPTIONS: Array<{
available: true,
pickerSidebarBadge: "new",
},
{
value: ProviderDriverKind.make("grok"),
label: "Grok",
available: true,
pickerSidebarBadge: "new",
},
];
export interface WorkLogEntry {
+1 -1
View File
@@ -2,7 +2,7 @@
- [Getting started](./getting-started/quick-start.md)
- [Architecture](./architecture/overview.md)
- [Cloud](./cloud/t3-cloud-clerk.md)
- [T3 Connect](./cloud/t3-connect-clerk.md)
- [Integrations](./integrations/source-control-providers.md)
- [Mobile](./mobile/app.md)
- [Operations](./operations/ci.md)
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>T3 Code Cloud Architecture</title>
<title>T3 Connect Architecture</title>
<style>
:root {
color-scheme: light;
@@ -253,10 +253,10 @@
<main class="shell">
<header>
<div class="eyebrow">Implemented architecture</div>
<h1>T3 Code Cloud Control Plane and Managed Endpoint Flow</h1>
<h1>T3 Connect Control Plane and Managed Endpoint Flow</h1>
<p class="lede">
T3 Cloud links a locally authorized T3 environment to a signed-in cloud user, provisions a
managed HTTPS/WSS endpoint for that environment, and brokers proof-bound remote
T3 Connect links a locally authorized T3 environment to a signed-in cloud user, provisions
a managed HTTPS/WSS endpoint for that environment, and brokers proof-bound remote
connections. The local environment remains the authority that issues environment access
credentials. The hosted relay stores links, reconciles managed endpoint resources,
validates signed proofs, and delivers agent-activity notifications.
@@ -279,7 +279,7 @@
following:
</p>
<ul>
<li>a Clerk-authenticated T3 Cloud user;</li>
<li>a Clerk-authenticated T3 Connect user;</li>
<li>an active relay link for that user and environment;</li>
<li>a DPoP proof key held by the remote client;</li>
<li>a relay-signed mint request accepted by the linked local environment; and</li>
@@ -547,7 +547,7 @@ sequenceDiagram
participant CF as Cloudflare APIs
participant RC as Local relay client
U->>C: Enable T3 Cloud for a locally paired environment
U->>C: Enable T3 Connect for a locally paired environment
C->>E: Check relay client availability
alt relay client is missing
C->>U: Prompt before download and install
@@ -557,7 +557,7 @@ sequenceDiagram
end
C->>R: POST /v1/client/environment-link-challenges (Clerk bearer)
R-->>C: Short-lived challenge
C->>E: POST /api/cloud/link-proof (local relay:write bearer)
C->>E: POST /api/connect/link-proof (local relay:write bearer)
E->>E: Authenticate, reject forwarded authority, get or create key pair, validate loopback origin
E-->>C: Environment-signed link proof
C->>R: POST /v1/client/environment-links (Clerk bearer + proof)
@@ -565,7 +565,7 @@ sequenceDiagram
R->>CF: Reconcile tunnel, ingress, and CNAME
R->>R: Upsert user/environment link and issue environment bearer
R-->>C: Managed endpoint, relay config, and connector token
C->>E: POST /api/cloud/relay-config (local relay:write bearer)
C->>E: POST /api/connect/relay-config (local relay:write bearer)
E->>RC: Start relay client with TUNNEL_TOKEN
</pre>
<div class="callout">
@@ -585,13 +585,13 @@ sequenceDiagram
<pre class="diagram mermaid">
sequenceDiagram
participant U as Operator
participant CLI as t3 cloud CLI
participant CLI as t3 connect CLI
participant Clerk as Clerk OAuth
participant S as Environment server on next start
participant R as Relay Worker
participant RC as Local relay client
U->>CLI: t3 cloud link
U->>CLI: t3 connect link
CLI->>CLI: Resolve relay client
alt relay client is missing
CLI->>U: Confirm managed relay-client install
@@ -607,9 +607,9 @@ sequenceDiagram
S->>RC: Start relay client
</pre>
<p>
<code>t3 cloud login</code> stores authorization without enabling exposure.
<code>t3 cloud unlink</code> disables exposure while retaining authorization.
<code>t3 cloud logout</code> also removes the stored CLI authorization.
<code>t3 connect login</code> stores authorization without enabling exposure.
<code>t3 connect unlink</code> disables exposure while retaining authorization.
<code>t3 connect logout</code> also removes the stored CLI authorization.
</p>
</article>
@@ -626,7 +626,7 @@ sequenceDiagram
C->>R: POST /v1/client/dpop-token (Clerk JWT + DPoP proof)
R-->>C: Relay DPoP access token
C->>R: POST /v1/environments/:id/connect (relay DPoP)
R->>E: POST /api/t3-cloud/mint-credential (relay-signed proof)
R->>E: POST /api/t3-connect/mint-credential (relay-signed proof)
E->>E: Verify relay signer, linked user, scope, lifetime, cnf, and replay guards
E-->>R: Bootstrap credential + environment-signed proof
R->>R: Verify environment signature, nonce, endpoint, and DPoP binding
@@ -941,37 +941,37 @@ sequenceDiagram
</thead>
<tbody>
<tr>
<td><code>POST /api/cloud/link-proof</code></td>
<td><code>POST /api/connect/link-proof</code></td>
<td>Local environment token with <code>relay:write</code></td>
<td>Validate local origin and sign an environment link proof.</td>
</tr>
<tr>
<td><code>POST /api/cloud/relay-config</code></td>
<td><code>POST /api/connect/relay-config</code></td>
<td>Local environment token with <code>relay:write</code></td>
<td>Persist linked relay configuration and start the relay client.</td>
</tr>
<tr>
<td><code>GET /api/cloud/link-state</code></td>
<td><code>GET /api/connect/link-state</code></td>
<td>Local environment token with <code>relay:read</code></td>
<td>Read the environment's current T3 Cloud link state.</td>
<td>Read the environment's current T3 Connect link state.</td>
</tr>
<tr>
<td><code>POST /api/cloud/preferences</code></td>
<td><code>POST /api/connect/preferences</code></td>
<td>Local environment token with <code>relay:write</code></td>
<td>Enable or disable agent-activity publication.</td>
</tr>
<tr>
<td><code>POST /api/cloud/unlink</code></td>
<td><code>POST /api/connect/unlink</code></td>
<td>Local environment token with <code>relay:write</code></td>
<td>Stop the relay client and clear local T3 Cloud configuration.</td>
<td>Stop the relay client and clear local T3 Connect configuration.</td>
</tr>
<tr>
<td><code>POST /api/t3-cloud/health</code></td>
<td><code>POST /api/t3-connect/health</code></td>
<td>Relay-signed proof</td>
<td>Return a signed environment health response.</td>
</tr>
<tr>
<td><code>POST /api/t3-cloud/mint-credential</code></td>
<td><code>POST /api/t3-connect/mint-credential</code></td>
<td>Relay-signed proof</td>
<td>Mint a DPoP-bound one-time bootstrap credential for a remote client.</td>
</tr>
@@ -1,12 +1,12 @@
# T3 Cloud Clerk Setup
# T3 Connect Clerk Setup
T3 Cloud uses one Clerk application for web, desktop, and mobile authentication. The relay accepts
T3 Connect uses one Clerk application for web, desktop, and mobile authentication. The relay accepts
Clerk JWTs only when they are generated from the `t3-relay` template with the shared
`t3-code-relay` audience.
## Application Keys
T3 Cloud is disabled in a fresh clone. To enable it for source builds, add a repository-root `.env`
T3 Connect is disabled in a fresh clone. To enable it for source builds, add a repository-root `.env`
or `.env.local` file:
```dotenv
@@ -36,7 +36,7 @@ production builds only need the Clerk publishable key, JWT template name, and re
environment.
When any client-facing public value is absent, cloud UI is omitted. When the CLI public values are
absent, the `t3 cloud` CLI command group is omitted. The bundled server still accepts runtime
absent, the `t3 connect` CLI command group is omitted. The bundled server still accepts runtime
overrides for self-hosted or operator-managed
deployments.
@@ -56,7 +56,7 @@ personal developer stage.
## Headless CLI OAuth Application
The `t3 cloud` commands authorize a headless environment with a separate Clerk OAuth application.
The `t3 connect` commands authorize a headless environment with a separate Clerk OAuth application.
This uses an OAuth public client with PKCE, so the CLI stores no client secret.
In **Clerk Dashboard > OAuth applications**:
@@ -75,25 +75,25 @@ handshake; it only validates the issued Clerk bearer token when the CLI manages
The CLI supports these headless operations:
```sh
t3 cloud login
t3 cloud link
t3 cloud status
t3 cloud unlink
t3 cloud logout
t3 connect login
t3 connect link
t3 connect status
t3 connect unlink
t3 connect logout
t3 serve
```
`t3 cloud login` opens the Clerk authorization flow and stores the CLI credential without enabling
cloud exposure. `t3 cloud link` installs the pinned managed `cloudflared` binary when needed,
`t3 connect login` opens the Clerk authorization flow and stores the CLI credential without enabling
cloud exposure. `t3 connect link` installs the pinned managed `cloudflared` binary when needed,
authorizes when needed, and records durable intent to expose the environment. It works without a
running T3 server. The next `t3 serve` or `t3 start` reconciles the relay link and launches the
managed tunnel. `t3 cloud unlink` records disabled intent immediately, stops a reachable running
managed tunnel. `t3 connect unlink` records disabled intent immediately, stops a reachable running
connector, and attempts to revoke the relay-side environment record. It retains the stored CLI
authorization so `t3 cloud link` can re-enable exposure without another browser flow. `t3 cloud
authorization so `t3 connect link` can re-enable exposure without another browser flow. `t3 connect
logout` performs the same cleanup and removes the stored CLI authorization.
The current OAuth callback listener binds to loopback port `34338`. When running the CLI over SSH,
forward that port before running `t3 cloud login` or `t3 cloud link`:
forward that port before running `t3 connect login` or `t3 connect link`:
```sh
ssh -L 34338:127.0.0.1:34338 <host>
@@ -145,9 +145,9 @@ For a private beta where people should request access, use **Clerk Dashboard > W
1. Toggle on **Enable waitlist** and save.
2. Review requests on the same page and select **Invite** or **Deny**.
Signed-out web and desktop users see Clerk's waitlist enrollment as the T3 Cloud page content,
while approved signed-in users see cloud settings. The browser app also uses `/settings/cloud` as
its Clerk waitlist URL.
Approved signed-in users manage T3 Connect under **Connections**. The web and desktop sidebars do
not expose a dedicated account or waitlist control. Signed-out users reach Clerk's waitlist and
sign-in flow contextually from the T3 Connect controls on the Connections page.
On mobile, signed-out users open **Settings > T3 Account** to reach `/settings/waitlist` within the
Settings form sheet. It submits enrollment through Clerk's `useWaitlist()` flow because the prebuilt
+2 -2
View File
@@ -10,7 +10,7 @@ This document covers the unified release workflow for stable and nightly desktop
- scheduled nightly check every three hours
- manual `workflow_dispatch` for either channel
- Runs quality gates first: lint, typecheck, test.
- Reads the shared production T3 Cloud relay URL and Clerk client configuration before packaging clients.
- Reads the shared production T3 Connect relay URL and Clerk client configuration before packaging clients.
- Builds four artifacts in parallel for both channels:
- macOS `arm64` DMG
- macOS `x64` DMG
@@ -30,7 +30,7 @@ This document covers the unified release workflow for stable and nightly desktop
- nightly releases are aliased to the `nightly` hosted app channel
- Signing is optional and auto-detected per platform from secrets.
## T3 Cloud relay deployment
## T3 Connect relay deployment
The relay is a shared control plane versioned separately from client releases. Stable and nightly
client builds must point at the same relay so users see the same linked environments when switching
+6 -6
View File
@@ -1,15 +1,15 @@
# T3 Code Cloud Relay
# T3 Connect Relay
> [!WARNING]
> T3 Code Cloud is currently in private beta. Join the waitlist in the app under Settings > T3 Cloud.
> T3 Connect is currently in private beta. Join the waitlist in the app under Settings > T3 Connect.
The relay is the hosted control plane for T3 Code Cloud. It helps clients discover and connect to
The relay is the hosted control plane for T3 Connect. It helps clients discover and connect to
remote environments, manages the cloud-side records needed for those connections, and delivers
optional mobile notifications and Live Activities.
The relay is intentionally not in the hot path for normal T3 Code traffic. After a client connects,
regular API and WebSocket traffic goes directly between that client and the selected environment.
See the [cloud architecture overview](../../docs/t3-code-cloud-auth-flow.html) for the larger system
See the [T3 Connect architecture overview](../../docs/cloud/t3-code-connect-auth-flow.html) for the larger system
design.
## Responsibilities
@@ -159,8 +159,8 @@ and hosted web builds.
See:
- [T3 Cloud Clerk Setup](../../docs/t3-cloud-clerk.md) for Clerk keys, JWT templates, and waitlist
- [T3 Connect Clerk Setup](../../docs/cloud/t3-connect-clerk.md) for Clerk keys, JWT templates, and waitlist
setup.
- [Relay Observability](../../docs/relay-observability.md) for deployment tracing and diagnostics.
- [Cloud Architecture Overview](../../docs/t3-code-cloud-auth-flow.html) for the full link,
- [T3 Connect Architecture Overview](../../docs/cloud/t3-code-connect-auth-flow.html) for the full link,
connect, endpoint, and notification flows.
@@ -300,7 +300,7 @@ describe("EnvironmentConnector", () => {
environmentId: "env-connector-test",
});
expect(seenUrls).toEqual(["https://env.example.test/api/t3-cloud/health"]);
expect(seenUrls).toEqual(["https://env.example.test/api/t3-connect/health"]);
expect(seenProofs[0]).toMatchObject({
iss: "https://relay.example.test",
aud: "t3-env:env-connector-test",
@@ -663,7 +663,7 @@ describe("EnvironmentConnector", () => {
deviceId: "device-123",
});
expect(seenUrls).toEqual(["https://env.example.test/api/t3-cloud/mint-credential"]);
expect(seenUrls).toEqual(["https://env.example.test/api/t3-connect/mint-credential"]);
expect(seenProofs[0]).toMatchObject({
iss: "https://relay.example.test",
aud: "t3-env:env-connector-test",
@@ -458,7 +458,7 @@ const make = Effect.gen(function* () {
);
const checkedAt = DateTime.formatIso(now);
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
const responseOption = yield* environmentClient.cloud.health({ payload: { proof } }).pipe(
const responseOption = yield* environmentClient.connect.health({ payload: { proof } }).pipe(
withoutRedirects,
Effect.match({
onFailure: (cause) => ({ _tag: "Failure" as const, cause }),
@@ -591,30 +591,32 @@ const make = Effect.gen(function* () {
),
);
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
const decoded = yield* environmentClient.cloud.t3MintCredential({ payload: { proof } }).pipe(
withoutRedirects,
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "connect",
cause,
const decoded = yield* environmentClient.connect
.t3MintCredential({ payload: { proof } })
.pipe(
withoutRedirects,
Effect.mapError(
(cause) =>
new EnvironmentMintRequestFailed({
environmentId: input.environmentId,
operation: "connect",
cause,
}),
),
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new EnvironmentMintRequestTimedOut({
environmentId: input.environmentId,
timeoutMs: ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS,
}),
),
onSome: Effect.succeed,
}),
),
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new EnvironmentMintRequestTimedOut({
environmentId: input.environmentId,
timeoutMs: ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS,
}),
),
onSome: Effect.succeed,
}),
),
);
),
);
const verified = yield* verifyEnvironmentResponse({
response: decoded,
environmentId: input.environmentId,
@@ -53,7 +53,7 @@ export function createManagedRelaySession(input: {
try: input.readClerkToken,
catch: (cause) =>
new ManagedRelaySessionError({
message: "Could not obtain the T3 Cloud session token.",
message: "Could not obtain the T3 Connect session token.",
cause,
}),
}),
@@ -76,7 +76,7 @@ function readSessionClerkToken(
? Effect.succeed(token)
: Effect.fail(
new ManagedRelaySessionError({
message: "The T3 Cloud session token is unavailable.",
message: "The T3 Connect session token is unavailable.",
}),
),
),
@@ -121,7 +121,7 @@ function requireClerkToken(
if (!session || session.accountId !== accountId) {
return Effect.fail(
new ManagedRelaySessionError({
message: "Sign in to T3 Cloud before loading relay data.",
message: "Sign in to T3 Connect before loading relay data.",
}),
);
}
@@ -190,7 +190,7 @@ export function readManagedRelaySnapshotState<A>(
let error: string | null = null;
if (result._tag === "Failure") {
const cause = Cause.squash(result.cause);
error = cause instanceof Error ? cause.message : "Could not load T3 Cloud data.";
error = cause instanceof Error ? cause.message : "Could not load T3 Connect data.";
}
return {
data: Option.getOrNull(AsyncResult.value(result)),
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.24",
"version": "0.0.27",
"private": true,
"files": [
"dist"
+10 -10
View File
@@ -439,9 +439,9 @@ export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestr
}).middleware(EnvironmentAuthenticatedAuth),
) {}
export class EnvironmentCloudHttpApi extends HttpApiGroup.make("cloud")
export class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
.add(
HttpApiEndpoint.post("linkProof", "/api/cloud/link-proof", {
HttpApiEndpoint.post("linkProof", "/api/connect/link-proof", {
headers: OptionalBearerHeaders,
payload: RelayLinkProofRequest,
success: RelayEnvironmentLinkProof,
@@ -449,7 +449,7 @@ export class EnvironmentCloudHttpApi extends HttpApiGroup.make("cloud")
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.post("relayConfig", "/api/cloud/relay-config", {
HttpApiEndpoint.post("relayConfig", "/api/connect/relay-config", {
headers: OptionalBearerHeaders,
payload: RelayEnvironmentConfigRequest,
success: EnvironmentCloudRelayConfigResult,
@@ -457,21 +457,21 @@ export class EnvironmentCloudHttpApi extends HttpApiGroup.make("cloud")
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.get("linkState", "/api/cloud/link-state", {
HttpApiEndpoint.get("linkState", "/api/connect/link-state", {
headers: OptionalBearerHeaders,
success: EnvironmentCloudLinkStateResult,
error: EnvironmentHttpCloudErrors,
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.post("unlink", "/api/cloud/unlink", {
HttpApiEndpoint.post("unlink", "/api/connect/unlink", {
headers: OptionalBearerHeaders,
success: EnvironmentCloudRelayConfigResult,
error: EnvironmentHttpCloudErrors,
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.post("preferences", "/api/cloud/preferences", {
HttpApiEndpoint.post("preferences", "/api/connect/preferences", {
headers: OptionalBearerHeaders,
payload: EnvironmentCloudPreferencesRequest,
success: EnvironmentCloudLinkStateResult,
@@ -479,21 +479,21 @@ export class EnvironmentCloudHttpApi extends HttpApiGroup.make("cloud")
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.post("health", "/api/t3-cloud/health", {
HttpApiEndpoint.post("health", "/api/t3-connect/health", {
payload: RelayCloudEnvironmentHealthRequest,
success: RelayEnvironmentHealthResponse,
error: EnvironmentHttpCloudErrors,
}),
)
.add(
HttpApiEndpoint.post("mintCredential", "/api/cloud/mint-credential", {
HttpApiEndpoint.post("mintCredential", "/api/connect/mint-credential", {
payload: RelayCloudMintCredentialRequest,
success: RelayEnvironmentMintResponse,
error: EnvironmentHttpCloudErrors,
}),
)
.add(
HttpApiEndpoint.post("t3MintCredential", "/api/t3-cloud/mint-credential", {
HttpApiEndpoint.post("t3MintCredential", "/api/t3-connect/mint-credential", {
payload: RelayCloudMintCredentialRequest,
success: RelayEnvironmentMintResponse,
error: EnvironmentHttpCloudErrors,
@@ -504,4 +504,4 @@ export class EnvironmentHttpApi extends HttpApi.make("environment")
.add(EnvironmentMetadataHttpApi)
.add(EnvironmentAuthHttpApi)
.add(EnvironmentOrchestrationHttpApi)
.add(EnvironmentCloudHttpApi) {}
.add(EnvironmentConnectHttpApi) {}
+3
View File
@@ -130,6 +130,7 @@ export type ModelCapabilities = typeof ModelCapabilities.Type;
const CODEX_DRIVER_KIND = ProviderDriverKind.make("codex");
const CLAUDE_DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
export const DEFAULT_MODEL = "gpt-5.4";
@@ -139,6 +140,7 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, strin
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
[CLAUDE_DRIVER_KIND]: "claude-sonnet-4-6",
[CURSOR_DRIVER_KIND]: "auto",
[GROK_DRIVER_KIND]: "grok-build",
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
};
@@ -201,5 +203,6 @@ export const PROVIDER_DISPLAY_NAMES: Partial<Record<ProviderDriverKind, string>>
[CODEX_DRIVER_KIND]: "Codex",
[CLAUDE_DRIVER_KIND]: "Claude",
[CURSOR_DRIVER_KIND]: "Cursor",
[GROK_DRIVER_KIND]: "Grok",
[OPENCODE_DRIVER_KIND]: "OpenCode",
};
+1 -1
View File
@@ -537,7 +537,7 @@ export class RelayEnvironmentPrincipal extends Context.Service<
const RelayClientBearerAuthorization = HttpApiSecurity.http({ scheme: "bearer" }).pipe(
HttpApiSecurity.annotate(
OpenApi.Description,
"Clerk session or OAuth bearer token for the signed-in T3 Cloud user.",
"Clerk session or OAuth bearer token for the signed-in T3 Connect user.",
),
);
+1
View File
@@ -165,6 +165,7 @@ export const ServerProvider = Schema.Struct({
badgeLabel: Schema.optional(TrimmedNonEmptyString),
continuation: Schema.optional(ServerProviderContinuation),
showInteractionModeToggle: Schema.optional(Schema.Boolean),
requiresNewThreadForModelChange: Schema.optional(Schema.Boolean),
enabled: Schema.Boolean,
installed: Schema.Boolean,
version: Schema.NullOr(TrimmedNonEmptyString),
+32
View File
@@ -281,6 +281,30 @@ export const CursorSettings = makeProviderSettingsSchema(
);
export type CursorSettings = typeof CursorSettings.Type;
export const GrokSettings = makeProviderSettingsSchema(
{
enabled: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(true)),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
binaryPath: makeBinaryPathSetting("grok").pipe(
Schema.annotateKey({
title: "Binary path",
description: "Path to the Grok CLI binary.",
providerSettingsForm: { placeholder: "grok", clearWhenEmpty: "omit" },
}),
),
customModels: Schema.Array(Schema.String).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
},
{
order: ["binaryPath"],
},
);
export type GrokSettings = typeof GrokSettings.Type;
export const OpenCodeSettings = makeProviderSettingsSchema(
{
enabled: Schema.Boolean.pipe(
@@ -369,6 +393,7 @@ export const ServerSettings = Schema.Struct({
codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
}).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
// New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values
@@ -437,6 +462,12 @@ const CursorSettingsPatch = Schema.Struct({
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
const GrokSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(TrimmedString),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
const OpenCodeSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(TrimmedString),
@@ -463,6 +494,7 @@ export const ServerSettingsPatch = Schema.Struct({
codex: Schema.optionalKey(CodexSettingsPatch),
claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
cursor: Schema.optionalKey(CursorSettingsPatch),
grok: Schema.optionalKey(GrokSettingsPatch),
opencode: Schema.optionalKey(OpenCodeSettingsPatch),
}),
),
+3
View File
@@ -94,6 +94,9 @@ describe("resolveModelSlugForProvider", () => {
expect(resolveModelSlugForProvider(ProviderDriverKind.make("ollama"), undefined)).toBe(
DEFAULT_MODEL,
);
expect(resolveModelSlugForProvider(ProviderDriverKind.make("grok"), undefined)).toBe(
"grok-build",
);
});
it("preserves normalized unknown models", () => {