Skip to content

Commit 7c7e17f

Browse files
sahrizviclaude
andcommitted
feat: add Workspaces post-scan prompt + altimate link subcommand
Adds the CLI half of the Workspaces pilot: after the first-run scan completes and the CLI is authenticated with Altimate, prompt the user once to create a new workspace or attach the project to an existing one. The link is a direct authenticated call — no device flow — and the browser opens after create so the user can configure integrations / knowledge in the SaaS. Fork-owned TuiPlugin per docs/internal/2026-06-23-tui-fork-features- as-plugins-adr.md: single file at `packages/opencode/src/plugin/tui/altimate/workspace.tsx`, added to the existing `altimateTuiPlugins()` aggregator. Upstream `packages/tui/**` stays byte-for-byte upstream. Uses the real `api.ui.*` / `api.keymap.registerLayer` / `api.state.path.directory` / `api.kv` (persistent) surface. Shared modules under `packages/opencode/src/altimate/workspace/` so the plugin and the `altimate link` subcommand can't drift on request shape or error handling: - `api-client.ts` — typed errors (Conflict/Precondition/NotFound/ Forbidden/NotConfigured/Api), FastAPI `{"detail": {...}}` parsing, 15s abort timeout, credentials re-read on every call so an account switch is picked up without restart. - `detect.ts` — `detectProjectRemote` + `projectNameFromRemote`; reuses `stripGitRemoteCredentials` (now exported from `project-scan.ts` so the two callers can't drift). - `state.ts` — local binding cache scoped to (tenant, apiUrl) with atomic write + post-write `chmod 0o600` + corruption recovery. Trigger: `onboarding-telemetry.ts` `tool.execute.after` hook publishes `TuiEvent.CommandExecute` with `"altimate.workspace.postScan"` when `project_scan` completes, gated on the new `Flag.ALTIMATE_WORKSPACE` and `AltimateApi.isConfigured()` (BYOK users are silently skipped — no place to send them). Never blocks onboarding on a publish failure. Server-authoritative pre-check via `GET /datamate-project-bindings/ by-remote`; local cache used only as an offline fallback, and the fallback path renders a mandatory "unverified" banner rather than silently trusting stale data. Browser-open failure surfaces a copyable-URL toast rather than swallowing silently. 7-day Skip latch lives in `api.kv` keyed by SHA-1(remote) — UTC rolling window; `altimate link` (user-initiated) deliberately bypasses the latch. New `altimate-code link` subcommand runs the same three-way flow outside a TUI session via `@clack/prompts` for scripting / catch-up after a Skip. Bails early with helpful messages when credentials are missing or no git remote is set. Tests: 17 unit tests covering project-name parsing, git detection graceful failure, cache read/write + chmod + tenant-scoping (account- switch invalidation), and Skip latch TTL semantics with UTC boundary. Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_01Q8FGy89Qpr39k8nCSpCcK2
1 parent 54a8f32 commit 7c7e17f

11 files changed

Lines changed: 1398 additions & 2 deletions

File tree

