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
12 changes: 10 additions & 2 deletions apps/desktop/src/app/DesktopCrashReport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,21 @@ describe("resolveTelemetryConsent", () => {
);
});

it("keeps the default when settings are unreadable", () => {
assert.isTrue(
it("fails closed when an existing settings file is malformed or unreadable", () => {
assert.isFalse(
resolveTelemetryConsent({
envOverride: undefined,
throwawayRun: false,
rawSettingsJson: "not json",
}),
);
assert.isFalse(
resolveTelemetryConsent({
envOverride: undefined,
throwawayRun: false,
rawSettingsJson: undefined,
settingsReadFailed: true,
}),
);
});
});
28 changes: 22 additions & 6 deletions apps/desktop/src/app/DesktopCrashReport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,23 +106,25 @@ const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
* Mirrors the server's telemetry consent: `THREADLINES_TELEMETRY_ENABLED`
* wins when set, a throwaway run (CI, or a data folder in the temp folder)
* sends nothing, otherwise `usageAnalyticsEnabled` from settings.json decoded
* with the same lenient JSONC parser the server uses, defaulting to enabled
* when the file is absent or undecodable.
* with the same lenient JSONC parser the server uses. A missing file uses the
* default; an unreadable or malformed existing file fails closed.
*/
export function resolveTelemetryConsent(input: {
readonly envOverride: string | undefined;
readonly throwawayRun: boolean;
readonly rawSettingsJson: string | undefined;
readonly settingsReadFailed?: boolean;
}): boolean {
const override = parseTelemetryEnabledOverride(input.envOverride);
if (override !== undefined) return override;
if (input.throwawayRun) return false;
if (input.settingsReadFailed === true) return false;

if (input.rawSettingsJson === undefined) {
return DEFAULT_SERVER_SETTINGS.usageAnalyticsEnabled;
}
return Option.match(decodeServerSettingsJson(input.rawSettingsJson), {
onNone: () => DEFAULT_SERVER_SETTINGS.usageAnalyticsEnabled,
onNone: () => false,
onSome: (settings) => settings.usageAnalyticsEnabled,
});
}
Expand Down Expand Up @@ -164,9 +166,22 @@ const makeDesktopCrashReport = Effect.gen(function* () {
const posthogHost = process.env.THREADLINES_POSTHOG_HOST?.trim() || bundledPosthogHost;
if (!posthogKey) return;

const rawSettingsJson = yield* fileSystem
const settingsRead = yield* fileSystem
.readFileString(environment.serverSettingsPath)
.pipe(Effect.map(Option.some), Effect.orElseSucceed(Option.none<string>));
.pipe(Effect.result);
let rawSettingsJson: string | undefined;
let settingsReadFailed = false;
if (settingsRead._tag === "Success") {
rawSettingsJson = settingsRead.success;
} else {
const error = settingsRead.failure;
const isMissing =
typeof error === "object" &&
error !== null &&
"reason" in error &&
(error as { readonly reason?: { readonly _tag?: string } }).reason?._tag === "NotFound";
settingsReadFailed = !isMissing;
}
const realPathOrSelf = (path: string) =>
fileSystem.realPath(path).pipe(Effect.orElseSucceed(() => path));
const tempDir = NodeOS.tmpdir();
Expand All @@ -177,7 +192,8 @@ const makeDesktopCrashReport = Effect.gen(function* () {
tempDirs: [tempDir, yield* realPathOrSelf(tempDir)],
ciEnv: process.env.CI,
}),
rawSettingsJson: Option.getOrUndefined(rawSettingsJson),
rawSettingsJson,
settingsReadFailed,
});
if (!consented) return;

Expand Down
27 changes: 26 additions & 1 deletion apps/server/src/assistants/AssistantMcpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
ThreadWaitTool,
} from "../outsideAgents/connectTools.ts";
import { OutsideAgentConnections } from "../outsideAgents/OutsideAgentConnections.ts";
import { makeDailyAnalyticsCounter } from "../telemetry/DailyCounter.ts";
import { AssistantAlerts } from "./AssistantAlerts.ts";
import { type AssistantMcpTool, makeAssistantMcp, mapStrings } from "./AssistantMcp.ts";
import { makeAssistantMcpEvents } from "./assistantMcpEvents.ts";
Expand Down Expand Up @@ -172,13 +173,37 @@ export const AssistantMcpServerLive = Layer.effectDiscard(
},
},
];
const toolCallCounter = yield* makeDailyAnalyticsCounter<{
readonly tool: string;
readonly outcome: string;
readonly door: "assistant";
}>({
event: "outside_agent.tool_calls",
keyOf: ({ tool, outcome }) => `${tool}\u0000${outcome}`,
});
const countedTools: ReadonlyArray<AssistantMcpTool> = tools.map((entry) => ({
...entry,
run: (caller, parameters) =>
Effect.tap(entry.run(caller, parameters), (result) =>
Effect.sync(() => {
const outcome =
typeof result === "object" &&
result !== null &&
"outcome" in result &&
typeof (result as { readonly outcome?: unknown }).outcome === "string"
? (result as { readonly outcome: string }).outcome
: "ok";
toolCallCounter.increment({ tool: entry.tool.name, outcome, door: "assistant" });
}),
),
}));
const handler = makeAssistantMcp({
authenticate: assistants.authenticate,
listed: (caller) =>
connections
.grant(caller.connectionId)
.pipe(Effect.map((grant) => listedToolsFor(grant?.access ?? null))),
tools,
tools: countedTools,
events: makeAssistantMcpEvents({
alerts,
grantOf: connections.grant,
Expand Down
22 changes: 20 additions & 2 deletions apps/server/src/assistants/AssistantsLive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ import {
SERVER_SIGNING_SECRET_NAME,
} from "../auth/Layers/SessionCredentialService.ts";
import { ServerSecretStore } from "../auth/Services/ServerSecretStore.ts";
import { AnalyticsService } from "../telemetry/Services/AnalyticsService.ts";
import { makeKeyedLock } from "../links/keyedLock.ts";
import {
assistantOfRow,
Expand Down Expand Up @@ -213,6 +214,7 @@ const frameBytes = (frame: unknown) => Buffer.byteLength(JSON.stringify(frame),
export const makeAssistants = Effect.gen(function* () {
const relay = yield* AssistantRelay;
const repository = yield* OutsideAgentConnectionRepository;
const analytics = yield* Effect.serviceOption(AnalyticsService);
const reviewComputer = yield* Config.Boolean(ASSISTANT_REVIEW_COMPUTER_ENV).pipe(
Config.withDefault(false),
Effect.orElseSucceed(() => false),
Expand Down Expand Up @@ -778,11 +780,12 @@ export const makeAssistants = Effect.gen(function* () {
identity: identityOf(entry.signIn),
clientName: entry.name,
};
const assistant = assistantOfRow(shown);
return {
connectionId,
name: connectionNameOf(shown),
givenName: connectionNameOf(shown) === entry.name ? null : entry.name,
assistant: assistantOfRow(shown),
assistant,
kind: "assistant",
signIn: "oauth",
identity: shown.identity,
Expand Down Expand Up @@ -884,8 +887,16 @@ export const makeAssistants = Effect.gen(function* () {
);
yield* notify;
yield* recountConnections;
const connection = connectionOfRow(row);
if (Option.isSome(analytics)) {
yield* analytics.value.record("assistant.connected", {
assistant: connection.assistant ?? "other",
signIn: "key",
access: row.access,
});
}
return {
connection: connectionOfRow(row),
connection,
key: formatAssistantCredential({ kind: "key", route, secret }),
address: door.address,
};
Expand Down Expand Up @@ -989,6 +1000,13 @@ export const makeAssistants = Effect.gen(function* () {
yield* notify;
// The one it replaced is revoked at the relay.
yield* connectionsChanged;
if (Option.isSome(analytics)) {
yield* analytics.value.record("assistant.connected", {
assistant: assistantOfRow(row) ?? "other",
signIn: "oauth",
access: row.access,
});
}
return tokensFor(row, issued.route, 0, now);
});

Expand Down
124 changes: 77 additions & 47 deletions apps/server/src/device/DeviceService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
type DeviceSummary,
type ThreadId,
} from "@threadlines/contracts";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
Expand All @@ -51,6 +52,7 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
import { writeFileStringAtomically } from "../atomicWrite.ts";
import { ServerConfig } from "../config.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import { AnalyticsService } from "../telemetry/Services/AnalyticsService.ts";
import {
agentDeviceLauncherKey,
bindAgentDeviceLauncher,
Expand Down Expand Up @@ -169,6 +171,7 @@ export const make = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const scope = yield* Scope.Scope;
const analytics = yield* Effect.serviceOption(AnalyticsService);
const stateDir = config.stateDir;
const claimsPath = path.join(deviceStateDir(path, stateDir), "claims.json");
const services = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Expand Down Expand Up @@ -454,55 +457,82 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`,

const open: DeviceServiceShape["open"] = (input, openedBy = "user") =>
Effect.gen(function* () {
const releasesAtStart = releaseCounts.get(input.threadId) ?? 0;
yield* ensurePlatform(input.platform);
const ready = yield* readiness;
let state = yield* refresh(ready);
let device = findDevice(state, input.deviceId);
if (!device) return yield* new DeviceNotFoundError({ deviceId: input.deviceId });
if (device.platform === "android" && !device.physical) yield* requireAndroidVideo(ready);
let bootedNow = false;
if (!device.booted && input.boot !== false) {
const booting = { ...device, threadId: input.threadId };
yield* publish((current) => ({
...current,
bootingDevices: [
...current.bootingDevices.filter((entry) => entry.id !== booting.id),
booting,
],
}));
const bootedId = yield* ready.devices.boot(device).pipe(
Effect.ensuring(
publish((current) => ({
...current,
bootingDevices: current.bootingDevices.filter((entry) => entry.id !== booting.id),
})),
),
);
bootedNow = true;
state = yield* refresh(ready);
// Retained entries predate the boot, so only a complete listing confirms the booted device.
device = state.incompletePlatforms.includes(device.platform)
? undefined
: (findDevice(state, bootedId) ?? findDevice(state, device.id));
const startedNanos = yield* Clock.monotonicTimeNanos;
const elapsedMs = Clock.monotonicTimeNanos.pipe(
Effect.map((now) => Math.max(0, Math.round(Number(now - startedNanos) / 1_000_000))),
);
const recordAnalytics = (event: string, properties: Readonly<Record<string, unknown>>) =>
Option.isSome(analytics) ? analytics.value.record(event, properties) : Effect.void;

return yield* Effect.gen(function* () {
const releasesAtStart = releaseCounts.get(input.threadId) ?? 0;
yield* ensurePlatform(input.platform);
const ready = yield* readiness;
let state = yield* refresh(ready);
let device = findDevice(state, input.deviceId);
if (!device) return yield* new DeviceNotFoundError({ deviceId: input.deviceId });
} else if (device.booted) {
yield* ready.devices.attach(device);
}
const opened = device;
const earlier = (yield* currentState).sessions.find(
(session) => session.deviceId === opened.id && session.bootedByThreadlines,
if (device.platform === "android" && !device.physical) yield* requireAndroidVideo(ready);
let bootedNow = false;
if (!device.booted && input.boot !== false) {
const booting = { ...device, threadId: input.threadId };
yield* publish((current) => ({
...current,
bootingDevices: [
...current.bootingDevices.filter((entry) => entry.id !== booting.id),
booting,
],
}));
const bootedId = yield* ready.devices.boot(device).pipe(
Effect.ensuring(
publish((current) => ({
...current,
bootingDevices: current.bootingDevices.filter((entry) => entry.id !== booting.id),
})),
),
);
bootedNow = true;
state = yield* refresh(ready);
// Retained entries predate the boot, so only a complete listing confirms the booted device.
device = state.incompletePlatforms.includes(device.platform)
? undefined
: (findDevice(state, bootedId) ?? findDevice(state, device.id));
if (!device) return yield* new DeviceNotFoundError({ deviceId: input.deviceId });
} else if (device.booted) {
yield* ready.devices.attach(device);
}
const opened = device;
const earlier = (yield* currentState).sessions.find(
(session) => session.deviceId === opened.id && session.bootedByThreadlines,
);
const session: DeviceSession = {
threadId: input.threadId,
deviceId: opened.id,
platform: opened.platform,
openedAt: DateTime.formatIso(yield* DateTime.now),
bootedByThreadlines: bootedNow || earlier !== undefined,
openedBy,
};
yield* recordSession(session, releasesAtStart);
yield* recordAnalytics("device.session.opened", {
devicePlatform: opened.platform,
openedBy,
bootedNow,
physical: opened.physical,
durationMs: yield* elapsedMs,
});
return session;
}).pipe(
Effect.tapError((error) =>
Effect.flatMap(elapsedMs, (durationMs) =>
recordAnalytics("device.session.open_failed", {
devicePlatform: input.platform,
openedBy,
errorKind: error._tag,
durationMs,
}),
),
),
);
const session: DeviceSession = {
threadId: input.threadId,
deviceId: opened.id,
platform: opened.platform,
openedAt: DateTime.formatIso(yield* DateTime.now),
bootedByThreadlines: bootedNow || earlier !== undefined,
openedBy,
};
yield* recordSession(session, releasesAtStart);
return session;
}).pipe(Effect.withSpan("DeviceService.open"));

/** Removes launchers whose session is gone. Under the launcher lock, so binding never races it. */
Expand Down
21 changes: 20 additions & 1 deletion apps/server/src/mcp/McpDeviceServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { McpProtocol, McpSchema, McpServer, Tool } from "effect/ai";
import { HttpRouter, HttpServerRequest, type HttpServerResponse } from "effect/http";

import { DeviceService } from "../device/DeviceService.ts";
import { makeDailyAnalyticsCounter } from "../telemetry/DailyCounter.ts";
import { deviceClose, deviceList, deviceOpen, deviceScreenshot } from "./deviceToolHandlers.ts";
import { makeOutsideToolLimits } from "./outsideToolLimit.ts";
import {
Expand Down Expand Up @@ -209,14 +210,32 @@ const registerDeviceTools = Effect.fn("McpDeviceServer.registerDeviceTools")(fun
),
};

const toolCallCounter = yield* makeDailyAnalyticsCounter<{
readonly tool: string;
readonly outcome: "ok" | "error";
}>({
event: "device.tool_calls",
keyOf: ({ tool, outcome }) => `${tool}\u0000${outcome}`,
});

for (const tool of DEVICE_TOOLS) {
const handle = handlers[tool.name]!;
yield* server.addTool({
tool: describe(tool),
annotations: tool.annotations,
handle: (payload) =>
Effect.withFiber((fiber) =>
handle(callerOf(fiber), payload).pipe(Effect.provideService(DeviceService, devices)),
handle(callerOf(fiber), payload).pipe(
Effect.provideService(DeviceService, devices),
Effect.tap((result) =>
Effect.sync(() => {
toolCallCounter.increment({
tool: tool.name,
outcome: result.isError === true ? "error" : "ok",
});
}),
),
),
),
});
}
Expand Down
Loading
Loading