Skip to content

Commit 49a3dbe

Browse files
fix: read the opt-out from the command's project; guard the marker across processes
- init reads the config of the run/attach `--dir` or TUI project - legacy TOML global config read; a non-boolean value is unreadable - the marker is written only while this send still holds its claim - docs: eligibility is an existing machine id Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01YNasdD5tQMNtzXsuMEy82X
1 parent 57eed56 commit 49a3dbe

7 files changed

Lines changed: 131 additions & 23 deletions

File tree

‎docs/docs/reference/telemetry.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ You can also set the environment variable:
134134
export ALTIMATE_TELEMETRY_DISABLED=true
135135
```
136136

137-
When telemetry is disabled, a machine that has sent telemetry before sends one final `telemetry_opted_out` event, then nothing: no further events and no requests to the telemetry endpoint until telemetry is turned back on. The event carries only the machine ID, the opt-out source, the CLI version and the client — see the event table above. With it, an opted-out machine can be counted instead of looking like a client that stopped working.
137+
When telemetry is disabled, a machine with an existing machine ID sends one final `telemetry_opted_out` event, then nothing: no further events and no requests to the telemetry endpoint until telemetry is turned back on. The event carries only the machine ID, the opt-out source, the CLI version and the client — see the event table above. With it, an opted-out machine can be counted instead of looking like a client that stopped working.
138138

139139
- The event is sent only if `~/.altimate/machine-id` already exists. A machine that never ran with telemetry on sends nothing.
140140
- Once the telemetry endpoint accepts the event, Altimate Code writes the marker file `~/.altimate/telemetry-opted-out`, and later launches send nothing. If the endpoint cannot be reached, no marker is written and a later launch tries again.

‎packages/opencode/src/altimate/telemetry/config-state.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import { ConfigManaged } from "@/config/managed"
1515
* before one exists, so there it throws. Treating that as "enabled" let an opted-out user's main
1616
* thread clear the opt-out marker and resolve their identity. This reads the same files `Config`
1717
* merges, in the same order (a later source overrides an earlier one), straight from disk:
18-
* the global config files, `OPENCODE_CONFIG`, the project files and `.altimate-code`/`.opencode`
18+
* the global config files (the legacy TOML `config` file included), `OPENCODE_CONFIG`, the project files and `.altimate-code`/`.opencode`
1919
* directories found from `directory`, the inline `OPENCODE_CONFIG_CONTENT`, the managed config
2020
* directory and macOS managed preferences. Remote and account configs are not read (they need
2121
* the network).
@@ -48,7 +48,12 @@ export async function disabledState(directory: string = process.cwd()): Promise<
4848
const apply = (data: unknown) => {
4949
const disabled = (data as { telemetry?: { disabled?: unknown } } | undefined)?.telemetry?.disabled
5050
if (disabled === undefined) return
51-
value = Boolean(disabled)
51+
// Config's schema accepts only a boolean; anything else makes the whole config invalid there.
52+
if (typeof disabled !== "boolean") {
53+
unknown = true
54+
return
55+
}
56+
value = disabled
5257
unknown = false
5358
}
5459
const readFile = async (file: string) => {
@@ -74,6 +79,13 @@ export async function disabledState(directory: string = process.cwd()): Promise<
7479
}
7580

7681
for (const file of GLOBAL_FILES) await readFile(path.join(Global.Path.config, file))
82+
// The legacy TOML global config, which Config merges after the JSON files (and migrates).
83+
const legacy = path.join(Global.Path.config, "config")
84+
try {
85+
apply(Bun.TOML.parse(await fs.readFile(legacy, "utf-8")))
86+
} catch (err) {
87+
if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") unknown = true
88+
}
7789
if (Flag.OPENCODE_CONFIG) await readFile(Flag.OPENCODE_CONFIG)
7890

7991
const worktree = worktreeOf(directory)

‎packages/opencode/src/altimate/telemetry/index.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1913,6 +1913,12 @@ export namespace Telemetry {
19131913
// altimate_change — false when this init could not read the user config: an opted-out user may be
19141914
// behind it, so no identity is resolved (at init, at a flush or on refresh) until an init that can.
19151915
let identityAllowed = true
1916+
// altimate_change — the project the command will run in, for reading the config without an
1917+
// Instance: the CLI initialises telemetry before a command changes into its `--dir` or project.
1918+
let configDirectory: string | undefined
1919+
export function setConfigDirectory(directory: string | undefined) {
1920+
configDirectory = directory
1921+
}
19161922
let machineId = ""
19171923
let sessionId = ""
19181924
let projectId = ""
@@ -2128,7 +2134,7 @@ export namespace Telemetry {
21282134
return
21292135
}
21302136
} catch {
2131-
const state = await TelemetryConfig.disabledState()
2137+
const state = await TelemetryConfig.disabledState(configDirectory)
21322138
if (state === "disabled") {
21332139
buffer = []
21342140
void recordOptOut("config")
@@ -2279,7 +2285,8 @@ export namespace Telemetry {
22792285
// A shutdown since this task started means a later init may own the marker now: do not
22802286
// send, and let the next disabled init start over.
22812287
if (lifecycle !== lifecycleGeneration) return
2282-
if (!OptOutMarker.claim()) return
2288+
const claim = OptOutMarker.claim()
2289+
if (!claim) return
22832290
const controller = new AbortController()
22842291
const timeout = setTimeout(() => controller.abort(), OPT_OUT_TIMEOUT_MS)
22852292
try {
@@ -2291,11 +2298,12 @@ export namespace Telemetry {
22912298
body: JSON.stringify(envelopes),
22922299
signal: controller.signal,
22932300
})
2294-
// Accepted: write the marker unless telemetry was turned back on meanwhile.
2295-
if (res.ok && marker === markerGeneration) OptOutMarker.write()
2301+
// Accepted: write the marker unless telemetry was turned back on meanwhile, in this process
2302+
// (the generation) or another one (an enabled init removes the claim).
2303+
if (res.ok && marker === markerGeneration && OptOutMarker.holds(claim)) OptOutMarker.write()
22962304
} finally {
22972305
clearTimeout(timeout)
2298-
OptOutMarker.release()
2306+
OptOutMarker.release(claim)
22992307
}
23002308
} catch {
23012309
// The opt-out path never surfaces: a missed marker only means one more attempt next launch.

‎packages/opencode/src/altimate/telemetry/opt-out.ts‎

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import fs from "fs"
2+
import { randomUUID } from "crypto"
23
import path from "path"
34
import { Global } from "../../global"
45
import { readExistingMachineId } from "@/altimate/util/machine-id"
@@ -51,41 +52,57 @@ function claimPath(): string {
5152
/**
5253
* Claim the one opt-out send, across threads and processes: an exclusive create of an in-flight
5354
* file next to the marker. The TUI's main thread and its worker both init telemetry, so without
54-
* this the first opted-out launch sent the event twice. False when another send holds a fresh
55-
* claim (or the file cannot be created); a claim left by a process that died is taken over.
55+
* this the first opted-out launch sent the event twice. Returns this send's token, or undefined when
56+
* another send holds a fresh claim (or the file cannot be created); a claim left by a process that
57+
* died is taken over.
5658
*/
57-
export function claim(): boolean {
58-
const create = () => fs.writeFileSync(claimPath(), `${process.pid}\n`, { mode: 0o600, flag: "wx" })
59+
export function claim(): string | undefined {
60+
const token = `${process.pid}:${randomUUID()}`
61+
const create = () => fs.writeFileSync(claimPath(), `${token}\n`, { mode: 0o600, flag: "wx" })
5962
try {
6063
create()
61-
return true
64+
return token
6265
} catch (err) {
63-
if ((err as NodeJS.ErrnoException)?.code !== "EEXIST") return false
66+
if ((err as NodeJS.ErrnoException)?.code !== "EEXIST") return undefined
6467
}
6568
try {
6669
const age = Date.now() - fs.lstatSync(claimPath()).mtimeMs
67-
if (age < CLAIM_STALE_MS) return false
70+
if (age < CLAIM_STALE_MS) return undefined
6871
fs.rmSync(claimPath(), { force: true })
6972
create()
70-
return true
73+
return token
74+
} catch {
75+
return undefined
76+
}
77+
}
78+
79+
/** Whether `token`'s claim still stands. An enabled init in any process removes the claim with the
80+
* marker (see `clear`), so a send it outlived must not write the marker back. */
81+
export function holds(token: string): boolean {
82+
try {
83+
return fs.readFileSync(claimPath(), "utf-8").trim() === token
7184
} catch {
7285
return false
7386
}
7487
}
7588

76-
/** Give the claim back: after the marker is written, or when the send failed so a later launch tries. */
77-
export function release(): void {
89+
/** Give the claim back, if it is still this send's: after the marker is written, or when the send
90+
* failed so a later launch tries. */
91+
export function release(token: string): void {
7892
try {
79-
fs.rmSync(claimPath(), { force: true })
93+
if (holds(token)) fs.rmSync(claimPath(), { force: true })
8094
} catch {
8195
// a leftover claim goes stale and is taken over
8296
}
8397
}
8498

85-
/** Best effort: an unremovable marker (read-only directory) must never fail an init. */
99+
/** Telemetry is on again: remove the marker and any in-flight claim, so a send still running in
100+
* another process does not write the marker back. Best effort: an unremovable marker (read-only
101+
* directory) must never fail an init. */
86102
export function clear(): void {
87103
try {
88104
fs.rmSync(markerPath(), { force: true })
105+
fs.rmSync(claimPath(), { force: true })
89106
} catch {
90107
// leave it; the next opt-out is then not recorded again, which is the lesser failure
91108
}

‎packages/opencode/src/index.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ import { ExportCommand } from "./cli/cmd/export"
3030
import { ImportCommand } from "./cli/cmd/import"
3131
import { AttachCommand } from "./cli/cmd/attach"
3232
import { TuiThreadCommand } from "./cli/cmd/tui"
33+
// altimate_change start — telemetry: the command's project directory for the config opt-out
34+
import path from "path"
35+
import { resolveThreadDirectory } from "./cli/cmd/tui"
36+
// altimate_change end
3337
import { AcpCommand } from "./cli/cmd/acp"
3438
import { EOL } from "os"
3539
import { WebCommand } from "./cli/cmd/web"
@@ -188,6 +192,15 @@ let cli = yargs(args)
188192
// `debug bundle --no-network` promises no network access; telemetry would send its events.
189193
// Any form of "no network" counts (`--no-network`, `--network=false`, `--network false`), as parsed by yargs.
190194
const noNetwork = firstPositional === "debug" && (opts as { network?: unknown }).network === false
195+
// The command changes into its project only after this; the config opt-out is read from there.
196+
const target = opts as { dir?: unknown; project?: unknown; attach?: unknown }
197+
Telemetry.setConfigDirectory(
198+
(firstPositional === "attach" || (firstPositional === "run" && !target.attach)) && typeof target.dir === "string"
199+
? path.resolve(target.dir)
200+
: !CLI_COMMAND_NAMES.has(firstPositional) && typeof target.project === "string"
201+
? resolveThreadDirectory(target.project)
202+
: undefined,
203+
)
191204
if (!noNetwork) Telemetry.init().catch(() => {})
192205
// altimate_change end
193206
})

‎packages/opencode/test/altimate/telemetry/config-state.test.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
2-
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs"
2+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"
33
import os from "os"
44
import path from "path"
55
import { Global } from "../../../src/global"
@@ -8,17 +8,28 @@ import { TelemetryConfig } from "../../../src/altimate/telemetry/config-state"
88
describe("TelemetryConfig.disabledState (no Instance)", () => {
99
let dir: string
1010
let savedContent: string | undefined
11+
// The preload points the global config at a per-run temp directory; other suites may have
12+
// seeded these files there, so each test puts back what it found.
1113
const globalFile = () => path.join(Global.Path.config, "altimate-code.json")
14+
const legacyFile = () => path.join(Global.Path.config, "config")
15+
const savedFiles = new Map<string, string | undefined>()
1216

1317
beforeEach(() => {
1418
dir = mkdtempSync(path.join(os.tmpdir(), "telemetry-config-state-"))
1519
savedContent = process.env.OPENCODE_CONFIG_CONTENT
1620
delete process.env.OPENCODE_CONFIG_CONTENT
21+
for (const file of [globalFile(), legacyFile()]) {
22+
savedFiles.set(file, existsSync(file) ? readFileSync(file, "utf-8") : undefined)
23+
rmSync(file, { force: true })
24+
}
1725
})
1826
afterEach(() => {
1927
if (savedContent === undefined) delete process.env.OPENCODE_CONFIG_CONTENT
2028
else process.env.OPENCODE_CONFIG_CONTENT = savedContent
21-
rmSync(globalFile(), { force: true })
29+
for (const [file, text] of savedFiles) {
30+
if (text === undefined) rmSync(file, { force: true })
31+
else writeFileSync(file, text)
32+
}
2233
rmSync(dir, { recursive: true, force: true })
2334
})
2435

@@ -31,6 +42,18 @@ describe("TelemetryConfig.disabledState (no Instance)", () => {
3142
expect(await TelemetryConfig.disabledState(dir)).toBe("disabled")
3243
})
3344

45+
test("the legacy TOML global config turns it off, and a broken one is unreadable", async () => {
46+
writeFileSync(legacyFile(), "[telemetry]\ndisabled = true\n")
47+
expect(await TelemetryConfig.disabledState(dir)).toBe("disabled")
48+
writeFileSync(legacyFile(), "[telemetry\ndisabled = \n")
49+
expect(await TelemetryConfig.disabledState(dir)).toBe("unreadable")
50+
})
51+
52+
test("a value Config's schema would reject is unreadable, not enabled", async () => {
53+
writeFileSync(globalFile(), JSON.stringify({ telemetry: { disabled: 0 } }))
54+
expect(await TelemetryConfig.disabledState(dir)).toBe("unreadable")
55+
})
56+
3457
test("a project's .altimate-code directory turns it off", async () => {
3558
mkdirSync(path.join(dir, ".altimate-code"))
3659
writeFileSync(path.join(dir, ".altimate-code", "altimate-code.json"), '{ "telemetry": { "disabled": true } }')

‎packages/opencode/test/altimate/telemetry/opt-out.test.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -311,9 +311,10 @@ describe("telemetry opt-out marker", () => {
311311
process.env.ALTIMATE_TELEMETRY_FORCE = "true"
312312
await Telemetry.shutdown()
313313
await Telemetry.init()
314-
await new Promise((r) => setTimeout(r, 100))
314+
await new Promise((r) => setTimeout(r, 100)) // nothing to wait for: the force check returns first
315315
expect(trackPosts()).toHaveLength(0)
316316
expect(OptOutMarker.exists()).toBe(false)
317+
expect(existsSync(path.join(home, ".altimate", "telemetry-opted-out.sending"))).toBe(false)
317318
})
318319

319320
test("two disabled inits while the first send is in flight send the event once", async () => {
@@ -366,6 +367,40 @@ describe("telemetry opt-out marker", () => {
366367
expect(OptOutMarker.exists()).toBe(false)
367368
})
368369

370+
test("telemetry turned back on in another process stops an in-flight send from writing the marker", async () => {
371+
writeMachineId()
372+
let release: () => void = () => {}
373+
holdTrack = new Promise<void>((r) => (release = r))
374+
process.env.ALTIMATE_TELEMETRY_DISABLED = "1"
375+
await Telemetry.shutdown()
376+
await Telemetry.init()
377+
expect(await waitFor(() => trackPosts().length === 1)).toBe(true)
378+
OptOutMarker.clear() // what an enabled init in another process does
379+
release()
380+
await new Promise((r) => setTimeout(r, 100))
381+
expect(OptOutMarker.exists()).toBe(false)
382+
})
383+
384+
test("an init without an Instance reads the opt-out from the command's project directory", async () => {
385+
writeMachineId()
386+
const project = mkdtempSync(path.join(os.tmpdir(), "telemetry-opt-out-project-"))
387+
mkdirSync(path.join(project, ".altimate-code"))
388+
writeFileSync(path.join(project, ".altimate-code", "altimate-code.json"), '{ "telemetry": { "disabled": true } }')
389+
const configSpy = spyOn(Config, "get").mockRejectedValue(new Error("InstanceRef not provided"))
390+
try {
391+
Telemetry.setConfigDirectory(project)
392+
await Telemetry.shutdown()
393+
await Telemetry.init()
394+
expect(Telemetry.isEnabled()).toBe(false)
395+
expect(await waitFor(() => optOuts().length === 1)).toBe(true)
396+
expect(optOuts()[0].data.baseData.properties.opt_out_source).toBe("config")
397+
} finally {
398+
Telemetry.setConfigDirectory(undefined)
399+
configSpy.mockRestore()
400+
rmSync(project, { recursive: true, force: true })
401+
}
402+
})
403+
369404
test("the marker creates a missing ~/.altimate owner-only", () => {
370405
expect(existsSync(path.join(home, ".altimate"))).toBe(false)
371406
OptOutMarker.write()

0 commit comments

Comments
 (0)