‎packages/core/src/flag/flag.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,14 @@ export const Flag = {
6363
OPENCODE_WORKSPACE_ID: process.env["OPENCODE_WORKSPACE_ID"],
6464
OPENCODE_EXPERIMENTAL_WORKSPACES: enabledByExperimental("OPENCODE_EXPERIMENTAL_WORKSPACES"),
6565

66+
// altimate_change start — pilot flag for the Workspaces feature (post-scan prompt +
67+
// altimate link subcommand). Read as a getter so tests and the runtime `--` middleware
68+
// can flip it between plugin activation and command execution.
69+
get ALTIMATE_WORKSPACE() {
70+
return enabledByExperimental("ALTIMATE_WORKSPACE")
71+
},
72+
// altimate_change end
73+
6674
// Evaluated at access time (not module load) because tests, the CLI, and
6775
// external tooling set these env vars at runtime.
6876
get OPENCODE_DISABLE_PROJECT_CONFIG() {

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,16 @@
1212
// session loop.
1313
import type { Hooks, PluginInput } from "@opencode-ai/plugin"
1414
import * as OnboardingTelemetry from "../telemetry/onboarding"
15+
// altimate_change start — AI-8398 workspaces trigger. Reaches into the same
16+
// EventV2 bridge the server/routes/tui.ts uses to publish TuiEvent.CommandExecute
17+
// so the workspace TuiPlugin (packages/opencode/src/plugin/tui/altimate/workspace.tsx)
18+
// runs its post-scan flow. Feature-flagged via Flag.ALTIMATE_WORKSPACE.
19+
import { Flag } from "@opencode-ai/core/flag/flag"
20+
import { AltimateApi } from "@/altimate/api/client"
21+
import { AppRuntime } from "@/effect/app-runtime"
22+
import { EventV2Bridge } from "@/event-v2-bridge"
23+
import { TuiEvent } from "@/server/tui-event"
24+
// altimate_change end
1525

1626
const ONBOARD_CONNECT = "onboard-connect"
1727

@@ -134,6 +144,28 @@ export async function OnboardingTelemetryPlugin(_input: PluginInput): Promise<Ho
134144
},
135145
input.sessionID,
136146
)
147+
// altimate_change start — AI-8398 workspaces post-scan prompt trigger.
148+
// Fires the TUI plugin's altimate.workspace.postScan command once the scan
149+
// completes AND the CLI has real Altimate credentials (BYOK users skip this
150+
// path entirely — no place to send them). All the state (Skip latch, cache,
151+
// server pre-check) is plugin-side so the trigger stays a fire-and-forget
152+
// signal here; a retry would just re-enter the plugin's idempotent runFlow.
153+
if (Flag.ALTIMATE_WORKSPACE && (await AltimateApi.isConfigured().catch(() => false))) {
154+
void AppRuntime.runPromise(
155+
EventV2Bridge.Service.use((events) =>
156+
events.publish(TuiEvent.CommandExecute, {
157+
command: "altimate.workspace.postScan",
158+
}),
159+
),
160+
).catch((err) => {
161+
// Never block onboarding on a publish failure — worst case the
162+
// user picks up the workspace on their next launch or via the
163+
// /altimate.workspace.link palette command.
164+
// eslint-disable-next-line no-console
165+
console.error("[altimate-workspace] postScan trigger failed:", err)
166+
})
167+
}
168+
// altimate_change end
137169
return
138170
}
139171

