Skip to content
Open
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
3 changes: 2 additions & 1 deletion docs/docs/reference/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ These events describe projects linked to an Altimate workspace. A workspace is i
| `workspace_unlinked` | A project was unlinked, with the workspace id when the CLI knew it. |
| `workspace_switched` | A linked project was moved to another workspace. `how` is `rebind_remote` or `rebind_path`. |
| `workspace_auth_expired` | A workspace call was answered 401: the sign-in has expired. Carries `endpoint` and `status`. |
| `workspace_api_error` | A workspace call failed. `status_class` is `4xx`, `5xx`, `network`, `timeout`, or `response` (a success status with an empty or unreadable body), plus the HTTP `status` when there was one. A 403 is reported here, not as expired auth. A status the caller handles as an answer is not a failure and is not reported, such as a 404 from the link lookups ("not linked") or from an unlink ("already unlinked"). `GET /users/me` is not a workspace call and is not reported. |
| `workspace_api_error` | A workspace call failed. `status_class` is `4xx`, `5xx`, `network`, `timeout`, or `response` (a success status with an empty or unreadable body), plus the HTTP `status` when there was one. A 403 is reported here, not as expired auth. A status the caller handles as an answer is not a failure and is not reported, such as a 404 from the link lookups ("not linked") or from an unlink ("already unlinked"). `GET /users/me` is not a workspace call and is not reported. The link lookups (`by-remote`, `by-path`) are retried once after a timeout, a network error or a 502, 503 or 504. Only the last attempt's failure is reported. |
| `workspace_link_check_stale` | The check of which workspace a project is linked to failed, after one retry when the failure allows one (see above), and the saved link was used instead. A 403 or 500 isn't retried and is reported here too. Carries `endpoint`, `status_class` and `status` as `workspace_api_error` does. Reported in place of `workspace_api_error` because the user never sees it; a 401 is still `workspace_auth_expired`. |
| `starter_shown` | The "what this workspace provides" starter was served after a link: to the TUI, to the IDE extension's chat, or printed by `altimate-code link`. It counts the starter being served, so a client that closes before rendering it is still counted. Contains the counts of skills and integrations when known, `knowledge` (`off`, `all`, `selected` or `unknown`) and `memory_enabled`. |
| `starter_action_picked` | The user chose an option from the TUI starter: `action` is `prompt`, `open` or `done`, with `prompt_index` (its position) for a suggested prompt. Never the prompt's text. |
| `workspace_memory_contributed` | A memory block was written back to the workspace's shared memory, including the existing blocks seeded when a project is linked. `block_count` is per write. No memory content. |
Expand Down
11 changes: 11 additions & 0 deletions packages/opencode/src/altimate/telemetry/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,17 @@ export namespace Telemetry {
status?: number
workspace_id?: number
}
| {
/** The check of which workspace a project is linked to failed, after one retry when the failure
* was eligible for one, and the saved link was served instead. Not an API error: the user never sees it. */
type: "workspace_link_check_stale"
timestamp: number
session_id: string
/** "GET /datamate-project-bindings/by-remote" or ".../by-path". */
endpoint: string
status_class: "4xx" | "5xx" | "network" | "timeout" | "response"
status?: number
}
| {
/** The post-link starter message was served (TUI or extension chat); what the workspace provides. */
type: "starter_shown"
Expand Down
138 changes: 109 additions & 29 deletions packages/opencode/src/altimate/workspace/api-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,8 @@ export class WorkspaceApiError extends Error {
public readonly failure: "transport" | "response" = status === undefined ? "transport" : "response",
// altimate_change — workspace rules: a coded `detail` object, read by `rules/api.ts` `classify`
public readonly detail?: Record<string, unknown>,
/** Our own timeout fired, before an answer or while its body was still arriving. */
public readonly timedOut = false,
) {
super(msg)
this.name = "WorkspaceApiError"
Expand Down Expand Up @@ -289,12 +291,15 @@ function workspaceIdIn(body: unknown): number | undefined {
return typeof id === "number" && Number.isInteger(id) && id > 0 ? id : undefined
}

function reportApiErrorRow(input: {
/** One failed call, as `req` would report it. */
interface ApiErrorRow {
endpoint: string
status?: number
kind: "4xx" | "5xx" | "network" | "timeout" | "response"
workspaceId?: number
}) {
}

function reportApiErrorRow(input: ApiErrorRow) {
const session_id = Telemetry.getContext().sessionId
const ws = input.workspaceId !== undefined ? { workspace_id: input.workspaceId } : {}
// Only a 401 says the session expired. A 403 is a refusal (a teammate's private workspace), so
Expand Down Expand Up @@ -426,6 +431,11 @@ async function req<T>(
expectedStatuses?: readonly number[]
/** false for a call that is not a workspace call (`GET /users/me`): it reports no row at all. */
reportErrors?: boolean
/** Hand a failure's row to the caller instead of reporting it, for a caller that only knows what
* the failure means once it has decided what to do about it (the link check, `lookupBinding`). */
onErrorRow?: (row: ApiErrorRow) => void
/** Send the request on a new connection rather than a pooled one. */
freshConnection?: boolean
// altimate_change end
} = {},
): Promise<T> {
Expand All @@ -436,8 +446,10 @@ async function req<T>(
const target = `${url}${basePath}${subpath}${qs}`
const endpoint = endpointOf(method, basePath, subpath)
const bodyWorkspaceId = workspaceIdIn(opts.body)
const reportApiError = (input: Parameters<typeof reportApiErrorRow>[0]) => {
if (opts.reportErrors !== false) reportApiErrorRow(input)
const reportApiError = (input: ApiErrorRow) => {
if (opts.reportErrors === false) return
if (opts.onErrorRow) opts.onErrorRow(input)
else reportApiErrorRow(input)
}
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), timeoutMs)
Expand All @@ -455,6 +467,8 @@ async function req<T>(
},
signal: controller.signal,
...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),
// Bun opens a new connection for a request with keepalive off, instead of reusing a pooled one.
...(opts.freshConnection ? { keepalive: false } : {}),
})
answered = res.status
// Keep the AbortController timeout ACTIVE while we read the response body.
Expand Down Expand Up @@ -497,7 +511,13 @@ async function req<T>(
})
// The answer's status rides on the error too, so a link failure after an answer is not
// classified as a network failure.
throw new WorkspaceApiError(`Request to ${target} timed out after ${Math.round(timeoutMs / 1000)}s`, answered)
throw new WorkspaceApiError(
`Request to ${target} timed out after ${Math.round(timeoutMs / 1000)}s`,
answered,
undefined,
undefined,
true,
)
}
// The server answered and the body failed afterwards (readBounded's cap, a cut stream):
// classify by the status it answered with, so an oversized 500 is still a 5xx row; only a
Expand Down Expand Up @@ -624,34 +644,90 @@ async function readBounded(res: Response, target: string): Promise<string> {

export { req as altimateRequest }

export namespace WorkspaceApi {
/** Server-authoritative pre-check by git remote. Returns null on 404. */
export async function getBindingForRemote(remote: string, actAs?: ActAs): Promise<GetBindingResponse | null> {
/** How a link-check lookup that still fails after its retry is reported. `error`: as
* `workspace_api_error`, like any failed call. `stale`: the caller serves the saved link instead, which
* the user never notices, so it is `workspace_link_check_stale`. A 401 is `workspace_auth_expired` in
* both: the sign-in has expired whatever the caller serves. */
export type LookupFailureReport = "error" | "stale"

/** A lookup that failed before any answer (a timeout, a dropped or refused connection), that timed out
* while a 2xx body was still arriving, or that a gateway answered for a server it could not reach.
* Long-idle processes see the first kind one at a time, which reads as a dead pooled connection, so the
* retry goes out on a new one. */
function retriesLookup(err: unknown): boolean {
if (!(err instanceof WorkspaceApiError)) return false
if (err.status === undefined) return err.failure === "transport"
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
if (err.timedOut && err.status < 300) return true
return err.status === 502 || err.status === 503 || err.status === 504
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/** The by-remote / by-path lookup, retried once (`retriesLookup`). Both attempts run as one credential,
* read once here unless the caller passed one, so an account switch between them can't answer for another
* account. Only the last attempt's failure is reported, once, as `report` says: a first attempt that the
* retry answers reports nothing. */
async function lookup(
subpath: "/by-remote" | "/by-path",
query: Record<string, string>,
actAs: ActAs | undefined,
report: LookupFailureReport,
): Promise<GetBindingResponse | null> {
const account = actAs ?? (await creds())
let failure: ApiErrorRow | undefined
const attempt = (freshConnection: boolean) => {
failure = undefined
return req<GetBindingResponse>("GET", subpath, {
query,
expectedStatuses: [404],
actAs: account,
onErrorRow: (row) => {
failure = row
},
freshConnection,
})
}
try {
try {
return await req<GetBindingResponse>("GET", "/by-remote", {
query: { repo_remote: remote },
expectedStatuses: [404],
...(actAs ? { actAs } : {}),
})
return await attempt(false)
} catch (err) {
if (err instanceof NotFoundError) return null
throw err
if (!retriesLookup(err)) throw err
return await attempt(true)
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
}
} catch (err) {
if (err instanceof NotFoundError) return null
if (failure && (report === "error" || failure.status === 401)) reportApiErrorRow(failure)
else if (failure)
Telemetry.track({
type: "workspace_link_check_stale",
timestamp: Date.now(),
session_id: Telemetry.getContext().sessionId,
endpoint: failure.endpoint,
status_class: failure.kind,
...(failure.status !== undefined ? { status: failure.status } : {}),
})
throw err
}
}

export namespace WorkspaceApi {
/** Server-authoritative pre-check by git remote. Returns null on 404. Retried once on a transport
* failure, a timeout while a 2xx body is arriving, or a 502/503/504 (`retriesLookup`); `report` says
* how a failure that outlasts the retry is reported. */
export async function getBindingForRemote(
remote: string,
actAs?: ActAs,
report: LookupFailureReport = "error",
): Promise<GetBindingResponse | null> {
return lookup("/by-remote", { repo_remote: remote }, actAs, report)
}

/** Symmetric pre-check by absolute project directory path (for projects
* without a git remote). Returns null on 404. */
export async function getBindingForPath(projectPath: string, actAs?: ActAs): Promise<GetBindingResponse | null> {
try {
return await req<GetBindingResponse>("GET", "/by-path", {
query: { project_path: projectPath },
expectedStatuses: [404],
...(actAs ? { actAs } : {}),
})
} catch (err) {
if (err instanceof NotFoundError) return null
throw err
}
* without a git remote). Returns null on 404. Retried and reported as `getBindingForRemote` is. */
export async function getBindingForPath(
projectPath: string,
actAs?: ActAs,
report: LookupFailureReport = "error",
): Promise<GetBindingResponse | null> {
return lookup("/by-path", { project_path: projectPath }, actAs, report)
}

/** Tries remote first (stronger identity), then path. Returns the first hit
Expand All @@ -662,13 +738,17 @@ export namespace WorkspaceApi {
export async function getBindingForProject(
id: ProjectIdentifier,
actAs?: ActAs,
report: LookupFailureReport = "error",
): Promise<ProjectBindingLookup | null> {
if (!id.repoRemote && !id.projectPath) return null
// One credential for both lookups and their retries.
const account = actAs ?? (await creds())
if (id.repoRemote) {
const hit = await getBindingForRemote(id.repoRemote, actAs)
const hit = await getBindingForRemote(id.repoRemote, account, report)
if (hit) return { ...hit, matchedBy: "remote" }
}
if (id.projectPath) {
const hit = await getBindingForPath(id.projectPath, actAs)
const hit = await getBindingForPath(id.projectPath, account, report)
if (hit) return { ...hit, matchedBy: "path" }
}
return null
Expand Down
13 changes: 8 additions & 5 deletions packages/opencode/src/altimate/workspace/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { Filesystem } from "@/util/filesystem"
import { Log } from "@/altimate/util/log"
// Type-only: the value side is imported dynamically in resolveBinding to keep
// this module's import graph free of the API client at load time.
import type { Binding, ProjectBindingLookup } from "./api-client"
import type { Binding, LookupFailureReport, ProjectBindingLookup } from "./api-client"
import type { SeedOutcome } from "./memory-backfill"
// altimate_change — the IDE extension's workspace pin; see ./pin.ts
import { readPin, readPinLogged, resolveWithinRoot, type ValidPin } from "./pin"
Expand Down Expand Up @@ -881,7 +881,7 @@ export async function resolveBindingOutcome(directory: string): Promise<BindingO
if (validated !== undefined && Date.now() - validated < REVALIDATE_MS) {
return { status: "bound", binding: local }
}
const fresh = await lookupBinding(directory, key)
const fresh = await lookupBinding(directory, key, "stale")
if (fresh.status === "unknown") {
// Cannot reach the server: keep serving what we have rather than tearing
// a working setup down over a network blip — marked, so a caller that
Expand Down Expand Up @@ -913,7 +913,7 @@ export async function resolveBindingOutcome(directory: string): Promise<BindingO
},
}
}
return await lookupBinding(directory, key)
return await lookupBinding(directory, key, "error")
}

/** Listeners fired when THIS process changes a project's binding.
Expand Down Expand Up @@ -1151,10 +1151,13 @@ function forgetBinding(
return true
}

/** The server's answer for this project, with no cache consulted. */
/** The server's answer for this project, with no cache consulted. `report`: how a failed lookup is
* reported, `stale` when the caller serves the saved link if it fails (a fallback the user never sees,
* not an API error). */
async function lookupBinding(
directory: string,
key: AccountKey,
report: LookupFailureReport,
): Promise<BindingOutcome> {
const canon = accountScopedKey(directory, key)
const missedAt = serverLookupMissed.get(canon)
Expand All @@ -1164,7 +1167,7 @@ async function lookupBinding(
try {
const { resolveProjectIdentifier } = await import("./detect")
const { WorkspaceApi } = await import("./api-client")
hit = await WorkspaceApi.getBindingForProject(resolveProjectIdentifier(directory))
hit = await WorkspaceApi.getBindingForProject(resolveProjectIdentifier(directory), undefined, report)
} catch (err) {
// Unreachable or a 5xx: unknown, not unbound. Deliberately NOT memoized —
// the next session should ask again rather than inherit a network blip.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,12 @@ describe("workspace id on the telemetry context", () => {
{ ...base, type: "workspace_switched", to_workspace_id: 2, how: "rebind_remote" },
{ ...base, type: "workspace_auth_expired", endpoint: "GET /datamates/", status: 401 },
{ ...base, type: "workspace_api_error", endpoint: "GET /datamates/", status_class: "5xx", status: 500 },
{
...base,
type: "workspace_link_check_stale",
endpoint: "GET /datamate-project-bindings/by-remote",
status_class: "timeout",
},
{ ...base, type: "starter_shown", workspace_id: 1, knowledge: "off" },
{ ...base, type: "starter_action_picked", workspace_id: 1, action: "done" },
{ ...base, type: "workspace_memory_contributed", workspace_id: 1, block_count: 1 },
Expand All @@ -175,7 +181,7 @@ describe("workspace id on the telemetry context", () => {

test("the workspace rows are sent when telemetry is on and dropped when it is off", async () => {
const names = workspaceRows().map((e) => e.type)
expect(new Set(names).size).toBe(16) // plus tool_call rows, which are not new types
expect(new Set(names).size).toBe(17) // plus tool_call rows, which are not new types

await Telemetry.shutdown()
await Telemetry.init()
Expand Down
Loading
Loading