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
40 changes: 40 additions & 0 deletions apps/server/src/orchestration/decider.threadMoves.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
MessageId,
ProjectId,
ProviderInstanceId,
RELAY_DEVICE_SESSION_SUBJECT,
SideTurnId,
ThreadId,
ThreadMoveBatchId,
Expand All @@ -17,6 +18,7 @@ import {
ThreadParticipantId,
TurnId,
RoomAgentRequestId,
type AuthClientMetadata,
type ModelSelection,
type OrchestrationCommand,
type OrchestrationEvent,
Expand All @@ -35,6 +37,7 @@ import { describe, expect, it } from "vite-plus/test";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
import { isLinkFenced } from "./linkFence.ts";
import { messageSentFromSession } from "./messageSentFrom.ts";
import { threadMoveGuardRefusal, threadMoveRefusals } from "./threadMoveDecisions.ts";

const now = "2026-10-22T10:00:00.000Z";
Expand Down Expand Up @@ -1636,6 +1639,43 @@ describe("what a moved thread is trusted with (Part 3e, security changes)", () =
expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBeUndefined();
});

it("a browser paired through the relay lifts the fence; a linked computer, a CLI token or a script can't", async () => {
const signedIn = (
subject: string,
role: "owner" | "client" | "peer",
client: AuthClientMetadata,
) => messageSentFromSession({ subject, role, client }, "elsewhere");
const relayBrowser = signedIn(RELAY_DEVICE_SESSION_SUBJECT, "client", {
label: "Chrome on macOS",
deviceType: "unknown",
os: "macOS",
});
expect(relayBrowser).toEqual({
kind: "computer",
name: "Chrome on macOS",
os: "macOS",
place: "elsewhere",
});
const notAPerson = [
// A computer link through the relay: its pairing said "computer".
signedIn(RELAY_DEVICE_SESSION_SUBJECT, "peer", { deviceType: "desktop" }),
// `threadlines auth session issue`, an owner token for a script or an agent.
signedIn("cli-issued-session", "owner", { label: "deploy bot", deviceType: "bot" }),
// A paired sign-in from curl, and one that sent no user agent at all.
signedIn("one-time-token", "client", { deviceType: "bot", userAgent: "curl/8.7.1" }),
signedIn("one-time-token", "owner", { deviceType: "unknown" }),
];
expect(notAPerson).toEqual([undefined, undefined, undefined, undefined]);

const fenced = await withSession(await importedEmpty(), "ready");
for (const sentFrom of notAPerson) {
const { model } = await apply(fenced, userTurn(sentFrom ? { sentFrom } : {}));
expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBe(true);
}
const { model } = await apply(fenced, userTurn({ sentFrom: relayBrowser }));
expect(threadOf(model, ARRIVED).movedFrom?.fenced).toBeUndefined();
});