‎packages/opencode/src/altimate/tools/project-scan.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,8 +173,13 @@ export async function detectGit(): Promise<GitInfo> {
173173
* SSH-form remotes (`[email protected]:owner/repo.git`) have no userinfo
174174
* concept and are left untouched. URLs we can't parse are dropped to
175175
* undefined (better to lose the breadcrumb than leak creds).
176+
*
177+
* Exported so the workspace TuiPlugin (packages/opencode/src/plugin/tui/
178+
* altimate/workspace.tsx) can reuse the exact same scrubbing rules when
179+
* deriving the project's git remote for the post-scan prompt — the alt
180+
* of duplicating the logic risks the two callers drifting.
176181
*/
177-
function stripGitRemoteCredentials(url: string): string | undefined {
182+
export function stripGitRemoteCredentials(url: string): string | undefined {
178183
if (!url) return undefined
179184
// SSH form: `git@host:path` — no creds to strip.
180185
if (/^[\w.-]+@[\w.-]+:/.test(url) && !url.includes("://")) return url
Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
// altimate_change - new file
2+
//
3+
// Wire client for the workspace-binding endpoints in altimate-backend
4+
// (/datamate-project-bindings/*, added by AI-8398). Shared between the TUI
5+
// plugin (packages/opencode/src/plugin/tui/altimate/workspace.tsx) and the
6+
// `altimate link` CLI subcommand (packages/opencode/src/cli/cmd/link.ts) so
7+
// the two entry points can't drift on request shape / error handling.
8+
//
9+
// Reads AltimateApi credentials on every call so an account switch is picked
10+
// up immediately without a plugin restart. All FastAPI HTTPException.detail
11+
// bodies come out as `{"detail": <string|object>}` — we parse the object form
12+
// for 409/412 and surface it as a typed error rather than a bare status code.
13+
import { AltimateApi } from "@/altimate/api/client"
14+
15+
const REQUEST_TIMEOUT_MS = 15_000
16+
17+
export interface DatamateRef {
18+
id: number
19+
name: string
20+
}
21+
22+
export interface Binding {
23+
id: number
24+
datamate_id: number
25+
datamate_name: string
26+
repo_remote: string
27+
created_at?: string
28+
}
29+
30+
export interface CreateAndBindResponse {
31+
datamate: DatamateRef
32+
binding: Binding
33+
manage_url: string
34+
}
35+
36+
export interface BindingResponse {
37+
binding: Binding
38+
}
39+
40+
export interface GetBindingResponse {
41+
binding: Binding
42+
datamate: DatamateRef
43+
}
44+
45+
export interface ConflictDetail {
46+
message: string
47+
existing_datamate_id?: number
48+
existing_datamate_name?: string | null
49+
repo_remote?: string
50+
}
51+
52+
export interface PreconditionDetail {
53+
message: string
54+
actual_current_datamate_id?: number
55+
expected_current_datamate_id?: number
56+
}
57+
58+
export class NotConfiguredError extends Error {
59+
constructor() {
60+
super("Altimate credentials not configured — sign in first.")
61+
this.name = "NotConfiguredError"
62+
}
63+
}
64+
65+
export class ConflictError extends Error {
66+
constructor(public readonly detail: ConflictDetail) {
67+
super(detail.message)
68+
this.name = "ConflictError"
69+
}
70+
}
71+
72+
export class PreconditionFailedError extends Error {
73+
constructor(public readonly detail: PreconditionDetail) {
74+
super(detail.message)
75+
this.name = "PreconditionFailedError"
76+
}
77+
}
78+
79+
export class NotFoundError extends Error {
80+
constructor(msg = "Not found") {
81+
super(msg)
82+
this.name = "NotFoundError"
83+
}
84+
}
85+
86+
export class ForbiddenError extends Error {
87+
constructor(msg = "Forbidden") {
88+
super(msg)
89+
this.name = "ForbiddenError"
90+
}
91+
}
92+
93+
export class WorkspaceApiError extends Error {
94+
constructor(
95+
msg: string,
96+
public readonly status?: number,
97+
) {
98+
super(msg)
99+
this.name = "WorkspaceApiError"
100+
}
101+
}
102+
103+
async function creds(): Promise<{ url: string; instance: string; apiKey: string }> {
104+
if (!(await AltimateApi.isConfigured())) throw new NotConfiguredError()
105+
const c = await AltimateApi.getCredentials()
106+
return { url: c.altimateUrl, instance: c.altimateInstanceName, apiKey: c.altimateApiKey }
107+
}
108+
109+
async function req<T>(
110+
method: string,
111+
subpath: string,
112+
opts: { body?: unknown; query?: Record<string, string> } = {},
113+
): Promise<T> {
114+
const { url, instance, apiKey } = await creds()
115+
const qs = opts.query ? "?" + new URLSearchParams(opts.query).toString() : ""
116+
const target = `${url}/datamate-project-bindings${subpath}${qs}`
117+
const controller = new AbortController()
118+
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
119+
let res: Response
120+
try {
121+
res = await fetch(target, {
122+
method,
123+
headers: {
124+
"Content-Type": "application/json",
125+
Authorization: `Bearer ${apiKey}`,
126+
"x-tenant": instance,
127+
},
128+
signal: controller.signal,
129+
...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),
130+
})
131+
} catch (err) {
132+
const msg = err instanceof Error ? err.message : String(err)
133+
throw new WorkspaceApiError(`Cannot reach ${target}: ${msg}`)
134+
} finally {
135+
clearTimeout(timeout)
136+
}
137+
let json: unknown = undefined
138+
const text = await res.text().catch(() => "")
139+
if (text) {
140+
try {
141+
json = JSON.parse(text)
142+
} catch {
143+
/* non-JSON body — surface as opaque via status code below */
144+
}
145+
}
146+
const detail = (json as { detail?: unknown } | undefined)?.detail
147+
if (res.status === 404) throw new NotFoundError(typeof detail === "string" ? detail : "Not found")
148+
if (res.status === 403) throw new ForbiddenError(typeof detail === "string" ? detail : "Forbidden")
149+
if (res.status === 409) {
150+
const d =
151+
typeof detail === "object" && detail !== null
152+
? (detail as ConflictDetail)
153+
: { message: typeof detail === "string" ? detail : "Conflict" }
154+
throw new ConflictError(d)
155+
}
156+
if (res.status === 412) {
157+
const d =
158+
typeof detail === "object" && detail !== null
159+
? (detail as PreconditionDetail)
160+
: { message: typeof detail === "string" ? detail : "Precondition failed" }
161+
throw new PreconditionFailedError(d)
162+
}
163+
if (!res.ok) {
164+
throw new WorkspaceApiError(
165+
typeof detail === "string" ? detail : `Request failed with status ${res.status}`,
166+
res.status,
167+
)
168+
}
169+
return json as T
170+
}
171+
172+
export namespace WorkspaceApi {
173+
/** Server-authoritative pre-check: is this remote already bound in this tenant? */
174+
export async function getBindingForRemote(remote: string): Promise<GetBindingResponse | null> {
175+
try {
176+
return await req<GetBindingResponse>("GET", "/by-remote", { query: { repo_remote: remote } })
177+
} catch (err) {
178+
if (err instanceof NotFoundError) return null
179+
throw err
180+
}
181+
}
182+
183+
export async function createAndBind(input: {
184+
name: string
185+
repoRemote: string
186+
description?: string
187+
}): Promise<CreateAndBindResponse> {
188+
return req<CreateAndBindResponse>("POST", "/", {
189+
body: {
190+
name: input.name,
191+
repo_remote: input.repoRemote,
192+
description: input.description ?? null,
193+
},
194+
})
195+
}
196+
197+
export async function bindExisting(datamateId: number, remote: string): Promise<BindingResponse> {
198+
return req<BindingResponse>("POST", "/bind", {
199+
body: { datamate_id: datamateId, repo_remote: remote },
200+
})
201+
}
202+
203+
export async function rebindByRemote(input: {
204+
remote: string
205+
targetDatamateId: number
206+
expectedCurrentDatamateId?: number
207+
}): Promise<BindingResponse> {
208+
return req<BindingResponse>("PUT", "/by-remote", {
209+
body: {
210+
repo_remote: input.remote,
211+
target_datamate_id: input.targetDatamateId,
212+
...(input.expectedCurrentDatamateId !== undefined
213+
? { expected_current_datamate_id: input.expectedCurrentDatamateId }
214+
: {}),
215+
},
216+
})
217+
}
218+
219+
/** Populates the "link to existing workspace" picker. Reuses the existing
220+
* /datamates/ list endpoint on the datamates_router. */
221+
export async function listDatamates(): Promise<DatamateRef[]> {
222+
const { url, instance, apiKey } = await creds()
223+
const res = await fetch(`${url}/datamates/`, {
224+
headers: { Authorization: `Bearer ${apiKey}`, "x-tenant": instance },
225+
})
226+
if (!res.ok)
227+
throw new WorkspaceApiError(`Failed to list workspaces (status ${res.status})`, res.status)
228+
const body = (await res.json()) as { datamates?: Array<{ id: number | string; name: string }> }
229+
return (body.datamates ?? []).map((d) => ({ id: Number(d.id), name: d.name }))
230+
}
231+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// altimate_change - new file
2+
//
3+
// Cheap, sync git-remote detection for the workspace-binding flow. Shared by
4+
// the TuiPlugin (packages/opencode/src/plugin/tui/altimate/workspace.tsx) and
5+
// the `altimate link` CLI subcommand so both entry points identify projects
6+
// identically. Reuses the credential-scrubbing helper the ProjectScan tool
7+
// exports (../tools/project-scan.ts) so an HTTPS remote with embedded
8+
// basic-auth (e.g. `https://x-access-token:[email protected]/...`) never
9+
// reaches the server or the local cache in clear.
10+
import { spawnSync } from "node:child_process"
11+
import { stripGitRemoteCredentials } from "../tools/project-scan"
12+
13+
export function detectProjectRemote(directory: string): string | undefined {
14+
try {
15+
const r = spawnSync("git", ["remote", "get-url", "origin"], {
16+
cwd: directory,
17+
encoding: "utf8",
18+
timeout: 3000,
19+
})
20+
if (r.status !== 0 || !r.stdout) return undefined
21+
return stripGitRemoteCredentials(r.stdout.trim())
22+
} catch {
23+
return undefined
24+
}
25+
}
26+
27+
/** Sensible default workspace name from a remote URL — best-effort. Used to
28+
* prefill the workspace-name prompt in the CreateDialog and `altimate link`.
29+
* ``github.com/foo/bar.git`` → ``bar`` ; ``[email protected]:foo/bar.git`` → ``bar``. */
30+
export function projectNameFromRemote(remote: string): string {
31+
const trimmed = remote.replace(/\.git$/, "").replace(/\/$/, "")
32+
const parts = trimmed.split(/[/:]/)
33+
return parts[parts.length - 1] || "workspace"
34+
}

0 commit comments

Comments
 (0)