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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 24 additions & 32 deletions .agents/skills/t3code-routine-update/SKILL.md

Large diffs are not rendered by default.

22 changes: 22 additions & 0 deletions apps/server/src/auth/EnvironmentAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
} from "@t3tools/shared/dpop";
import { expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import { onTestFinished, vi } from "vite-plus/test";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
Expand Down Expand Up @@ -294,6 +295,27 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
),
);

it.effect("authenticates requests without credentials through WebSocket setup", () => {
vi.stubEnv("T3CODE_UNSAFE_NO_AUTH", "1");
onTestFinished(() => {
vi.unstubAllEnvs();
});
return Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const request = { cookies: {}, headers: {} };
const session = yield* serverAuth.authenticateHttpRequest(request as never);
const ticket = yield* serverAuth.issueWebSocketTicket(session);
const websocketSession = yield* serverAuth.authenticateWebSocketUpgrade(
{ ...request, url: `/?wsTicket=${encodeURIComponent(ticket.ticket)}` } as never,
"rpc",
);

expect(session.subject).toBe("unsafe-no-auth");
expect(session.scopes).toEqual(AuthStandardClientScopes);
expect(websocketSession).toEqual(session);
}).pipe(Effect.provide(layerEnvironmentAuth()));
});

it.effect("prefers a bearer token over a stale legacy cookie", () =>
Effect.gen(function* () {
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
Expand Down
36 changes: 31 additions & 5 deletions apps/server/src/auth/EnvironmentAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
type AuthMcpClientAccess,
type AuthPairingLink,
type AuthPairingCredentialResult,
type AuthSessionId,
AuthSessionId,
type AuthSessionState,
authScopeResponse,
type ServerAuthDescriptor,
Expand Down Expand Up @@ -48,6 +48,17 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts";
const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";

const unsafeSession: AuthenticatedSession & { readonly audience?: undefined } = {
sessionId: AuthSessionId.make("unsafe-no-auth"),
subject: "unsafe-no-auth",
method: "browser-session-cookie",
scopes: AuthStandardClientScopes,
};

/** The no-auth session has no stored row, so nothing can revoke it. */
export const isUnsafeNoAuthSession = (sessionId: AuthSessionId) =>
sessionId === unsafeSession.sessionId;

export interface IssuedPairingLink {
readonly id: string;
readonly credential: string;
Expand Down Expand Up @@ -704,6 +715,7 @@ export const make = Effect.gen(function* () {
const descriptor = yield* policy.getDescriptor();
const config = yield* ServerConfig.ServerConfig;
const devAuth = resolveReusableDevAuth(config);
const unsafeNoAuth = process.env.T3CODE_UNSAFE_NO_AUTH === "1";

const authenticateToken = (
token: string,
Expand Down Expand Up @@ -762,7 +774,9 @@ export const make = Effect.gen(function* () {
const dpopToken = parseDpopToken(request);
const credential = resolveRequestCredential(request);
if (!credential?.token) {
return Effect.fail(new ServerAuthMissingCredentialError({}));
return unsafeNoAuth
? Effect.succeed(unsafeSession)
: Effect.fail(new ServerAuthMissingCredentialError({}));
}
if (
isBrowserCookieCredential(credential.source) &&
Expand Down Expand Up @@ -805,6 +819,10 @@ export const make = Effect.gen(function* () {
}
return Effect.succeed(session);
}),
Effect.catchIf(
(error) => unsafeNoAuth && isServerAuthCredentialError(error),
() => Effect.succeed(unsafeSession),
),
);
};

Expand Down Expand Up @@ -1226,9 +1244,17 @@ export const make = Effect.gen(function* () {
if (Option.isSome(requestUrl)) {
const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
if (websocketTicket && websocketTicket.trim().length > 0) {
const session = yield* sessions
.verifyWebSocketToken(websocketTicket)
.pipe(mapSessionVerificationErrors, Effect.flatMap(rejectMcpClientAudience));
const session = yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
Effect.catchIf(
(error) =>
unsafeNoAuth &&
error._tag === "UnknownWebSocketSessionError" &&
error.sessionId === unsafeSession.sessionId,
() => Effect.succeed(unsafeSession),
),
mapSessionVerificationErrors,
Effect.flatMap(rejectMcpClientAudience),
);
if (session.audience !== undefined && session.audience !== use) {
return yield* new ServerAuthInvalidCredentialError({
diagnostic: `WebSocket ticket was issued for the ${session.audience} route.`,
Expand Down
11 changes: 11 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,17 @@ describe("ClaudeAdapterV2 runtime query policy", () => {
assert.isUndefined(options.extraArgs?.["dangerously-skip-permissions"]);
});

it("loads a session-local plugin configured by the hosting T3 instance", () => {
const options = ClaudeAdapterV2.makeClaudeQueryOptions({
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
nativeThreadId: "native-thread-plugin",
resume: false,
cwd: "/workspace",
environment: { T3CODE_CLAUDE_PLUGIN_ROOT: " /opt/whiteboard " },
});
assert.deepEqual(options.plugins, [{ type: "local", path: "/opt/whiteboard" }]);
});

it("gives delegated children Claude's subagent prompt cache TTL", () => {
const lineage = (relationshipToParent: "fork" | "subagent" | null) => ({
lineage: {
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1508,6 +1508,7 @@ export function makeClaudeQueryOptions(input: {
: typeof input.sdkSettings === "object" && input.sdkSettings !== null
? ({ ...input.sdkSettings, ...selectionSettings } as ClaudeSdkSettings)
: selectionSettings;
const pluginRoot = input.environment?.T3CODE_CLAUDE_PLUGIN_ROOT?.trim();
const compactQuerySettings =
input.settings?.autoCompactWindow === undefined || input.settings.autoCompactWindow.length === 0
? querySettings
Expand Down Expand Up @@ -1569,6 +1570,7 @@ export function makeClaudeQueryOptions(input: {
: {}),
...(input.environment === undefined ? {} : { env: input.environment }),
...(input.mcpServers === undefined ? {} : { mcpServers: input.mcpServers }),
...(pluginRoot ? { plugins: [{ type: "local" as const, path: pluginRoot }] } : {}),
systemPrompt: {
type: "preset" as const,
preset: "claude_code" as const,
Expand Down
10 changes: 9 additions & 1 deletion apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,11 @@ import {
shouldPersistProviderEvent,
} from "../../provider/EventNdjsonLogger.ts";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import { codexAppServerArgs, resolveCodexLaunchArgs } from "../../provider/codexLaunchArgs.ts";
import {
codexAppServerArgs,
resolveCodexLaunchArgs,
resolveCodexSkillRoot,
} from "../../provider/codexLaunchArgs.ts";
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
Expand Down Expand Up @@ -1752,6 +1756,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
}),
);
yield* client.notify("initialized", undefined);
const skillRoot = resolveCodexSkillRoot(clientEnvironment);
if (skillRoot) {
yield* client.request("skills/extraRoots/set", { extraRoots: [skillRoot] });
}
yield* Ref.set(initialized, true);
}),
);
Expand Down
10 changes: 9 additions & 1 deletion apps/server/src/provider/CodexProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ import {
formatCodexModelName,
} from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts";
import {
codexAppServerArgs,
resolveCodexLaunchArgs,
resolveCodexSkillRoot,
} from "./codexLaunchArgs.ts";
import {
buildServerProvider,
COMPACT_SLASH_COMMAND,
Expand Down Expand Up @@ -505,6 +509,10 @@ export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(fu
);
const initialize = yield* client.request("initialize", buildCodexInitializeParams());
yield* client.notify("initialized", undefined);
const skillRoot = resolveCodexSkillRoot(input.environment);
if (skillRoot) {
yield* client.request("skills/extraRoots/set", { extraRoots: [skillRoot] });
}
return { client, initialize };
});

Expand Down
19 changes: 18 additions & 1 deletion apps/server/src/provider/codexLaunchArgs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,24 @@ import * as NodeAssert from "node:assert/strict";

import { describe, it } from "vite-plus/test";

import { codexAppServerArgs, codexExecLaunchArgs } from "./codexLaunchArgs.ts";
import {
codexAppServerArgs,
codexExecLaunchArgs,
resolveCodexSkillRoot,
} from "./codexLaunchArgs.ts";

describe("resolveCodexSkillRoot", () => {
it("returns the configured skill root without surrounding whitespace", () => {
NodeAssert.equal(
resolveCodexSkillRoot({ T3CODE_CODEX_SKILL_ROOT: " /opt/whiteboard/skills " }),
"/opt/whiteboard/skills",
);
});

it("ignores an empty skill root", () => {
NodeAssert.equal(resolveCodexSkillRoot({ T3CODE_CODEX_SKILL_ROOT: " " }), undefined);
});
});

describe("codexAppServerArgs", () => {
it("preserves escaped TOML quotes in config values", () => {
Expand Down
4 changes: 4 additions & 0 deletions apps/server/src/provider/codexLaunchArgs.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { tokenizeCliArgs } from "@t3tools/shared/cliArgs";

const T3CODE_CODEX_LAUNCH_ARGS_ENV = "T3CODE_CODEX_LAUNCH_ARGS";
const T3CODE_CODEX_SKILL_ROOT_ENV = "T3CODE_CODEX_SKILL_ROOT";

export const resolveCodexLaunchArgs = (
launchArgs?: string,
environment: NodeJS.ProcessEnv = process.env,
) => environment[T3CODE_CODEX_LAUNCH_ARGS_ENV]?.trim() || launchArgs?.trim() || "";

export const resolveCodexSkillRoot = (environment: NodeJS.ProcessEnv = process.env) =>
environment[T3CODE_CODEX_SKILL_ROOT_ENV]?.trim() || undefined;

const codexLaunchArgv = (launchArgs?: string): ReadonlyArray<string> => tokenizeCliArgs(launchArgs);

export const codexAppServerArgs = (launchArgs?: string) => [
Expand Down
22 changes: 12 additions & 10 deletions apps/server/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3364,16 +3364,18 @@ export const layer = Layer.unwrap(
return yield* Effect.acquireUseRelease(
sessions.markConnected(session.sessionId),
() =>
Effect.raceFirst(
rpcWebSocketHttpEffect,
sessions.awaitInvalidation(session.sessionId).pipe(
Effect.as(HttpServerResponse.empty()),
Effect.catchTags({
SessionCredentialVerificationError: (error) =>
failEnvironmentInternal("internal_error", error),
}),
),
),
EnvironmentAuth.isUnsafeNoAuthSession(session.sessionId)
? rpcWebSocketHttpEffect
: Effect.raceFirst(
rpcWebSocketHttpEffect,
sessions.awaitInvalidation(session.sessionId).pipe(
Effect.as(HttpServerResponse.empty()),
Effect.catchTags({
SessionCredentialVerificationError: (error) =>
failEnvironmentInternal("internal_error", error),
}),
),
),
() => sessions.markDisconnected(session.sessionId),
);
}).pipe(
Expand Down
4 changes: 2 additions & 2 deletions apps/web/public/manifest.webmanifest
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
"theme_color": "#161616",
"icons": [
{
"src": "/favicon-32x32.png",
"src": "favicon-32x32.png",
"sizes": "32x32",
"type": "image/png"
},
{
"src": "/apple-touch-icon.png",
"src": "apple-touch-icon.png",
"sizes": "180x180",
"type": "image/png"
}
Expand Down
28 changes: 24 additions & 4 deletions apps/web/src/components/AppSidebarLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ import { useLocation, useRouter, type AnyRouter } from "@tanstack/react-router";
import { moveWorkspaceFocus, workspaceAreaProps } from "../lib/workspaceFocus";
import { isCommandPaletteOpen } from "../commandPaletteBus";
import { isElectron } from "../env";
import { isWhiteboardBuild } from "../fork/whiteboard/build";
import {
useWhiteboardBoardHidden,
useWhiteboardSidebarStartState,
WHITEBOARD_BOARD_BUTTON_TITLEBAR_STYLE,
WhiteboardBoardButton,
} from "../fork/whiteboard/WhiteboardSidebar";
import {
releaseThreadUndoShortcut,
threadUndoClaimsShortcut,
Expand Down Expand Up @@ -311,11 +318,18 @@ function registerAppShellCommands(router: AnyRouter, shellElement: Element): ()
};
}

function SidebarControl() {
function SidebarControl({
boardHidden,
sidebarFits,
}: {
boardHidden: boolean | null;
sidebarFits: boolean;
}) {
const router = useRouter();
const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const { toggleSidebar, isMobile, mobileSheetMounted } = useSidebar();
const { setOpen, toggleSidebar, isMobile, mobileSheetMounted } = useSidebar();
useWhiteboardSidebarStartState(boardHidden, sidebarFits, setOpen);
const isSidebarVisible = useSidebarVisibility();
const environmentIdentificationMode = useEnvironmentIdentificationMode();
const stageBackdropVariant = useSidebarStageBackdropVariant(environmentIdentificationMode);
Expand Down Expand Up @@ -379,6 +393,7 @@ function SidebarControl() {
)}
data-sidebar-control=""
>
{boardHidden && <WhiteboardBoardButton />}
<Tooltip>
<TooltipTrigger
render={
Expand Down Expand Up @@ -413,11 +428,13 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
const boardHidden = useWhiteboardBoardHidden();
// A clamped drag may not change width, so viewport changes need a separate subscription.
const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
const [brandWidth, setBrandWidth] = useState(0);
const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
const sidebarFits = viewportWidth >= sidebarWidth + THREAD_MAIN_CONTENT_MIN_WIDTH;
const resetSidebarWidth = () => {
try {
removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
Expand All @@ -439,14 +456,17 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
"--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
"--panel-animation-duration": `${panelAnimationDurationMs}ms`,
...windowControlsInsetStyle,
...(boardHidden ? WHITEBOARD_BOARD_BUTTON_TITLEBAR_STYLE : {}),
} as CSSProperties;

return (
<PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
<SidebarProvider
className="h-dvh! min-h-0!"
data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
defaultOpen
// The whiteboard build starts open only when standalone and wide enough; inside the
// board's iframe the start state comes from its layout report (useWhiteboardSidebarStartState).
defaultOpen={isWhiteboardBuild ? window.self === window.top && sidebarFits : true}
style={sidebarProviderStyle}
>
<SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
Expand All @@ -473,7 +493,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
</Sidebar>
{children}
<BackgroundThreadAnnouncer />
<SidebarControl />
<SidebarControl boardHidden={boardHidden} sidebarFits={sidebarFits} />
</SidebarProvider>
</PanelAnimationSuppressionProvider>
);
Expand Down
Loading
Loading