Repository navigation
Expand file tree
/
Copy pathinteractive.tsx
More file actions
511 lines (482 loc) · 18.3 KB
/
Copy pathinteractive.tsx
File metadata and controls
511 lines (482 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
import { resolve } from "path"
import type { Root } from "@opentui/react"
import type { CliRenderer } from "@opentui/core"
import { createCliRenderer } from "@opentui/core"
import { createRoot } from "@opentui/react"
import {
Registry,
RegistryContext,
Result,
scheduleTask,
} from "@effect-atom/atom-react"
import type * as FileSystem from "@effect/platform/FileSystem"
import type * as CommandExecutor from "@effect/platform/CommandExecutor"
import type * as HttpClient from "@effect/platform/HttpClient"
import type * as Path from "@effect/platform/Path"
import type * as Terminal from "@effect/platform/Terminal"
import { FetchHttpClient } from "@effect/platform"
import {
createAgentClient,
onboardingModelSetupViewAtom,
pushNotificationAtom,
stopDisplayViewController,
type HarnessLaunchPlan,
type HarnessConnectionError,
} from "@magnitudedev/client-common"
import {
updateActionFor,
type PackageManager,
type UpdateAction,
} from "@magnitudedev/release"
import { logger } from "@magnitudedev/logger"
import { acnInstallationPresent, DAEMON_TARGET } from "@magnitudedev/daemon-management"
import { type FirstPartyConnection } from "@magnitudedev/client-common"
import {
interactiveProcessExitCode,
runInteractiveProcess,
} from "@magnitudedev/utils/process"
import type { StateDocumentError } from "@magnitudedev/storage"
import { Array as Arr, Effect, Fiber, Layer, Option, Schema, Scope, Stream } from "effect"
import type { SessionOptions } from "@magnitudedev/sdk"
import type { CliAppProps, SessionStart } from "../app"
import type { AuthSource } from "../state/cli-atoms"
import { getLastSessionId } from "../state/last-session"
import { CLI_VERSION } from "../version"
import { makeCliEffectLoggingLayer } from "../platform/effect-logger"
import {
installTerminalAppearanceRuntime,
probeTerminalAppearance,
} from "../platform/terminal-appearance"
import {
makeTerminalAdapter,
} from "../platform/terminal"
import {
makeProcessExitSource,
restoreTerminalState,
untilProcessExit,
type ProcessExitRequest,
} from "../platform/process-exit"
import { terminalAppearanceAtom } from "../hooks/use-theme"
import { executeUpdate } from "../features/update/execute"
import { CliUpdater, makeCliUpdater } from "../features/update/updater"
import { CliApplicationRoot } from "./root"
import { makeHarnessConnection } from "../harness-connections/service"
import { makeAcnConnectionWithInstanceManager } from "../server/acn-connection"
import { makeBootstrappingAcnInstanceManager } from "../server/acn-instance-manager"
import { resolveCliTheme } from "../utils/theme"
import { runInlineUpdatePrompt } from "../startup/inline-update-prompt"
import { makeInlineServiceStartupPresenter } from "../startup/inline-service-lifecycle"
export class CliRendererAcquisitionFailed extends Schema.TaggedError<CliRendererAcquisitionFailed>()(
"CliRendererAcquisitionFailed",
{ reason: Schema.String },
) {}
export interface InteractiveLaunchOptions {
readonly debug: boolean
readonly setup: boolean
readonly developmentBuild: boolean
readonly sessionStart: SessionStart
readonly initialPrompt: string | undefined
readonly envAuth: AuthSource
readonly sessionOptions: SessionOptions
}
type InteractiveSessionResult =
| {
readonly _tag: "UpdateRequested"
readonly action: UpdateAction
}
| {
readonly _tag: "Exit"
readonly code: number
readonly notices: ReadonlyArray<string>
readonly fatal: Option.Option<{
readonly label: string
readonly message: string
readonly stack: Option.Option<string>
}>
}
| {
readonly _tag: "LaunchHarness"
readonly plan: HarnessLaunchPlan
}
/** Everything before the application is on screen, or an update the user chose instead. */
type PreparedApplication =
| { readonly _tag: "UpdateRequested"; readonly action: UpdateAction }
| {
readonly _tag: "Prepared"
readonly connection: FirstPartyConnection
readonly handoff: Effect.Effect<HarnessLaunchPlan>
}
const acquireRegistry = Effect.acquireRelease(
Effect.sync(() => Registry.make({
scheduleTask,
defaultIdleTTL: 5_000,
})),
(registry) => Effect.sync(() => registry.dispose()),
)
const acquireRenderer: Effect.Effect<
CliRenderer,
CliRendererAcquisitionFailed,
Scope.Scope
> = Effect.acquireRelease(
Effect.tryPromise({
try: () => createCliRenderer({ exitOnCtrlC: false }),
catch: (error) => new CliRendererAcquisitionFailed({
reason: String(error),
}),
}),
(renderer) => Effect.sync(() => {
restoreTerminalState()
try {
renderer.destroy()
} catch {
// Terminal restoration must remain best-effort during finalization.
}
}),
)
const acquireRoot = (renderer: CliRenderer) => Effect.acquireRelease(
Effect.sync(() => createRoot(renderer)),
(root) => Effect.sync(() => root.unmount()),
)
const renderRoot = (
root: Root,
registry: ReturnType<typeof Registry.make>,
platform: Parameters<typeof CliApplicationRoot>[0]["platform"],
agentClient: Parameters<typeof CliApplicationRoot>[0]["agentClient"],
startup: Parameters<typeof CliApplicationRoot>[0]["startup"],
app: CliAppProps,
): Effect.Effect<void> => Effect.sync(() => {
root.render(
<RegistryContext.Provider value={registry}>
<CliApplicationRoot
platform={platform}
agentClient={agentClient}
startup={startup}
app={app}
/>
</RegistryContext.Provider>,
)
})
const fatalResult = (
request: Extract<ProcessExitRequest, { readonly _tag: "Fatal" }>,
): InteractiveSessionResult => {
const isError = request.error instanceof Error
return {
_tag: "Exit",
code: 1,
notices: [],
fatal: Option.some({
label: request.label,
message: isError ? request.error.message : String(request.error),
stack: Option.fromNullable(isError ? request.error.stack : undefined),
}),
}
}
const preApplicationExit = (
request: ProcessExitRequest,
): InteractiveSessionResult => request._tag === "Fatal"
? fatalResult(request)
: { _tag: "Exit", code: 0, notices: [], fatal: Option.none() }
const closeApplication = (
connection: FirstPartyConnection,
request: ProcessExitRequest,
): Effect.Effect<InteractiveSessionResult> => request._tag === "Fatal"
? Effect.succeed(fatalResult(request))
: connection.close.pipe(
Effect.map(() => {
const notices: string[] = []
const activeSessionId = getLastSessionId()
if (activeSessionId) {
notices.push(`Resume this session with:\nmagnitude --resume ${activeSessionId}`)
}
stopDisplayViewController()
return {
_tag: "Exit" as const,
code: 0,
notices,
fatal: Option.none(),
}
}),
)
/**
* Startup, from update discovery to the application on screen. It contains no
* exit handling: a failure anywhere propagates, and `runInteractiveSession` is
* the one place that races the whole of it against a user exit request.
*/
const prepareApplication = (
options: InteractiveLaunchOptions,
): Effect.Effect<
PreparedApplication,
CliRendererAcquisitionFailed | StateDocumentError | import("@magnitudedev/sdk").ConnectionError | HarnessConnectionError,
CliUpdater | FileSystem.FileSystem | Path.Path | Scope.Scope
| CommandExecutor.CommandExecutor | HttpClient.HttpClient | Terminal.Terminal
> => Effect.gen(function* () {
const updater = yield* CliUpdater
const registry = yield* acquireRegistry
const effectLoggingLayer = makeCliEffectLoggingLayer({
debug: options.debug,
publishNotification: (notification) => {
registry.set(pushNotificationAtom, notification)
},
})
// The appearance probe starts with the session — concurrent with discovery
// and service work — and self-terminates within one terminal roundtrip
// (fence) or its 100ms ceiling, so its answer is in long before anything
// paints. It owns terminal input until then; the renderer is only created
// after it is joined.
const appearanceProbe = yield* Effect.forkScoped(probeTerminalAppearance())
// Update interaction happens only on plain interactive launches with a
// known owning package manager; discovery itself still runs and caches.
const updateMethod: Option.Option<PackageManager> =
(options.initialPrompt?.length ?? 0) === 0
&& process.stdin.isTTY === true
&& process.stdout.isTTY === true
? updater.packageManager
: Option.none()
const discovery = yield* updater.discover.pipe(Effect.provide(effectLoggingLayer))
let freshPending = true
const declinedVersions = new Set<string>()
const offerable = (latest: Option.Option<string>): Option.Option<string> =>
Option.filter(latest, (version) => !declinedVersions.has(version))
// Ctrl-C inside the prompt raises SIGINT, which the session-level exit race
// turns into an interruption of this whole effect.
const presentUpdatePrompt = (latestVersion: string, action: UpdateAction) =>
Effect.gen(function* () {
const appearance = yield* Fiber.join(appearanceProbe)
const selected = yield* runInlineUpdatePrompt({
currentVersion: CLI_VERSION,
latestVersion,
action,
theme: resolveCliTheme(appearance),
})
if (selected._tag === "Dismiss") {
yield* updater.dismissVersion(latestVersion)
}
if (selected._tag === "Update") return { _tag: "Update" } as const
declinedVersions.add(latestVersion)
return { _tag: "Declined" } as const
})
if (Option.isSome(updateMethod) && Option.isSome(discovery.known)) {
const action = updateActionFor(updateMethod.value, discovery.known.value)
const resolution = yield* presentUpdatePrompt(discovery.known.value, action)
if (resolution._tag === "Update") {
return { _tag: "UpdateRequested", action }
}
}
// The installation gate: with no installed service build this launch is about
// to download one, so it awaits the version check first — an offer must
// prompt before any download of the version it would replace. Installation
// needs the network regardless, so the wait costs nothing real.
if (Option.isSome(updateMethod)
&& !(yield* acnInstallationPresent(DAEMON_TARGET.identity))) {
const answer = yield* discovery.fresh
freshPending = false
const offer = offerable(answer)
if (Option.isSome(offer)) {
const action = updateActionFor(updateMethod.value, offer.value)
const resolution = yield* presentUpdatePrompt(offer.value, action)
if (resolution._tag === "Update") {
return { _tag: "UpdateRequested", action }
}
}
}
const connection = yield* Effect.gen(function* () {
const manager = yield* makeBootstrappingAcnInstanceManager({
launchCommand: developmentLaunchCommand(options),
debug: options.debug,
})
return yield* makeAcnConnectionWithInstanceManager(manager)
}).pipe(Effect.provide(effectLoggingLayer))
const appearance = yield* Fiber.join(appearanceProbe)
const startupTheme = resolveCliTheme(appearance)
const serviceStartup = yield* makeInlineServiceStartupPresenter(startupTheme)
type ServiceWaitOutcome =
| { readonly _tag: "Ready" }
| { readonly _tag: "FreshOffer"; readonly version: string }
// A fresh update offer may interrupt terminal presentation, but it does not
// interrupt the shared SDK ensurance occurrence. Declining resumes from the
// current authoritative lifecycle state. A readiness failure wins the race
// outright and propagates.
let starting = true
while (starting) {
const readiness = serviceStartup.run(connection.startup).pipe(
Effect.map((): ServiceWaitOutcome => ({ _tag: "Ready" })),
)
const outcome = Option.isSome(updateMethod) && freshPending
? yield* Effect.raceFirst(readiness, discovery.fresh.pipe(
Effect.flatMap((latest) => Option.match(offerable(latest), {
onNone: () => Effect.never,
onSome: (offer): Effect.Effect<ServiceWaitOutcome> => Effect.succeed({
_tag: "FreshOffer",
version: offer,
}),
})),
))
: yield* readiness
if (outcome._tag === "Ready") {
starting = false
continue
}
freshPending = false
if (Option.isNone(updateMethod)) continue
const action = updateActionFor(updateMethod.value, outcome.version)
const resolution = yield* presentUpdatePrompt(outcome.version, action)
if (resolution._tag === "Update") {
return { _tag: "UpdateRequested", action }
}
}
const harnessConnection = yield* makeHarnessConnection
const agentClient = createAgentClient(connection.client, {
onboardingSetupInitiallyOpen: options.setup,
harnessConnection,
})
// Warm the onboarding view so the first frame is not empty. Best-effort and
// bounded: the app reads the same atom reactively, so painting never waits on
// a daemon that is ready but slow to answer.
yield* Effect.exit(Registry.getResult(
registry,
onboardingModelSetupViewAtom(agentClient),
).pipe(Effect.timeout("5 seconds")))
const app: CliAppProps = {
sessionStart: options.sessionStart,
initialPrompt: options.initialPrompt,
envAuth: options.envAuth,
sessionOptions: options.sessionOptions,
}
registry.set(terminalAppearanceAtom, appearance)
const renderer = yield* acquireRenderer
yield* installTerminalAppearanceRuntime(renderer, registry)
const root = yield* acquireRoot(renderer)
yield* renderRoot(
root,
registry,
makeTerminalAdapter(),
agentClient,
connection.startup,
app,
)
// A discovery answer arriving after the app committed surfaces as one
// notification line; the prompt would interrupt real work now.
if (Option.isSome(updateMethod) && freshPending) {
yield* Effect.forkScoped(discovery.fresh.pipe(
Effect.flatMap((latest) => Option.match(offerable(latest), {
onNone: () => Effect.void,
onSome: (version) => Effect.sync(() => {
registry.set(pushNotificationAtom, {
message: `Update available: ${version} — restart or run \`magnitude update\``,
priority: "notice",
action: Option.none(),
dismissAfterMilliseconds: 30_000,
})
}),
})),
))
}
const handoff = Registry.toStream(
registry,
onboardingModelSetupViewAtom(agentClient),
).pipe(
Stream.filterMap((result) => Option.flatMap(Result.value(result), (state) =>
state._tag === "Open" && state.content._tag === "HarnessHandoff"
? Option.some(state.content.plan)
: Option.none())),
Stream.runHead,
Effect.flatMap(Option.match({ onNone: () => Effect.never, onSome: Effect.succeed })),
)
return { _tag: "Prepared", connection, handoff }
})
const runInteractiveSession = (
options: InteractiveLaunchOptions,
): Effect.Effect<
InteractiveSessionResult,
CliRendererAcquisitionFailed | StateDocumentError | import("@magnitudedev/sdk").ConnectionError | HarnessConnectionError,
CliUpdater | FileSystem.FileSystem | Path.Path | Scope.Scope
| CommandExecutor.CommandExecutor | HttpClient.HttpClient | Terminal.Terminal
> => Effect.gen(function* () {
const processExit = yield* makeProcessExitSource
const prepared = yield* untilProcessExit(prepareApplication(options), processExit)
if (prepared._tag === "Exit") return preApplicationExit(prepared.request)
if (prepared.value._tag === "UpdateRequested") return prepared.value
const { connection, handoff } = prepared.value
// The application's own wait: neither side can fail, and it ends only when
// the user exits or a harness handoff is chosen.
const outcome = yield* Effect.raceFirst(
processExit.await.pipe(Effect.map((request) => ({ _tag: "Exit" as const, request }))),
handoff.pipe(Effect.map((plan) => ({ _tag: "Launch" as const, plan }))),
)
if (outcome._tag === "Exit") return yield* closeApplication(connection, outcome.request)
yield* connection.close.pipe(Effect.ignore)
stopDisplayViewController()
return { _tag: "LaunchHarness", plan: outcome.plan }
})
const writeSessionResult = (
result: Extract<InteractiveSessionResult, { readonly _tag: "Exit" }>,
): Effect.Effect<void> => Effect.sync(() => {
if (Option.isSome(result.fatal)) {
const fatal = result.fatal.value
logger.error({
error: fatal.message,
stack: Option.getOrUndefined(fatal.stack),
}, fatal.label)
process.stderr.write(`\n${fatal.label}: ${fatal.message}\n`)
if (Option.isSome(fatal.stack)) process.stderr.write(`${fatal.stack.value}\n`)
}
if (result.notices.length > 0) {
process.stdout.write(`\n${result.notices.join("\n\n")}\n`)
}
})
export const runInteractiveCommand = (
options: InteractiveLaunchOptions,
): Effect.Effect<
number,
CliRendererAcquisitionFailed | StateDocumentError | import("@magnitudedev/sdk").ConnectionError | HarnessConnectionError,
| CommandExecutor.CommandExecutor
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
| Terminal.Terminal
> => Effect.gen(function* () {
const updater = yield* makeCliUpdater({
currentVersion: CLI_VERSION,
developmentBuild: options.developmentBuild,
})
const result = yield* Effect.scoped(runInteractiveSession(options).pipe(
Effect.provideService(CliUpdater, updater),
))
if (result._tag === "UpdateRequested") {
return yield* executeUpdate(updater, result.action, { relaunch: true })
}
if (result._tag === "LaunchHarness") {
return yield* runInteractiveProcess({
executable: result.plan.executable,
args: result.plan.args,
environment: { ...process.env, ...result.plan.environment },
workingDirectory: process.cwd(),
}).pipe(
Effect.map(interactiveProcessExitCode),
Effect.catchAll((error) => Effect.sync(() => {
const manual = [result.plan.command, ...result.plan.args]
.map((part) => /[\s'"\\]/.test(part) ? JSON.stringify(part) : part)
.join(" ")
process.stderr.write([
`Magnitude setup is complete, but ${result.plan.harness} could not be launched.`,
String(error),
`Run manually: ${manual}`,
"",
].join("\n"))
return 1
})),
)
}
yield* writeSessionResult(result)
return result.code
})
const developmentLaunchCommand = (
options: InteractiveLaunchOptions,
): Option.Option<Arr.NonEmptyReadonlyArray<string>> => options.developmentBuild
? Option.some([
"bun",
resolve(import.meta.dir, "..", "..", "..", "packages", "acn", "src", "binary.ts"),
"serve",
...(options.debug ? ["--debug"] : []),
])
: Option.none()