Skip to content

Commit 6828ef1

Browse files
sahrizviclaude
andcommitted
fix(onboarding): scope gateway events, guard the catalogue, fix Marker Guard
Marker Guard was red on `3875d00`, and the root cause was in the comment that warns about this exact trap: the prose at `cli/cmd/tui.ts` spelled the closing marker out literally, and the parser matches that token in comment text — so the enclosing region closed on that line and everything after it was reported as unmarked. Reworded, plus start/end pairs added around six multi-line additions that only carried a single-line marker. `analyze.ts --markers --strict` is clean. The four remaining findings from the class-scoped `codex` sweep, all of which this PR introduced (none of these symbols exist at the merge-base): - `plugin/altimate.ts`: gateway events fired for every `authorize()`, so routine `/auth`, `/connect` and reauthentication all emitted onboarding-taxonomy events. They could not be gated on `funnelStarted` because the flow runs in the worker and the funnel opens on the main thread. The TUI now tells the worker through a new `onboardingStarted` RPC, and the four emits are gated on it. In `serve` / `run` / `github` there is no first-run funnel, so they correctly stay silent. - `plugin/altimate.ts`: the per-attempt outcome latch was a boolean, so two callbacks exchanging the same one-time token let the one that failed fast claim it and report `gateway_auth_failed` while the other saved valid credentials — connected user, failed funnel. Tri-state now; success is authoritative. - `dialog-model.tsx`: the catalogue had no submit latch (`DialogSelect.submit()` has none of its own) and recorded the choice before awaiting an async provider action, so a second Enter emitted `provider_selected` twice and started a second authorization flow. The curated picker has this latch; the catalogue did not. - `dialog-model.tsx`: the "Other" row recorded a selection before `promptCustomProviderID()` resolved, so cancelling that prompt still produced a `provider_selected` classified as `other` with no provider behind it. - `dialog-provider.tsx`: `firstRunActive` had no clear on the one path where the user is genuinely onboarded but `markSetupComplete()` never runs — gateway connected with no usable model. Added `clearFirstRunActive()` as that catalogue's close handler. Ordinary dismissals deliberately keep the flag: a user who has set nothing up is still mid-first-run. Not addressed, and not ours: per-session `Telemetry.shutdown()` is unsafe with concurrent sessions (session A's shutdown disables telemetry under session B). `Telemetry.shutdown` in `session/prompt.ts` predates this branch. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_018SLUQF3xgZHsGZHSjxe7vb
1 parent 3875d00 commit 6828ef1

8 files changed

Lines changed: 125 additions & 20 deletions

File tree

