Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
import * as Schema from "effect/Schema";
import * as Predicate from "effect/Predicate";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { HttpBody, HttpClient } from "effect/unstable/http";
import { buildAppUnderTest } from "./serverTestApp.ts";
import {
getAuthenticatedSessionCookieHeader,
jsonRequestBody,
splitHeaderTokens,
} from "./serverTestClients.ts";
import { makeBrowserOtlpPayload } from "./serverTestTracing.ts";
it.layer(NodeServices.layer)("server router seam", (it) => {
it.effect("proxies browser OTLP trace exports through the server", () =>
Effect.gen(function* () {
const upstreamRequests: Array<{
readonly body: string;
readonly contentType: string | null;
}> = [];
const localTraceRecords: Array<unknown> = [];
const payload = {
resourceSpans: [
{
resource: {
attributes: [
{
key: "service.name",
value: { stringValue: "t3-web" },
},
],
},
scopeSpans: [
{
scope: {
name: "effect",
version: "4.0.0-beta.43",
},
spans: [
{
traceId: "11111111111111111111111111111111",
spanId: "2222222222222222",
parentSpanId: "3333333333333333",
name: "RpcClient.server.getSettings",
kind: 3,
startTimeUnixNano: "1000000",
endTimeUnixNano: "2000000",
attributes: [
{
key: "rpc.method",
value: { stringValue: "server.getSettings" },
},
],
events: [
{
name: "http.request",
timeUnixNano: "1500000",
attributes: [
{
key: "http.status_code",
value: { intValue: "200" },
},
],
},
],
links: [],
status: {
code: "STATUS_CODE_OK",
},
flags: 1,
},
],
},
],
},
],
};
const collector = yield* Effect.acquireRelease(
Effect.promise(async () => {
const NodeHttp = await import("node:http");
return await new Promise<{
readonly close: () => Promise<void>;
readonly url: string;
}>((resolve, reject) => {
const server = NodeHttp.createServer((request, response) => {
const chunks: Buffer[] = [];
request.on("data", (chunk) => {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
});
request.on("end", () => {
upstreamRequests.push({
body: Buffer.concat(chunks).toString("utf8"),
contentType: request.headers["content-type"] ?? null,
});
response.statusCode = 204;
response.end();
});
});
server.on("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (!address || Predicate.isString(address)) {
reject(new Error("Expected TCP collector address"));
return;
}
resolve({
url: `http://127.0.0.1:${address.port}/v1/traces`,
close: () =>
new Promise<void>((resolveClose, rejectClose) => {
server.close((error) => {
if (error) {
rejectClose(error);
return;
}
resolveClose();
});
}),
});
});
});
}),
({ close }) => Effect.promise(close),
);
yield* buildAppUnderTest({
config: {
otlpTracesUrl: collector.url,
},
layers: {
browserTraceCollector: {
record: (records) =>
Effect.sync(() => {
localTraceRecords.push(...records);
}),
},
},
});
const response = yield* HttpClient.post("/api/observability/v1/traces", {
headers: {
cookie: yield* getAuthenticatedSessionCookieHeader(),
"content-type": "application/json",
origin: "http://localhost:5733",
},
body: HttpBody.text(JSON.stringify(payload), "application/json"),
});
assert.equal(response.status, 204);
assert.equal(response.headers["access-control-allow-origin"], "*");
assert.deepEqual(localTraceRecords, [
{
type: "otlp-span",
name: "RpcClient.server.getSettings",
traceId: "11111111111111111111111111111111",
spanId: "2222222222222222",
parentSpanId: "3333333333333333",
sampled: true,
kind: "client",
startTimeUnixNano: "1000000",
endTimeUnixNano: "2000000",
durationMs: 1,
attributes: {
"rpc.method": "server.getSettings",
},
resourceAttributes: {
"service.name": "t3-web",
},
scope: {
name: "effect",
version: "4.0.0-beta.43",
attributes: {},
},
events: [
{
name: "http.request",
timeUnixNano: "1500000",
attributes: {
"http.status_code": "200",
},
},
],
links: [],
status: {
code: "STATUS_CODE_OK",
},
},
]);
assert.deepEqual(upstreamRequests, [
{
body: jsonRequestBody(payload),
contentType: "application/json",
},
]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("responds to browser OTLP trace preflight requests with CORS headers", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
const response = yield* HttpClient.options("/api/observability/v1/traces", {
headers: {
origin: "http://localhost:5733",
"access-control-request-method": "POST",
"access-control-request-headers": "content-type",
},
});
assert.equal(response.status, 204);
assert.equal(response.headers["access-control-allow-origin"], "*");
assert.deepEqual(splitHeaderTokens(response.headers["access-control-allow-methods"]), [
"GET",
"OPTIONS",
"POST",
]);
assert.deepEqual(splitHeaderTokens(response.headers["access-control-allow-headers"]), [
"authorization",
"b3",
"content-type",
"traceparent",
]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"stores browser OTLP trace exports locally when no upstream collector is configured",
() =>
Effect.gen(function* () {
const localTraceRecords: Array<unknown> = [];
const payload = yield* makeBrowserOtlpPayload("client.test");
const resourceSpan = payload.resourceSpans[0];
const scopeSpan = resourceSpan?.scopeSpans[0];
const span = scopeSpan?.spans[0];
assert.notEqual(resourceSpan, undefined);
assert.notEqual(scopeSpan, undefined);
assert.notEqual(span, undefined);
if (!resourceSpan || !scopeSpan || !span) {
return;
}
yield* buildAppUnderTest({
layers: {
browserTraceCollector: {
record: (records) =>
Effect.sync(() => {
localTraceRecords.push(...records);
}),
},
},
});
const response = yield* HttpClient.post("/api/observability/v1/traces", {
headers: {
cookie: yield* getAuthenticatedSessionCookieHeader(),
"content-type": "application/json",
},
body: HttpBody.text(JSON.stringify(payload), "application/json"),
});
assert.equal(response.status, 204);
assert.equal(localTraceRecords.length, 1);
const record = localTraceRecords[0] as {
readonly type: string;
readonly name: string;
readonly traceId: string;
readonly spanId: string;
readonly kind: string;
readonly attributes: Readonly<Schema.JsonObject>;
readonly events: ReadonlyArray<unknown>;
readonly links: ReadonlyArray<unknown>;
readonly scope: {
readonly name?: string;
readonly attributes: Readonly<Schema.JsonObject>;
};
readonly resourceAttributes: Readonly<Schema.JsonObject>;
readonly status?: {
readonly code?: string;
};
};
assert.equal(record.type, "otlp-span");
assert.equal(record.name, span.name);
assert.equal(record.traceId, span.traceId);
assert.equal(record.spanId, span.spanId);
assert.equal(record.kind, "internal");
assert.deepEqual(record.attributes, {});
assert.deepEqual(record.events, []);
assert.deepEqual(record.links, []);
assert.equal(record.scope.name, scopeSpan.scope.name);
assert.deepEqual(record.scope.attributes, {});
assert.equal(record.resourceAttributes["service.name"], "t3-web");
assert.equal(record.status?.code, String(span.status.code));
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
});