it("command output sent once the agent is idle leaves the fence up", async () => {
let model = await withSession(await importedEmpty(), "ready");
model = await project(model, "thread.command-run-started", {
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/orchestration/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
import { ServerAuth } from "../auth/Services/ServerAuth.ts";
import { normalizeDispatchCommand, toDispatchCommandError } from "./Normalizer.ts";
import {
messageSentFromClient,
messageSentFromSession,
sessionDevicePlace,
withMessageSentFrom,
writesUserMessage,
Expand Down Expand Up @@ -88,7 +88,7 @@ export const orchestrationDispatchRouteLayer = HttpRouter.add(
const normalizedCommand = writesUserMessage(normalized)
? withMessageSentFrom(
normalized,
messageSentFromClient(session.client, sessionDevicePlace(session)),
messageSentFromSession(session, sessionDevicePlace(session)),
)
: normalized;
// No ThreadBootstrap here: the app's first sends go over the WebSocket, and
Expand Down
76 changes: 48 additions & 28 deletions apps/server/src/orchestration/messageSentFrom.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import {
type AuthClientMetadata,
type AuthSessionRole,
type MessageDeviceKind,
type MessageId,
type MessageSentFrom,
type OrchestrationCommand,
Expand Down Expand Up @@ -41,27 +43,56 @@ export function sessionDevicePlace(
return "elsewhere";
}

/** A signed-in session, as far as the device it was issued to goes. */
export interface DeviceSession {
readonly subject: string;
readonly role: AuthSessionRole;
readonly client: AuthClientMetadata;
}

/**
* The kind of device a session was issued to, as MessageSentFrom.kind says
* it: a person's computer, phone or tablet. Undefined for a session that is
* no person's device the server can name: a linked computer's server
* (`peer`), a token the CLI issued or a sign-in that looked like a script
* (`bot`), and one that said nothing about itself (`unknown`). A browser
* paired through the relay is the one `unknown` that is a computer: its own
* pairing request called it a browser rather than a phone or a tablet, which
* RelayHost records as an unknown device type, and only a relay pairing the
* user approved gets that subject.
*/
export function sessionDeviceKind(session: DeviceSession): MessageDeviceKind | undefined {
if (session.role === "peer") return undefined;
switch (session.client.deviceType) {
case "desktop":
return "computer";
case "mobile":
return "phone";
case "tablet":
return "tablet";
case "unknown":
return session.subject === RELAY_DEVICE_SESSION_SUBJECT ? "computer" : undefined;
case "bot":
return undefined;
}
}

/**
* The device a client session was issued to, as a user message records it
* (see MessageSentFrom): by the name its user gave it, else what it called
* itself, and where it is (sessionDevicePlace). Undefined for a device of
* unknown kind.
* The device a session was issued to, as a user message records it (see
* MessageSentFrom): its kind (sessionDeviceKind), the name its user gave it,
* else what it called itself, and where it is (sessionDevicePlace). Undefined
* for a session that is no person's device: its messages can't lift a moved
* thread's fence (turnLiftsMoveFence).
*/
export function messageSentFromClient(
client: AuthClientMetadata,
export function messageSentFromSession(
session: DeviceSession,
place: MessageSentFrom["place"],
): MessageSentFrom | undefined {
const kind =
client.deviceType === "desktop"
? "computer"
: client.deviceType === "mobile"
? "phone"
: client.deviceType === "tablet"
? "tablet"
: undefined;
const kind = sessionDeviceKind(session);
if (kind === undefined) {
return undefined;
}
const { client } = session;
const name = client.name ?? client.label;
return {
kind,
Expand All @@ -73,20 +104,9 @@ export function messageSentFromClient(
};
}

/**
* Whether a session's device is a computer, for anything that asks if the user
* is at one. Beyond what messageSentFromClient says, a browser paired through
* the relay counts: its own pairing request called it a browser rather than a
* phone or a tablet, which RelayHost records as an unknown device type.
*/
export function sessionIsComputer(session: {
readonly subject: string;
readonly client: AuthClientMetadata;
}): boolean {
if (session.client.deviceType === "desktop") return true;
return (
session.client.deviceType === "unknown" && session.subject === RELAY_DEVICE_SESSION_SUBJECT
);
/** Whether a session's device is a computer, for anything that asks if the user is at one. */
export function sessionIsComputer(session: DeviceSession): boolean {
return sessionDeviceKind(session) === "computer";
}

/**
Expand Down
96 changes: 94 additions & 2 deletions apps/server/src/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,15 @@ import {
EMPTY_CHILD_REQUEST_STATE,
RelayHostId,
RelayInviteId,
RELAY_DEVICE_SESSION_SUBJECT,
} from "@threadlines/contracts";
import { assert, it } from "@effect/vitest";
import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";
import * as Deferred from "effect/Deferred";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
Expand Down Expand Up @@ -192,6 +194,7 @@ import * as PullRequestObservations from "./pullRequest/PullRequestObservations.
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
import { SessionCredentialService } from "./auth/Services/SessionCredentialService.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as StallMonitor from "./observability/StallMonitor.ts";
Expand Down Expand Up @@ -1165,8 +1168,10 @@ const buildAppUnderTest = (options?: {
Layer.provide(layerConfig),
);

yield* Layer.build(appLayer);
return config;
const app = yield* Layer.build(appLayer);
// The app's own sign-ins, for a case that needs one no HTTP route makes
// (a relay device's).
return { ...config, sessions: Context.get(app, SessionCredentialService) };
});

const parseSessionCookieFromWsUrl = (
Expand Down Expand Up @@ -5676,6 +5681,93 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect(
"stamps a browser paired through the relay as a computer, and no sign-in a script made",
() =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
const { sessions } = yield* buildAppUnderTest({
config: { host: "0.0.0.0" },
layers: {
orchestrationEngine: {
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
return { sequence: dispatchedCommands.length };
}),
readEvents: () => Stream.empty,
},
},
});
const baseUrl = yield* getWsServerUrl("/ws", { authenticated: false });
const withToken = (client: Parameters<typeof sessions.issue>[0]) =>
sessions.issue(client).pipe(
Effect.flatMap((issued) => sessions.issueWebSocketToken(issued.sessionId)),
Effect.map(({ token }) => `${baseUrl}?wsToken=${encodeURIComponent(token)}`),
);
// As RelayHost signs in a browser whose pairing the user approved.
const relayBrowserUrl = yield* withToken({
subject: RELAY_DEVICE_SESSION_SUBJECT,
method: "bearer-session-token",
role: "client",
client: { label: "Chrome on macOS", deviceType: "unknown", os: "macOS" },
});
// As `threadlines auth session issue` makes a token for a script or an agent.
const cliTokenUrl = yield* withToken({
subject: "cli-issued-session",
method: "bearer-session-token",
role: "owner",
client: { label: "deploy", deviceType: "bot" },
});
// A pairing link spent from curl.
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {
headers: { cookie: ownerCookie, "content-type": "application/json" },
body: HttpBody.text("{}", "application/json"),
});
const pairing = (yield* pairingResponse.json) as { readonly credential: string };
const curlBootstrap = yield* bootstrapBrowserSession(pairing.credential, {
headers: { "user-agent": "curl/8.7.1" },
});
const curlUrl = appendSessionCookieToWsUrl(
baseUrl,
curlBootstrap.cookie?.split(";")[0] ?? "",
);

for (const [index, url] of [relayBrowserUrl, cliTokenUrl, curlUrl].entries()) {
yield* Effect.scoped(
withWsRpcClient(url, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.turn.start",
commandId: CommandId.make(`cmd-signed-in-${index}`),
threadId: ThreadId.make("thread-signed-in"),
message: {
messageId: MessageId.make(`message-signed-in-${index}`),
role: "user",
text: "Carry on",
attachments: [],
},
runtimeMode: "full-access",
interactionMode: "default",
createdAt: "2026-01-01T00:00:00.000Z",
}),
),
);
}

assert.deepEqual(
dispatchedCommands.map((command) =>
"sentFrom" in command ? command.sentFrom : undefined,
),
[
{ kind: "computer", name: "Chrome on macOS", os: "macOS", place: "elsewhere" },
undefined,
undefined,
],
);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect("stamps a phone's messages with the name it was just given, without reconnecting", () =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
Expand Down
Loading
Loading