‎packages/opencode/src/altimate/plugin/altimate.ts‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,8 @@ export async function AltimateAuthPlugin(_input: PluginInput): Promise<Hooks> {
318318
try {
319319
await startCallbackServer()
320320
} catch (err) {
321-
void OnboardingTelemetry.emit({ type: "gateway_auth_failed", reason: "error" })
321+
if (OnboardingTelemetry.isFunnelActive())
322+
void OnboardingTelemetry.emit({ type: "gateway_auth_failed", reason: "error" })
322323
throw err
323324
}
324325
// altimate_change end
@@ -362,12 +363,19 @@ export async function AltimateAuthPlugin(_input: PluginInput): Promise<Hooks> {
362363
// attempted". open() failures are swallowed above (the URL is also printed for the
363364
// user to paste), so this fires even when no browser actually launched.
364365
// The URL is never sent — it carries the CSRF `state`.
365-
void OnboardingTelemetry.emit({ type: "gateway_device_code_issued" })
366+
if (OnboardingTelemetry.isFunnelActive()) void OnboardingTelemetry.emit({ type: "gateway_device_code_issued" })
366367

367368
// One outcome per attempt. callback() closes over `result` and re-runs its whole body
368369
// on every invocation, so a repeated call would otherwise re-emit completion/failure
369370
// (and re-report a connect time measured from the original attempt).
370-
let outcomeReported = false
371+
//
372+
// Tri-state rather than a boolean because concurrent invocations race for it and a
373+
// plain latch let the WRONG one win: two callbacks exchanging the same one-time token
374+
// means one fails fast, claims the latch, and reports gateway_auth_failed while the
375+
// other goes on to save valid credentials — the user is connected and the funnel says
376+
// they are not. Success is authoritative, so it emits even after a failure was
377+
// reported; failure only reports when nothing else has.
378+
let outcome: "none" | "failed" | "completed" = "none"
371379
// altimate_change end
372380

373381
return {
@@ -399,8 +407,8 @@ export async function AltimateAuthPlugin(_input: PluginInput): Promise<Hooks> {
399407
// callback server and browser open, both of which are part of the wait the user
400408
// actually experiences — and lives in this attempt's closure, so a concurrent
401409
// attempt cannot overwrite it.
402-
if (!outcomeReported) {
403-
outcomeReported = true
410+
if (outcome !== "completed" && OnboardingTelemetry.isFunnelActive()) {
411+
outcome = "completed"
404412
void OnboardingTelemetry.emit({ type: "gateway_auth_completed" })
405413
void OnboardingTelemetry.emit({
406414
type: "instance_connected",
@@ -416,8 +424,8 @@ export async function AltimateAuthPlugin(_input: PluginInput): Promise<Hooks> {
416424
// altimate_change — onboarding funnel: only the classified enum is sent. The
417425
// message can embed the instance name (see the invalid-instance throw above),
418426
// so it never reaches telemetry.
419-
if (!outcomeReported) {
420-
outcomeReported = true
427+
if (outcome === "none" && OnboardingTelemetry.isFunnelActive()) {
428+
outcome = "failed"
421429
void OnboardingTelemetry.emit({ type: "gateway_auth_failed", reason: reasonOf(err) })
422430
}
423431
return { type: "failed" }

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,29 @@ export function consumeCommandSubmission(sessionID: string): boolean {
279279
return true
280280
}
281281

282+
/**
283+
* Mark this THREAD as being inside a first run.
284+
*
285+
* The gateway auth flow (plugin/altimate.ts) emits funnel events from the worker, where
286+
* `funnelStarted` is always false — `onboarding_started` is emitted on the main thread and the
287+
* two threads are separate module instances. Gating those emits on `funnelStarted` would have
288+
* silenced them entirely, so they were left ungated and fired for routine `/auth`, `/connect`
289+
* and reauthentication too: onboarding-taxonomy events from returning users, which is the exact
290+
* contamination the funnel gates exist to prevent.
291+
*
292+
* The TUI calls the worker's `onboardingStarted` RPC when the first-run gate opens, which lands
293+
* here. In non-TUI hosts (`serve`, `run`, `github`) there is no first-run funnel, so this stays
294+
* false and the gateway events correctly do not fire.
295+
*/
296+
export function markFunnelActive() {
297+
funnelStarted = true
298+
}
299+
300+
/** Whether this thread has been told a first run is in progress. */
301+
export function isFunnelActive() {
302+
return funnelStarted
303+
}
304+
282305
export function markOnboardingSession(sessionID: string) {
283306
record(sessionID).onboarding = true
284307
}

‎packages/opencode/src/cli/cmd/tui.ts‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,12 +136,13 @@ export const TuiThreadCommand = cmd({
136136
}
137137
const cwd = Filesystem.resolve(process.cwd())
138138

139-
// altimate_change — hand the launch correlation id to the worker explicitly. A Bun Worker
140-
// does not see runtime mutations to process.env, so without this the worker mints its own
141-
// and the TUI-thread and worker-thread halves of the onboarding funnel cannot be joined.
139+
// altimate_change start — hand the launch correlation id to the worker explicitly. A Bun
140+
// Worker does not see runtime mutations to process.env, so without this the worker mints its
141+
// own and the TUI-thread and worker-thread halves of the onboarding funnel cannot be joined.
142142
const worker = new Worker(file, {
143143
env: { ...process.env, ALTIMATE_LAUNCH_ID: Telemetry.launchId() },
144144
} as WorkerOptions)
145+
// altimate_change end
145146
const client = Rpc.client<typeof rpc>(worker)
146147
const reload = () => {
147148
client.call("reload", undefined).catch(() => {})
@@ -153,7 +154,10 @@ export const TuiThreadCommand = cmd({
153154
if (stopped) return
154155
stopped = true
155156
process.off("SIGUSR2", reload)
157+
// altimate_change start — budget shared with the worker's own flush deadline, so the two
158+
// halves cannot drift apart and truncate the worker's telemetry buffer.
156159
await withTimeout(client.call("shutdown", undefined), Telemetry.TUI_SHUTDOWN_BUDGET_MS).catch(() => {})
160+
// altimate_change end
157161
worker.terminate()
158162
}
159163

@@ -215,8 +219,10 @@ export const TuiThreadCommand = cmd({
215219
pluginHost: createLegacyTuiPluginHost(),
216220
// altimate_change — onboarding funnel seam. Deliberately a single-line marker, not a
217221
// start/end pair: this sits inside the "clean up TUI worker after failed --session
218-
// validation" region, and a nested `altimate_change end` truncates the block that
219-
// test/cli/tui/command.test.ts slices to assert cleanup ordering.
222+
// validation" region, and a nested closing marker truncates the block that
223+
// test/cli/tui/command.test.ts slices to assert cleanup ordering. (Do not spell that
224+
// marker out in prose here either — the parser matches the token in comment text and
225+
// would close the region on this very line.)
220226
//
221227
// The TUI renders on this thread, so
222228
// this reaches the main-process Telemetry module directly (already initialized by the
@@ -230,6 +236,14 @@ export const TuiThreadCommand = cmd({
230236
// itself runs in the worker and cannot reach this thread's abandonment state.
231237
onTelemetry: (event) => {
232238
const { name, ...props } = event
239+
// The gateway auth flow emits from the WORKER, which cannot see this thread's
240+
// funnel state. Tell it once, when the funnel opens, so those events are scoped to a
241+
// real first run instead of firing for every /auth. (No nested marker pair here —
242+
// see the note above.)
243+
if (name === "onboarding_started") {
244+
OnboardingTelemetry.markFunnelActive()
245+
client.call("onboardingStarted", undefined).catch(() => {})
246+
}
233247
if (name === "provider_selected") {
234248
// Classify here, not in the TUI: a provider a user declared in their own config
235249
// can be named after their company, so the raw id is only forwarded when it is on

‎packages/opencode/src/cli/tui/worker.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import { TraceConsumer } from "@/altimate/observability/trace-consumer"
2626
import { Instance } from "@/project/instance"
2727
// altimate_change — onboarding telemetry: flush this thread's buffer in rpc.shutdown()
2828
import { Telemetry } from "@/altimate/telemetry"
29+
import * as OnboardingTelemetry from "@/altimate/telemetry/onboarding"
2930

3031
// altimate_change — shared with the withTimeout budget in cli/cmd/tui.ts stop(), so the coupling
3132
// is enforced by the compiler rather than by a comment.
@@ -101,6 +102,13 @@ export const rpc = {
101102
})
102103
// altimate_change end
103104
},
105+
// altimate_change start — onboarding funnel: the TUI owns the first-run decision and this thread
106+
// runs the gateway auth flow, so it has to be told. Without it the gateway events cannot tell a
107+
// first run from a routine /auth. See telemetry/onboarding.ts markFunnelActive().
108+
async onboardingStarted() {
109+
OnboardingTelemetry.markFunnelActive()
110+
},
111+
// altimate_change end
104112
async reload() {
105113
await AppRuntime.runPromise(
106114
Effect.gen(function* () {
@@ -111,8 +119,9 @@ export const rpc = {
111119
)
112120
},
113121
async shutdown() {
114-
// altimate_change — cli/cmd/tui.ts allows this RPC 5s before worker.terminate().
122+
// altimate_change start — cli/cmd/tui.ts allows this RPC 5s before worker.terminate().
115123
const shutdownStartedAt = Date.now()
124+
// altimate_change end
116125
// altimate_change start — trace: drain pending events (bounded), then finalize SYNCHRONOUSLY.
117126
// On a quiet Bun Worker thread, pending async fs writes from the consumer don't flush before
118127
// worker.terminate(), so an async flush() silently writes nothing; flushSync() uses writeFileSync.

‎packages/tui/src/app.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,13 @@ import { UPGRADE_KV_KEY } from "./component/upgrade-indicator-utils"
99
// altimate_change end
1010
import { ClipboardProvider, useClipboard } from "./context/clipboard"
1111
import { ExitProvider, useExit } from "./context/exit"
12-
// altimate_change — onboarding funnel telemetry seam
12+
// altimate_change start — onboarding funnel telemetry seam
1313
import {
1414
OnboardingTelemetryProvider,
1515
useOnboardingTelemetry,
1616
type TrackOnboarding,
1717
} from "./context/onboarding-telemetry"
18+
// altimate_change end
1819
import { EpilogueProvider } from "./context/epilogue"
1920
import * as Selection from "./util/selection"
2021
import { createCliRenderer, MouseButton, type CliRenderer } from "@opentui/core"
@@ -165,9 +166,10 @@ export type TuiInput = {
165166
headers?: RequestInit["headers"]
166167
events?: EventSource
167168
pluginHost: TuiPluginHost
168-
// altimate_change — onboarding funnel telemetry, injected by the host (packages/tui cannot
169+
// altimate_change start — onboarding funnel telemetry, injected by the host (packages/tui cannot
169170
// reach the Telemetry module). Optional: absent means no tracking, not an error.
170171
onTelemetry?: TrackOnboarding
172+
// altimate_change end
171173
}
172174

173175
function errorMessage(error: unknown) {

‎packages/tui/src/component/altimate-onboarding.tsx‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,20 @@ const [firstRunActive, setFirstRunActive] = createSignal(false)
3030
export function markFirstRunActive() {
3131
setFirstRunActive(true)
3232
}
33+
/**
34+
* Clear without marking setup complete.
35+
*
36+
* Needed for exactly one shape: the user HAS credentials but never chose a model, so
37+
* markSetupComplete() — the normal clear — will not run. The gateway's connected-but-no-usable-
38+
* model branch is the real instance (dialog-provider.tsx). Leaving the flag set there made later
39+
* routine /model use emit funnel events for the rest of the session.
40+
*
41+
* NOT for ordinary dismissals. A user who closes the picker without setting anything up is still
42+
* mid-first-run, and their next provider pick genuinely is the onboarding one.
43+
*/
44+
export function clearFirstRunActive() {
45+
setFirstRunActive(false)
46+
}
3347
export function useFirstRunActive() {
3448
return firstRunActive
3549
}

‎packages/tui/src/component/dialog-model.tsx‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,17 @@ import { useSync } from "../context/sync"
44
import { map, pipe, flatMap, entries, filter, sortBy } from "remeda"
55
import { DialogSelect } from "../ui/dialog-select"
66
import { useDialog } from "../ui/dialog"
7-
import { createDialogProviderOptions, DialogProvider, WARNLIST, PROVIDER_PRIORITY } from "./dialog-provider"
7+
// altimate_change start — PROVIDER_PRIORITY orders the READY section like the curated picker;
8+
// CUSTOM_PROVIDER_OPTION_VALUE identifies the "Other" row, which must not record a provider
9+
// choice before the user has supplied one.
10+
import {
11+
createDialogProviderOptions,
12+
DialogProvider,
13+
WARNLIST,
14+
PROVIDER_PRIORITY,
15+
CUSTOM_PROVIDER_OPTION_VALUE,
16+
} from "./dialog-provider"
17+
// altimate_change end
818
import { DialogVariant } from "./dialog-variant"
919
import * as fuzzysort from "fuzzysort"
1020
import { useConnected } from "./use-connected"
@@ -39,6 +49,12 @@ export function DialogModel(props: {
3949

4050
const connected = useConnected()
4151
const providers = createDialogProviderOptions()
52+
// altimate_change — one-shot submit latch. DialogSelect.submit() has no guard of its own, and
53+
// the NEEDS-SETUP rows record the choice and THEN await an async provider action, so a second
54+
// Enter (or a mouse-up landing during the await) emitted provider_selected twice and started a
55+
// second authorization flow. The curated picker has the same latch; this catalogue is one
56+
// dialog further on and had none.
57+
let activated = false
4258

4359
// A provider is "ready" (usable now) when it has valid credentials: it is present
4460
// in the live provider list with at least one model — and, for the free OpenCode
@@ -78,6 +94,8 @@ export function DialogModel(props: {
7894
category: "READY",
7995
footer: isFav ? "★" : undefined,
8096
onSelect() {
97+
if (activated) return
98+
activated = true
8199
// altimate_change — go through the shared onSelect(providerID, modelID)
82100
// helper so a ready pick also honors the model-variant follow-up flow,
83101
// and mark setup complete so the first-run chat lock lifts.
@@ -130,7 +148,14 @@ export function DialogModel(props: {
130148
// search path was added to capture. Emitted before the auth flow runs, matching the
131149
// documented promise that a sign-in later cancelled still counts as a selection.
132150
onSelect: () => {
133-
if (firstRunActive()) {
151+
if (activated) return
152+
activated = true
153+
// The "Other" row prompts for a provider id and the user can cancel it, so there
154+
// is no choice to record yet — emitting here classified an abandoned prompt as a
155+
// real `other` selection. Every other row dispatches a concrete provider, where
156+
// recording before the auth flow is deliberate (a sign-in later cancelled still
157+
// counts as a selection).
158+
if (firstRunActive() && o.value !== CUSTOM_PROVIDER_OPTION_VALUE) {
134159
trackOnboarding({
135160
name: "provider_selected",
136161
providerID: o.value,
@@ -147,6 +172,8 @@ export function DialogModel(props: {
147172
category: "NEEDS SETUP",
148173
footer: undefined as string | undefined,
149174
async onSelect() {
175+
if (activated) return
176+
activated = true
150177
// altimate_change — Big Pickle reached through the catalogue emitted its confirm
151178
// events but never a provider_selected, so the choice was invisible.
152179
if (firstRunActive()) {

‎packages/tui/src/component/dialog-provider.tsx‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import { useClipboard } from "../context/clipboard"
1818
import { useLocal } from "../context/local"
1919
// altimate_change — mark first-run setup complete once the gateway sign-in succeeds
2020
// (used by AutoMethod below); flips useReady() so the first-run chat lock lifts.
21-
import { markSetupComplete } from "./altimate-onboarding"
21+
import { markSetupComplete, clearFirstRunActive } from "./altimate-onboarding"
2222

2323
export const PROVIDER_PRIORITY: Record<string, number> = {
2424
// altimate_change start — Part 1 onboarding: Altimate LLM Gateway is the
@@ -43,7 +43,7 @@ export const WARNLIST: Record<string, string> = {
4343
}
4444
// altimate_change end
4545

46-
const CUSTOM_PROVIDER_OPTION_VALUE = "__opencode_custom_provider__"
46+
export const CUSTOM_PROVIDER_OPTION_VALUE = "__opencode_custom_provider__"
4747
const CUSTOM_PROVIDER_ID = /^[a-z0-9][a-z0-9-_]*$/
4848

4949
type ProviderOptionBase = {
@@ -417,7 +417,15 @@ function AutoMethod(props: AutoMethodProps) {
417417
message: "Connected, but no model is available yet — pick one to start.",
418418
variant: "warning",
419419
})
420-
dialog.replace(() => <DialogModel providerID={props.providerID} />)
420+
// altimate_change — funnel: credentials landed, so the first run is effectively over
421+
// even though no model was chosen and markSetupComplete() will never run. Without this
422+
// the firstRunActive flag stays set for the session and every later /model pick is
423+
// recorded as an onboarding provider choice. The gateway choice itself was already
424+
// recorded when the user picked it.
425+
dialog.replace(
426+
() => <DialogModel providerID={props.providerID} />,
427+
() => clearFirstRunActive(),
428+
)
421429
return
422430
}
423431
local.model.set({ providerID: props.providerID, modelID: model }, { recent: true })

0 commit comments

Comments
 (0)