@cmodjs/core 6.3.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/docs/commands.md +123 -65
  2. package/docs/dependencies.md +189 -4
  3. package/docs/index.md +56 -12
  4. package/docs/install-steps.md +20 -17
  5. package/docs/jobs.md +43 -16
  6. package/docs/mod.md +43 -27
  7. package/docs/options.md +2 -2
  8. package/docs/session.md +58 -32
  9. package/docs/testing.md +88 -24
  10. package/docs/ui.md +128 -58
  11. package/installer.d.ts +2 -2
  12. package/jobs/context.js +1 -1
  13. package/jobs/program.d.ts +4 -1
  14. package/jobs/program.d.ts.map +1 -1
  15. package/jobs/program.js +79 -20
  16. package/mod.d.ts +59 -9
  17. package/mod.d.ts.map +1 -1
  18. package/mod.js +5 -3
  19. package/package.json +1 -1
  20. package/records.d.ts +15 -2
  21. package/records.d.ts.map +1 -1
  22. package/records.js +24 -10
  23. package/register.d.ts.map +1 -1
  24. package/register.js +7 -4
  25. package/rpc.d.ts +7 -0
  26. package/rpc.d.ts.map +1 -0
  27. package/rpc.js +59 -0
  28. package/runtime/bound.d.ts +1 -0
  29. package/runtime/bound.d.ts.map +1 -1
  30. package/runtime/bound.js +10 -0
  31. package/runtime/bun.d.ts +20 -0
  32. package/runtime/bun.d.ts.map +1 -0
  33. package/runtime/bun.js +20 -0
  34. package/runtime/claude.d.ts +1 -0
  35. package/runtime/claude.d.ts.map +1 -1
  36. package/runtime/conversations.d.ts +12 -1
  37. package/runtime/conversations.d.ts.map +1 -1
  38. package/runtime/conversations.js +472 -362
  39. package/runtime/deadline.d.ts +4 -3
  40. package/runtime/deadline.d.ts.map +1 -1
  41. package/runtime/deadline.js +10 -4
  42. package/runtime/engine.d.ts +5 -4
  43. package/runtime/engine.d.ts.map +1 -1
  44. package/runtime/installer.d.ts +3 -3
  45. package/runtime/installer.d.ts.map +1 -1
  46. package/runtime/installer.js +10 -9
  47. package/runtime/interfaces.d.ts +262 -0
  48. package/runtime/interfaces.d.ts.map +1 -0
  49. package/runtime/interfaces.js +935 -0
  50. package/runtime/lifecycle.d.ts +3 -3
  51. package/runtime/lifecycle.d.ts.map +1 -1
  52. package/runtime/lifecycle.js +83 -52
  53. package/runtime/options.d.ts.map +1 -1
  54. package/runtime/options.js +2 -6
  55. package/runtime/parts.d.ts +64 -1
  56. package/runtime/parts.d.ts.map +1 -1
  57. package/runtime/parts.js +311 -4
  58. package/runtime/programs.d.ts +1 -0
  59. package/runtime/programs.d.ts.map +1 -1
  60. package/runtime/programs.js +5 -3
  61. package/runtime/rpc.d.ts +111 -0
  62. package/runtime/rpc.d.ts.map +1 -0
  63. package/runtime/rpc.js +387 -0
  64. package/runtime/sessions.d.ts +6 -4
  65. package/runtime/sessions.d.ts.map +1 -1
  66. package/runtime/sessions.js +59 -80
  67. package/runtime/toaster.js +1 -1
  68. package/runtime/ui.d.ts +23 -10
  69. package/runtime/ui.d.ts.map +1 -1
  70. package/runtime/ui.js +63 -52
  71. package/runtime/web.d.ts +0 -73
  72. package/runtime/web.d.ts.map +1 -1
  73. package/runtime/web.js +9 -5
  74. package/runtime/widgets.d.ts +4 -2
  75. package/runtime/widgets.d.ts.map +1 -1
  76. package/runtime/widgets.js +17 -16
  77. package/session/conversation.d.ts +7 -1
  78. package/session/conversation.d.ts.map +1 -1
  79. package/session/session.d.ts +31 -7
  80. package/session/session.d.ts.map +1 -1
  81. package/session/session.js +1 -0
  82. package/src/installer.ts +2 -2
  83. package/src/jobs/context.ts +1 -1
  84. package/src/jobs/program.ts +76 -21
  85. package/src/mod.ts +51 -10
  86. package/src/records.ts +33 -9
  87. package/src/register.ts +7 -4
  88. package/src/rpc.ts +67 -0
  89. package/src/runtime/bound.ts +10 -0
  90. package/src/runtime/bun.ts +40 -0
  91. package/src/runtime/claude.ts +1 -0
  92. package/src/runtime/conversations.ts +470 -352
  93. package/src/runtime/deadline.ts +13 -6
  94. package/src/runtime/engine.ts +5 -4
  95. package/src/runtime/installer.ts +13 -12
  96. package/src/runtime/interfaces.ts +1161 -0
  97. package/src/runtime/lifecycle.ts +102 -59
  98. package/src/runtime/options.ts +2 -5
  99. package/src/runtime/parts.ts +364 -5
  100. package/src/runtime/programs.ts +6 -3
  101. package/src/runtime/rpc.ts +457 -0
  102. package/src/runtime/sessions.ts +63 -83
  103. package/src/runtime/toaster.ts +1 -1
  104. package/src/runtime/ui.ts +82 -61
  105. package/src/runtime/web.ts +10 -39
  106. package/src/runtime/widgets.ts +20 -18
  107. package/src/session/conversation.ts +7 -1
  108. package/src/session/session.ts +22 -7
  109. package/src/testing/fake-claude.ts +38 -7
  110. package/src/testing/fake-serve.ts +144 -0
  111. package/src/testing/fake-sessions.ts +21 -6
  112. package/src/testing.ts +156 -68
  113. package/src/ui/areas.ts +2 -2
  114. package/src/ui/elements.ts +21 -16
  115. package/src/ui/panes.ts +14 -7
  116. package/testing/fake-claude.d.ts +6 -0
  117. package/testing/fake-claude.d.ts.map +1 -1
  118. package/testing/fake-claude.js +34 -7
  119. package/testing/fake-serve.d.ts +39 -0
  120. package/testing/fake-serve.d.ts.map +1 -0
  121. package/testing/fake-serve.js +110 -0
  122. package/testing/fake-sessions.d.ts.map +1 -1
  123. package/testing/fake-sessions.js +22 -6
  124. package/testing.d.ts +21 -4
  125. package/testing.d.ts.map +1 -1
  126. package/testing.js +138 -56
  127. package/ui/areas.d.ts +3 -1
  128. package/ui/areas.d.ts.map +1 -1
  129. package/ui/elements.d.ts +18 -9
  130. package/ui/elements.d.ts.map +1 -1
  131. package/ui/elements.js +9 -8
  132. package/ui/panes.d.ts +10 -6
  133. package/ui/panes.d.ts.map +1 -1
  134. package/ui/panes.js +5 -3
  135. package/runtime/pages.d.ts +0 -32
  136. package/runtime/pages.d.ts.map +0 -1
  137. package/runtime/pages.js +0 -142
  138. package/src/runtime/pages.ts +0 -183
@@ -15,7 +15,8 @@ import { ToolResult } from '../session/context/turn/message/tool-result.js'
15
15
  import { createConversation, emptyConversation, searchLimit, tasksWithAgents, type ContextData, type Conversation, type SessionChange, type SessionData, type TaskData, type TurnData, type TurnEnding } from '../session/conversation.js'
16
16
  import type { Decide, Place } from '../runtime/before.js'
17
17
  import type { Claude } from '../runtime/claude.js'
18
- import { conversationMethods, everySession, isHeardBy, resultOf, type Listened, type SessionColor } from '../runtime/sessions.js'
18
+ import { testDevice } from './fake-claude.js'
19
+ import { conversationMethods, isHeardBy, resultOf, type Listened, type SessionColor } from '../runtime/sessions.js'
19
20
  import { receivedMatcher } from '../utils/matcher.js'
20
21
  import { firstLine, messageOf } from '../utils/text.js'
21
22
 
@@ -78,7 +79,7 @@ export function fakeSessions({ project, cwd, given, push, callTool, listAgents,
78
79
  const now = () => new Date((clock += 1000)).toISOString()
79
80
 
80
81
  const keep = (data: SessionData): Kept => {
81
- const session: Kept = { data, conversation: createConversation(emptyConversation(data.id)), messages: [], turns: new Map(), contexts: new Map(), tasks: new Map() }
82
+ const session: Kept = { data: { device: { id: testDevice.id, name: testDevice.name }, ...data }, conversation: createConversation(emptyConversation(data.id)), messages: [], turns: new Map(), contexts: new Map(), tasks: new Map() }
82
83
  kept.set(data.id, session)
83
84
  return session
84
85
  }
@@ -91,7 +92,7 @@ export function fakeSessions({ project, cwd, given, push, callTool, listAgents,
91
92
  if ('task' in change) session.tasks.set(change.task.id, change.task)
92
93
  session.data = { ...session.data, lastAt: change.type === Message ? change.message.at : session.data.lastAt, ...(session.data.title === '' && change.type === Message && change.message.type === Prompt && change.message.from.type === Person ? { title: firstLine(change.message.text) } : {}) }
93
94
  for (const [mod, sessions] of heard) {
94
- if ([...(sessions.get(session.data.id) ?? []), ...(sessions.get(everySession) ?? [])].some(({ event, matcher }) => isHeardBy(event, matcher, change))) push(mod, session.data.id, change)
95
+ if ((sessions.get(session.data.id) ?? []).some(({ event, matcher }) => isHeardBy(event, matcher, change))) push(mod, session.data.id, change)
95
96
  }
96
97
  }
97
98
  }
@@ -131,7 +132,7 @@ export function fakeSessions({ project, cwd, given, push, callTool, listAgents,
131
132
  return { session, context, contextOpenedAt, ...(turn === undefined ? {} : { turn }), tasks, taskTurns, ...(openCalls === undefined ? {} : { openCalls }) }
132
133
  }
133
134
 
134
- const wantsBefore = (mod: string, event: string) => [current, everySession].some((target) => (watches.get(mod)?.get(target) ?? []).includes(event))
135
+ const wantsBefore = (mod: string, event: string) => (watches.get(mod)?.get(current) ?? []).includes(event)
135
136
 
136
137
  const taskOf = (session: Kept, id: string) => {
137
138
  const task = session.tasks.get(id)
@@ -157,9 +158,10 @@ export function fakeSessions({ project, cwd, given, push, callTool, listAgents,
157
158
  .filter((session) => isInScope(session, request))
158
159
  .map((session) => session.data)
159
160
  .toSorted((first, second) => second.lastAt.localeCompare(first.lastAt)),
161
+ [conversationMethods.session]: (request) => sessionOf(String(request['session'])).data,
160
162
  [conversationMethods.search](request) {
161
163
  const text = String(request['text'])
162
- if ([...text].length < 3) throw new Error('cmod history search takes at least 3 characters.')
164
+ if ([...text].length < 3) throw new Error('cmod sessions search takes at least 3 characters.')
163
165
  const inRecord = (message: Message) => {
164
166
  const session = kept.get(message.session)
165
167
  const task = request['task']
@@ -223,6 +225,15 @@ export function fakeSessions({ project, cwd, given, push, callTool, listAgents,
223
225
  const action = String(request['action'])
224
226
  const input = isObject(request['input']) ? request['input'] : {}
225
227
  const task = typeof request['task'] === 'string' ? request['task'] : undefined
228
+ if (action === 'visit') {
229
+ session.data = { ...session.data, visitedAt: typeof request['input'] === 'string' ? request['input'] : now() }
230
+ return null
231
+ }
232
+ if (action === 'delete') {
233
+ if (session.data.isRunning) throw new Error(`session ${session.data.id} runs, so it stays. End it first.`)
234
+ kept.delete(session.data.id)
235
+ return null
236
+ }
226
237
  const isLive = task === undefined ? session.data.isRunning : session.data.isRunning && taskOf(session, task).closedAt === undefined
227
238
  if (action === 'usage') return { model: task === undefined ? session.data.model : (taskOf(session, task).model ?? session.data.model), contextWindow: {} }
228
239
  if (action === 'surfaces') return isLive ? ['terminal'] : []
@@ -232,6 +243,10 @@ export function fakeSessions({ project, cwd, given, push, callTool, listAgents,
232
243
  if (open?.prompt.id !== input['turn']) throw new Error(`turn ${String(input['turn'])} has ended, so there is nothing to abort.`)
233
244
  return null
234
245
  }
246
+ if (action === 'end') {
247
+ session.data = { ...session.data, isRunning: false }
248
+ return null
249
+ }
235
250
  if (action === 'send') {
236
251
  sent.push({ session: session.data.id, ...(task === undefined ? {} : { task }), type: String(input['type']), text: String(input['text']), ...(typeof input['as'] === 'string' ? { as: input['as'] } : {}) })
237
252
  return null
@@ -240,7 +255,7 @@ export function fakeSessions({ project, cwd, given, push, callTool, listAgents,
240
255
  const title = text('title') ?? ''
241
256
  if (action === 'startTask' || action === 'fork' || action === 'startBackgroundTask' || action === 'clone') {
242
257
  if (title.trim() === '') throw new Error('a task needs a title.')
243
- const isClone = action === 'clone'
258
+ const isClone = action === 'clone' || (action === 'fork' && input['isBackground'] === true)
244
259
  const isBackground = isClone || action === 'startBackgroundTask'
245
260
  const forkedFrom = isClone || action === 'fork' ? session.data.id : undefined
246
261
  const agentType = forkedFrom === undefined ? text('agentType') : undefined
package/src/testing.ts CHANGED
@@ -20,9 +20,9 @@ import type {
20
20
  UiSelectArgument,
21
21
  } from 'claude-code'
22
22
  import type { CommandReply } from './jobs/slash-command.js'
23
- import type { ModDefinition } from './mod.js'
23
+ import type { InterfaceMethods, InterfaceName, ModDefinition, Provided } from './mod.js'
24
24
  import type { Options, OptionValues } from './options.js'
25
- import { hotkeyCommand, readSteps, storeFolder, type Steps } from './records.js'
25
+ import { hotkeyCommand, readSteps, type Steps } from './records.js'
26
26
  import { heldInput, type Claude } from './runtime/claude.js'
27
27
  import { answerCall, cmodPluginName, loadedMethod, notInstalled } from './runtime/dependencies.js'
28
28
  import { closingContext, foldBefore, installBefore, withAnswer, type Answers, type Decide } from './runtime/before.js'
@@ -32,6 +32,7 @@ import { keepClaudeCode, type ClaudeCode } from './testing/claude-code.js'
32
32
  import { createRouter } from './runtime/router.js'
33
33
  import { toolInputOf } from './runtime/tool-calls.js'
34
34
  import { createLifecycle } from './runtime/lifecycle.js'
35
+ import { cmodStore } from './runtime/programs.js'
35
36
  import { serveCmodPlugin } from './register.js'
36
37
  import { MissingOptions } from './runtime/options.js'
37
38
  import { conversationMethods, pickedColor, type SessionColor } from './runtime/sessions.js'
@@ -53,12 +54,12 @@ import { fakeSessions, type FakeSession, type FakeSessions, type MessageDraft, t
53
54
  import { listed, messageOf } from './utils/text.js'
54
55
  import { componentOf, type KindProps, type Row, type StyledAt } from './ui/styles.js'
55
56
  import { AbovePrompt, areas, BelowPrompt, Dashboard, TurnEnd as TurnEndArea, Working, type Area } from './ui/areas.js'
56
- import { drawWith, elementOf, withLinks, type Press } from './ui/elements.js'
57
- import { drawnParts } from './runtime/parts.js'
57
+ import { drawWith, elementOf, forClaudeCode } from './ui/elements.js'
58
+ import { drawnParts, pagesOf, providedBy, serveParts, viewsOf } from './runtime/parts.js'
58
59
  import { serveWidgets, type Widgets } from './runtime/widgets.js'
59
60
  import { engineOf } from './runtime/engine.js'
60
- import { pagesOf, servePages } from './runtime/pages.js'
61
- import { inheriting, openLink, partMethods, type DrawnPart, type PageRequest, type PartPress, type PartsUpdate } from './runtime/ui.js'
61
+ import { createProviders, interfaceMethods, styleInterface, type Provided as ProvidedHandle, type Providers, type ServedProviders } from './runtime/interfaces.js'
62
+ import { inheriting, openLink, partMethods, type DrawnPart, type PartPress, type PartRequest, type PartsUpdate } from './runtime/ui.js'
62
63
 
63
64
  export type { Fakes, TestCall } from './testing/fake-claude.js'
64
65
  export type { FakeSession, MessageDraft, StartedTask } from './testing/fake-sessions.js'
@@ -75,9 +76,13 @@ export type ShownPart = {
75
76
  focusedKey(): Promise<string | undefined>
76
77
  }
77
78
 
78
- export type Shown = ShownByClaude & { readonly toasts: readonly ShownToast[]; readonly sent: FakeSessions['sent']; readonly pane: ShownPart; readonly page: ShownPart }
79
+ export type Shown = ShownByClaude & { readonly toasts: readonly ShownToast[]; readonly sent: FakeSessions['sent']; readonly pane: ShownPart; readonly view: ShownPart; readonly page: ShownPart }
79
80
 
80
- export type TestOptions<State extends object, Declared extends Options = Options> = {
81
+ export type FakeProvider = {
82
+ readonly [Name in InterfaceName]: { readonly name: Name; readonly mod: string; readonly program?: string; readonly device?: { readonly id: string; readonly name: string }; readonly methods: InterfaceMethods<Name> }
83
+ }[InterfaceName]
84
+
85
+ export type TestOptions<State extends object, Declared extends Options = Options, Given extends readonly FakeProvider[] = readonly FakeProvider[]> = {
81
86
  readonly state?: { readonly [Lifetime in keyof State]?: Partial<State[Lifetime]> }
82
87
  readonly options?: Partial<OptionValues<Declared>>
83
88
  readonly scope?: 'user' | 'project'
@@ -88,6 +93,7 @@ export type TestOptions<State extends object, Declared extends Options = Options
88
93
  readonly links?: Readonly<Record<string, string>>
89
94
  readonly secrets?: Readonly<Record<string, string>>
90
95
  readonly sessions?: readonly FakeSession[]
96
+ readonly providers?: Given
91
97
  }
92
98
 
93
99
  type Placed<Payload> = Omit<Payload, keyof Placement> & Partial<Placement>
@@ -115,7 +121,7 @@ export type Raise = {
115
121
 
116
122
  type FiredEvent = 'ui.render' | 'ui.scroll' | 'ui.close' | 'cmod.call' | 'tool.check' | 'prompt.context'
117
123
 
118
- export type TestedMod<State extends object> = {
124
+ export type TestedMod<State extends object, Given extends readonly FakeProvider[] = readonly FakeProvider[]> = {
119
125
  start(): Promise<void>
120
126
  readonly raise: Raise
121
127
  fire<N extends FiredEvent>(event: N, input: Args<N>, below?: EventResult<N>): Promise<EventResult<N>>
@@ -137,6 +143,7 @@ export type TestedMod<State extends object> = {
137
143
  readonly calls: readonly TestCall[]
138
144
  readonly fakes: Fakes
139
145
  readonly shown: Shown
146
+ readonly providers: { readonly [Index in keyof Given]: Provided<Given[Index]['name']> }
140
147
  }
141
148
 
142
149
  const defaultColumns = 80
@@ -158,9 +165,15 @@ function drawnByStyle(key: string): (drawnKey: string) => boolean {
158
165
  }
159
166
  }
160
167
 
161
- export function testMod<State extends object, Declared extends Options = Options>(definition: ModDefinition<State, string, Declared>, options: TestOptions<State, Declared> = {}): TestedMod<State> {
168
+ export function testMod<State extends object, Declared extends Options = Options, const Given extends readonly FakeProvider[] = readonly FakeProvider[]>(definition: ModDefinition<State, string, Declared>, options: TestOptions<State, Declared, Given> = {}): TestedMod<State, Given> {
162
169
  installJsx()
163
170
  const name = definition.name
171
+ const given: readonly FakeProvider[] = options.providers ?? []
172
+ for (const each of given) {
173
+ if (each.program !== undefined) continue
174
+ if (each.mod === name) throw new Error(`${name} is the tested mod, so its own provide answers ${each.name}. Fake another mod's provider, or a program's with program: '<executable>'.`)
175
+ if (each.device !== undefined) throw new Error(`${each.mod}'s session code provides ${each.name} only in this session, on this computer, so it takes no device. Give the program that provides it on ${each.device.name}, with program: '<executable>'.`)
176
+ }
164
177
  const isProjectPlugin = options.scope === 'project'
165
178
  let projectRoot = options.projectRoot ?? (isProjectPlugin ? '/test/project' : `/test/plugins/${name}`)
166
179
  const root = isProjectPlugin ? `${projectRoot}/.claude/skills/${name}` : `/test/plugins/${name}`
@@ -196,6 +209,7 @@ export function testMod<State extends object, Declared extends Options = Options
196
209
  const held = conversations.color()
197
210
  if (held.color !== undefined) await tellColor(held)
198
211
  }
212
+ let declaredViews: ReturnType<typeof viewsOf> = []
199
213
  let declaredPages: ReturnType<typeof pagesOf> = []
200
214
  let openPages: { readonly id: string; readonly params: unknown }[] = []
201
215
  let shownPage: { readonly id: string; readonly params: unknown; readonly isFocused: boolean } | undefined
@@ -207,10 +221,11 @@ export function testMod<State extends object, Declared extends Options = Options
207
221
  return work
208
222
  }
209
223
  const settle = async () => {
210
- do {
211
- await fake.settle()
224
+ await fake.settle()
225
+ while (modeled.size > 0) {
212
226
  await Promise.allSettled(modeled)
213
- } while (modeled.size > 0)
227
+ await fake.settle()
228
+ }
214
229
  }
215
230
  let focused: { readonly part: string; readonly key: string } | undefined
216
231
  const forgetFocus = (part: string) => {
@@ -220,41 +235,42 @@ export function testMod<State extends object, Declared extends Options = Options
220
235
  const refusedFocus = async (isPane: boolean, id: string, key: string): Promise<string | undefined> => {
221
236
  const pane = isPane ? id : 'sidebar'
222
237
  if (!(await holdsKeyboard(isPane, id))) return `the pane "${pane}" does not hold the keyboard`
223
- const drawn = lifecycle.phase === 'active' ? (isPane ? await drawPane(id) : await drawPage(id)).drawing : undefined
238
+ const drawn = lifecycle.phase === 'active' ? (isPane ? await drawPane(id) : await drawInSidebar(id)).drawing : undefined
224
239
  if (drawn === undefined || focusableKey(drawn, (props) => props['key'] === key) === undefined) return `the pane "${pane}" draws no Button, Input, or Select with the key "${key}"`
225
240
  return undefined
226
241
  }
227
- const applyRequests = async (requests: readonly PageRequest[]) => {
242
+ const applyRequests = async (requests: readonly PartRequest[]) => {
228
243
  for (const request of requests) {
229
244
  if ('open' in request) {
230
- const isSettings = declaredPages.some((page) => page.id === request.open && page.place === 'settings')
245
+ const isSettings = declaredViews.some((view) => view.id === request.open && view.place === 'settings')
231
246
  if (!isSettings) openPages = [...openPages.filter((page) => page.id !== request.open), { id: request.open, params: request.params ?? null }]
232
247
  shownPage = { id: request.open, params: request.params ?? null, isFocused: request.focus === true }
233
- if (request.focus === true) forgetFocus(`page:${request.open}`)
248
+ if (request.focus === true) forgetFocus(`sidebar:${request.open}`)
234
249
  } else if ('close' in request) {
235
250
  openPages = openPages.filter((page) => page.id !== request.close)
236
251
  if (shownPage?.id === request.close) shownPage = undefined
237
252
  } else if ('focus' in request) {
238
253
  const key = `${name}/${request.focus}:${request.key}`
239
254
  const refused = await refusedFocus(false, request.focus, key)
240
- if (refused === undefined) focused = { part: `page:${request.focus}`, key: request.key }
241
- else reportPart(`pages:${name}`, `Could not show the page ${name} asked for`, new Error(`cmod: Claude Code did not focus "${key}" in the Sidebar pane: ${refused}`))
255
+ if (refused === undefined) focused = { part: `sidebar:${request.focus}`, key: request.key }
256
+ else reportPart(`pages:${name}`, `Could not show the view or page ${name} asked for`, new Error(`cmod: Claude Code did not focus "${key}" in the Sidebar pane: ${refused}`))
242
257
  } else if ('settings' in request) {
243
- const first = declaredPages.find((page) => page.place === 'settings')
258
+ const first = declaredViews.find((view) => view.place === 'settings')
244
259
  shownPage = first === undefined ? undefined : { id: first.id, params: null, isFocused: true }
245
- if (first !== undefined) forgetFocus(`page:${first.id}`)
260
+ if (first !== undefined) forgetFocus(`sidebar:${first.id}`)
246
261
  }
247
262
  }
248
263
  await tellShown()
249
264
  }
250
265
  let widgets: Promise<Widgets> | undefined
251
- let stylesMarkdown = false
266
+ let provides: readonly string[] = []
252
267
  const ownMarkdown = new Map<string, DrawnPart | null>()
253
268
  const missedMarkdown = new Map<string, { readonly markdown: string } & StyledAt>()
254
269
  const updated = async ({ parts, redraw, requests }: PartsUpdate) => {
255
270
  if (parts !== undefined) {
271
+ declaredViews = viewsOf(parts)
256
272
  declaredPages = pagesOf(parts)
257
- stylesMarkdown = parts.stylesMarkdown === true
273
+ provides = providedBy(parts)
258
274
  ownMarkdown.clear()
259
275
  }
260
276
  if (parts !== undefined || redraw !== undefined) (await widgetsOf()).update(name, { ...(parts === undefined ? {} : { parts }), ...(redraw === undefined ? {} : { redraw }) })
@@ -264,7 +280,7 @@ export function testMod<State extends object, Declared extends Options = Options
264
280
  const markdownIn = (table: ElementTable, at: StyledAt) => {
265
281
  let unkeyed = 0
266
282
  return (props: MarkdownProps): RenderElement => {
267
- if (!stylesMarkdown) return table.Markdown(props)
283
+ if (!provides.includes(styleInterface)) return table.Markdown(props)
268
284
  const keyPrefix = `${name}/markdown:${props.key ?? unkeyed++}:`
269
285
  const drawnAt = `${at.surface}\u0000${at.columns}\u0000${props.text}`
270
286
  const drawn = ownMarkdown.get(drawnAt)
@@ -282,10 +298,10 @@ export function testMod<State extends object, Declared extends Options = Options
282
298
  return draw()
283
299
  }
284
300
  const reportPart = (_id: string, message: string, error: unknown) => fake.claude.ui.log(`cmod: ${message}: ${messageOf(error)}`, { to: 'debug' })
285
- const openFromCmod = (href: string, press: Press) => void openLink(fake.claude, href, press.surface).catch((error: unknown) => reportPart('open-link', 'Could not open the link', error))
301
+ const openFromCmod = (href: string, press: UiPressArgument) => void openLink(fake.claude, href, press.surface).catch((error: unknown) => reportPart('open-link', 'Could not open the link', error))
286
302
  const cmodClaude: Claude = {
287
303
  ...fake.claude,
288
- ui: { ...fake.claude.ui, resolve: (e) => withLinks(fake.claude.ui.resolve(e), e.surface, openFromCmod) },
304
+ ui: { ...fake.claude.ui, resolve: (e) => forClaudeCode(fake.claude.ui.resolve(e), e.surface, openFromCmod) },
289
305
  cmod: { call: async (input) => (input.to === name ? callMod(input.method, input.input) : fake.claude.cmod.call(input)) },
290
306
  }
291
307
  const tellRefusedPress = (_mod: string, error: unknown) => fake.claude.ui.log(`cmod: ${name} did not take the press: ${messageOf(error)}`, { to: 'debug' })
@@ -296,7 +312,7 @@ export function testMod<State extends object, Declared extends Options = Options
296
312
  return serveWidgets({
297
313
  claude: cmodClaude,
298
314
  router: cmodPlugin,
299
- store: storeFolder({ HOME: await fake.claude.env.home(), XDG_DATA_HOME: await fake.claude.env.dataHome() }),
315
+ store: await cmodStore(fake.claude),
300
316
  report: reportPart,
301
317
  turnClosedBy: () => conversations.lastTurn(),
302
318
  parts,
@@ -305,13 +321,63 @@ export function testMod<State extends object, Declared extends Options = Options
305
321
  }
306
322
  const widgetsOf = () => (widgets ??= servedWidgets())
307
323
  const cmodBeneath = createRouter()
308
- const pages = servePages({ claude: cmodClaude, router: cmodBeneath, report: reportPart, tellRefusedPress, widgets: { update: (mod, update) => void widgetsOf().then((served) => served.update(mod, update)) }, parts, tellStylers: () => undefined })
309
- pages.apply((_mod, requests) => applyRequests(requests))
310
- const dependencies = fakeDependencies(name, options.dependencies ?? {}, conversations)
324
+ const servedParts = serveParts({ claude: cmodClaude, router: cmodBeneath, report: reportPart, tellRefusedPress, widgets: { update: (mod, update) => void widgetsOf().then((served) => served.update(mod, update)) }, parts, tellStylers: () => undefined, tellUi: () => undefined })
325
+ servedParts.apply((_mod, requests) => applyRequests(requests))
326
+ const after: Claude['clock']['after'] = (ms, run) => fake.claude.clock.after(ms, run)
327
+ const report = (error: unknown) => reportPart('interfaces', 'A provider listener failed', error)
328
+ const sessionMods = new Map<string, Providers>()
329
+ const served = fake.serve.connect({
330
+ tell: (_caller, heard) => new Promise((resolve) => fake.claude.clock.after(0, () => resolve(callMod(interfaceMethods.heard, heard)))),
331
+ sessionCode: (named) => [...(provides.includes(named) ? [name] : []), ...[...sessionMods].filter(([, each]) => each.provided().includes(named)).map(([mod]) => mod)],
332
+ device: async () => {
333
+ const { id, name: deviceName } = await fake.claude.device.read()
334
+ return { id, name: deviceName }
335
+ },
336
+ after,
337
+ report,
338
+ })
339
+ const providedInSession = given.map(({ name: named, mod, program, methods }) => {
340
+ if (program !== undefined) return undefined
341
+ const made = sessionMods.get(mod) ?? createProviders({ name: mod, call: (_to, method, input) => served.answer(method, input, mod) ?? Promise.reject(new Error(`${mod} reaches no ${method} in the test kit.`)), changed: () => undefined, after, report })
342
+ sessionMods.set(mod, made)
343
+ return made.provide(named, methods)
344
+ })
345
+ let fakesReady: Promise<readonly ProvidedHandle[]> | undefined
346
+ const fakeProviders = () =>
347
+ (fakesReady ??= (async () => {
348
+ const programs = await fake.serve.provide(
349
+ given.flatMap(({ name: named, mod, program, device, methods }) => (program === undefined ? [] : [{ name: named, mod, program, ...(device === undefined ? {} : { device }), methods }])),
350
+ { after, report },
351
+ )
352
+ let next = 0
353
+ return providedInSession.map((inSession) => inSession ?? (programs[next++] as ProvidedHandle))
354
+ })())
355
+ const fakeProvider = (index: number): ProvidedHandle => {
356
+ const reached = async () => {
357
+ const each = (await fakeProviders())[index] as ProvidedHandle
358
+ await fake.settle()
359
+ return each
360
+ }
361
+ return {
362
+ remove: () => void modeling(reached().then((each) => each.remove())),
363
+ tell: (event, payload) => void modeling(reached().then((each) => each.tell(event, payload))),
364
+ ask: (event, payload) => modeling(reached().then((each) => each.ask(event, payload))),
365
+ }
366
+ }
367
+ const fakedPrograms = new Set(given.flatMap(({ mod, program }) => (mod === name && program !== undefined ? [program] : [])))
368
+ const spawnUnlessFaked = fake.claude.process.spawn
369
+ fake.claude.process.spawn = (request) => {
370
+ const [, command, mod] = request.argv
371
+ const at = request.argv.indexOf('--')
372
+ const executable = at === -1 ? undefined : request.argv[at + 1]?.split('/').at(-1)
373
+ if (command !== 'program' || mod !== name || request.argv.includes('--remove-service') || executable === undefined || !fakedPrograms.has(executable)) return spawnUnlessFaked(request)
374
+ return { [Symbol.asyncIterator]: () => ({ next: () => new Promise<never>(() => undefined) }) } as never
375
+ }
376
+ const dependencies = fakeDependencies(name, options.dependencies ?? {}, conversations, served, sessionMods)
311
377
  fake.fakes.cmod.call = async (call) => {
312
378
  if (call.to !== cmodPluginName || call.method !== partMethods.changed) return dependencies(call)
313
379
  const { requests, isAsked, ...listing } = call.input as PartsUpdate
314
- const isHeld = isAsked === true && requests !== undefined && pages.update(name, { requests, isAsked })
380
+ const isHeld = isAsked === true && requests !== undefined && servedParts.update(name, { requests, isAsked })
315
381
  await updated(isAsked === true ? listing : (call.input as PartsUpdate))
316
382
  return { isHeld }
317
383
  }
@@ -354,11 +420,11 @@ export function testMod<State extends object, Declared extends Options = Options
354
420
  const runProcess = fake.claude.process.run
355
421
  fake.claude.process.run = async (argv, init) => {
356
422
  const [program, command, action, mod, key] = argv
357
- if (program?.split('/').at(-1) !== 'cmod' || command !== 'secret' || mod !== name || key === undefined) return runProcess(argv, init)
423
+ if (program?.split('/').at(-1) !== 'cmod' || command !== 'secrets' || mod !== name || key === undefined) return runProcess(argv, init)
358
424
  const answer = (stdout: string, stderr = '') => ({ exitCode: stderr === '' ? 0 : 1, stdout, stderr, isStdoutTruncated: false, isStderrTruncated: false })
359
425
  if (action === 'get') return answer(secrets.get(key) ?? '')
360
426
  if (action === 'delete') secrets.delete(key)
361
- else if (init?.stdin === undefined || init.stdin === '') return answer('', `cmod secret: cmod secret store read no value from stdin. cmod secret delete ${name} ${key} deletes the secret.\n`)
427
+ else if (init?.stdin === undefined || init.stdin === '') return answer('', `cmod secrets: cmod secrets store read no value from stdin. cmod secrets delete ${name} ${key} deletes the secret.\n`)
362
428
  else secrets.set(key, init.stdin)
363
429
  return answer('')
364
430
  }
@@ -390,15 +456,17 @@ export function testMod<State extends object, Declared extends Options = Options
390
456
  }
391
457
 
392
458
  const start = async () => {
393
- started ??= lifecycle.start(fake.claude, async (claude) => ({
394
- name,
395
- root,
396
- version: '0.0.0',
397
- store: storeFolder({ HOME: await claude.env.home(), XDG_DATA_HOME: await claude.env.dataHome() }),
398
- isInstalled: true,
399
- shouldRecord: false,
400
- steps: await modSteps(),
401
- }))
459
+ started ??= fakeProviders().then(() =>
460
+ lifecycle.start(fake.claude, async (claude) => ({
461
+ name,
462
+ root,
463
+ version: '0.0.0',
464
+ store: await cmodStore(claude),
465
+ isInstalled: true,
466
+ shouldRecord: false,
467
+ steps: await modSteps(),
468
+ })),
469
+ )
402
470
  await started
403
471
  await fake.settle()
404
472
  const { failure } = lifecycle
@@ -501,35 +569,39 @@ export function testMod<State extends object, Declared extends Options = Options
501
569
  return { drawing, columns }
502
570
  }
503
571
 
504
- const drawPage = async (pageId: string, columns = defaultColumns) => {
572
+ const drawInSidebar = async (id: string, columns = defaultColumns) => {
505
573
  await start()
506
- const page = shownPage
507
- if (page?.id !== pageId) throw new Error(`The page "${pageId}" of ${name} no longer shows, and a user sees a page only while it shows.`)
508
- const drawn = (await callMod(partMethods.draw, { page: pageId, params: page.params, columns, isFocused: page.isFocused })) as DrawnPart | null
574
+ const shown = shownPage
575
+ if (shown?.id !== id) throw new Error(`The view or page "${id}" of ${name} no longer shows, and a user sees one only while it shows.`)
576
+ const drawn = (await callMod(partMethods.draw, { page: id, params: shown.params, columns, isFocused: shown.isFocused, surface: 'terminal' })) as DrawnPart | null
509
577
  await fake.settle()
510
578
  const tree = drawn?.tree ?? null
511
- const table = withLinks(elements, 'terminal', openFromCmod)
512
- const drawing = tree === null || drawn === null ? elements.Box({}) : await withOwnMarkdown(async () => drawWith(table, () => elementOf(tree, `${name}/${pageId}:`, (handler, args) => void modeling(pressPart({ draw: drawn.draw, handler, args }))), markdownIn(table, { surface: 'terminal', columns })) as RenderElement)
579
+ const table = forClaudeCode(elements, 'terminal', openFromCmod)
580
+ const drawing = tree === null || drawn === null ? elements.Box({}) : await withOwnMarkdown(async () => drawWith(table, () => elementOf(tree, `${name}/${id}:`, (handler, args) => void modeling(pressPart({ draw: drawn.draw, handler, args }))), markdownIn(table, { surface: 'terminal', columns })) as RenderElement)
513
581
  checkKeys(drawing, cmodPluginName, 'Pane')
514
582
  return { drawing, columns }
515
583
  }
516
584
 
517
- const shownNow = (isPane: boolean): { readonly id: string; readonly params: unknown } => {
518
- if (isPane) {
585
+ const shownNow = (kind: 'pane' | 'view' | 'page'): { readonly id: string; readonly params: unknown } => {
586
+ if (kind === 'pane') {
519
587
  const id = [...fake.shown.openPanes].at(-1)
520
588
  if (id === undefined) throw new Error(`No pane of ${name} shows. Open one with pane.open(), from a slash command, a hotkey, or setup.`)
521
589
  return { id, params: undefined }
522
590
  }
523
- if (shownPage === undefined) throw new Error(`No page of ${name} shows in the Sidebar. Open one with page.open(), or Settings with mod.settings.open().`)
591
+ const shownKind = shownPage === undefined ? undefined : declaredPages.some((page) => page.id === shownPage?.id) ? 'page' : 'view'
592
+ if (shownPage === undefined || shownKind !== kind) {
593
+ const opening = kind === 'view' ? 'view.open(), or Settings with mod.settings.open()' : 'page.open()'
594
+ throw new Error(`No ${kind} of ${name} shows in the Sidebar${shownPage === undefined ? '' : `, where its ${shownKind} "${shownPage.id}" shows`}. Open one with ${opening}.`)
595
+ }
524
596
  return shownPage
525
597
  }
526
598
 
527
- const shownPart = (isPane: boolean): ShownPart => {
528
- const kind = isPane ? 'pane' : 'page'
599
+ const shownPart = (kind: 'pane' | 'view' | 'page'): ShownPart => {
600
+ const isPane = kind === 'pane'
529
601
  const draw = async (columns?: number) => {
530
602
  await start()
531
- const { id } = shownNow(isPane)
532
- return { id, ...(isPane ? await drawPane(id, columns) : await drawPage(id, columns)) }
603
+ const { id } = shownNow(kind)
604
+ return { id, ...(isPane ? await drawPane(id, columns) : await drawInSidebar(id, columns)) }
533
605
  }
534
606
  const drawnElement = async (type: 'Button' | 'Input' | 'Select' | 'Markdown', key: string) => {
535
607
  const { id, drawing } = await draw()
@@ -541,10 +613,10 @@ export function testMod<State extends object, Declared extends Options = Options
541
613
  const eventIn = (id: string, key: string) => ({ plugin: name, element: key, component: 'Pane' as const, requestId: id, surface: 'terminal' as const })
542
614
  return {
543
615
  get id() {
544
- return shownNow(isPane).id
616
+ return shownNow(kind).id
545
617
  },
546
618
  get params() {
547
- return shownNow(isPane).params
619
+ return shownNow(kind).params
548
620
  },
549
621
  lines: async (lineOptions) => {
550
622
  const { drawing, columns } = await draw(lineOptions?.columns)
@@ -580,9 +652,9 @@ export function testMod<State extends object, Declared extends Options = Options
580
652
  },
581
653
  async focusedKey() {
582
654
  await start()
583
- const { id } = shownNow(isPane)
655
+ const { id } = shownNow(kind)
584
656
  if (!(await holdsKeyboard(isPane, id))) return undefined
585
- if (focused?.part === `${kind}:${id}`) return focused.key
657
+ if (focused?.part === `${isPane ? 'pane' : 'sidebar'}:${id}`) return focused.key
586
658
  const autoFocused = focusableKey((await draw()).drawing, (props) => props['autoFocus'] === true)
587
659
  return isPane || autoFocused === undefined ? autoFocused : autoFocused.slice(`${name}/${id}:`.length)
588
660
  },
@@ -613,6 +685,12 @@ export function testMod<State extends object, Declared extends Options = Options
613
685
  return { drawing, columns: defaultColumns }
614
686
  }
615
687
 
688
+ const loadSettings = async (answer: EventResult<'classic.ConfigChange'>) => {
689
+ if (answer.block === undefined) await lifecycle.settingsLoaded()
690
+ await fake.settle()
691
+ return answer
692
+ }
693
+
616
694
  const fire = ((event: string, input: object, below?: unknown, signal?: AbortSignal) => {
617
695
  if (event.includes('.')) return route(event as RoutedEvent, input, below, signal)
618
696
  if (event === 'SessionStart') {
@@ -637,6 +715,7 @@ export function testMod<State extends object, Declared extends Options = Options
637
715
  const started = routed.then((answer) => ((answeredId = startedAs), answer))
638
716
  return source === 'startup' || source === 'clear' ? started : started.then(async (answer) => (await tellHeldColor(), answer))
639
717
  }
718
+ if (event === 'ConfigChange') return route('classic.ConfigChange', filled, below, signal).then(loadSettings)
640
719
  if (event !== 'PreToolUse') return route(`classic.${event}` as RoutedEvent, filled, below, signal)
641
720
  return firePreToolUse(filled as ClassicHookInputs['PreToolUse'], below as { deny?: string } | undefined)
642
721
  }) as ClaudeCode['fire']
@@ -707,7 +786,7 @@ export function testMod<State extends object, Declared extends Options = Options
707
786
  return value
708
787
  }
709
788
 
710
- const tested: TestedMod<State> = {
789
+ const tested: TestedMod<State, Given> = {
711
790
  start,
712
791
  raise,
713
792
  fire,
@@ -740,7 +819,7 @@ export function testMod<State extends object, Declared extends Options = Options
740
819
  return rowsOf(drawing, columns).map((row) => row.trimEnd())
741
820
  }
742
821
  const component = componentOf(target as Row)
743
- if (props === undefined || component === undefined) throw new Error(`lines takes an area, such as AbovePrompt, or a row kind, such as ToolCall, with its props, and ${target} is neither. Read a pane with tested.shown.pane.lines() and a page with tested.shown.page.lines().`)
822
+ if (props === undefined || component === undefined) throw new Error(`lines takes an area, such as AbovePrompt, or a row kind, such as ToolCall, with its props, and ${target} is neither. Read a pane with tested.shown.pane.lines(), a view with tested.shown.view.lines(), and a page with tested.shown.page.lines().`)
744
823
  const { drawing, columns } = await drawSlot(component, props, requestId)
745
824
  return rowsOf(drawing, columns).map((row) => row.trimEnd())
746
825
  },
@@ -810,22 +889,31 @@ export function testMod<State extends object, Declared extends Options = Options
810
889
  return lifecycle.toasts
811
890
  },
812
891
  sent: conversations.sent,
813
- pane: shownPart(true),
814
- page: shownPart(false),
892
+ pane: shownPart('pane'),
893
+ view: shownPart('view'),
894
+ page: shownPart('page'),
815
895
  },
896
+ providers: given.map((_each, index) => fakeProvider(index)) as never,
816
897
  }
817
898
  keepClaudeCode(tested, { fire })
818
899
  return tested
819
900
  }
820
901
 
821
- function fakeDependencies(caller: string, dependencies: NonNullable<TestOptions<object>['dependencies']>, conversations: FakeSessions): Claude['cmod']['call'] {
822
- const cmod = { forkParent: () => null, updateSettings: () => null, [loadedMethod]: ({ name }: { readonly name: string }) => name === caller || name === cmodPluginName || Object.hasOwn(dependencies, name) }
902
+ function fakeDependencies(caller: string, dependencies: NonNullable<TestOptions<object>['dependencies']>, conversations: FakeSessions, served: ServedProviders, sessionMods: ReadonlyMap<string, Providers>): Claude['cmod']['call'] {
903
+ const cmod = {
904
+ forkParent: () => null,
905
+ updateSettings: () => null,
906
+ [loadedMethod]: ({ name }: { readonly name: string }) => name === caller || name === cmodPluginName || Object.hasOwn(dependencies, name) || sessionMods.has(name),
907
+ }
823
908
  const apis = { [cmodPluginName]: cmod, ...dependencies } as Readonly<Record<string, Parameters<typeof answerCall>[1] | undefined>>
909
+ const provided = ({ to, method, input }: Parameters<Claude['cmod']['call']>[0]) => (to === cmodPluginName ? served.answer(method, input, caller) : sessionMods.get(to)?.answer(method, input, caller, new AbortController().signal))
824
910
  return async (call) => {
825
- const served = call.to === cmodPluginName ? conversations.answer(caller, call.method, call.input) : undefined
826
- if (served !== undefined) return calledAnswer(caller, served as EventResult<'cmod.call'>)
911
+ const told = call.to === cmodPluginName ? conversations.answer(caller, call.method, call.input) : undefined
912
+ if (told !== undefined) return calledAnswer(caller, told as EventResult<'cmod.call'>)
913
+ const answered = provided(call)
914
+ if (answered !== undefined) return calledAnswer(caller, await answered.then((value): EventResult<'cmod.call'> => ({ value }), (error: unknown) => ({ deny: messageOf(error) })))
827
915
  const api = apis[call.to]
828
- return calledAnswer(caller, api === undefined ? { deny: notInstalled(call.to) } : await answerCall(call.to, api, call))
916
+ return calledAnswer(caller, api === undefined ? { deny: sessionMods.has(call.to) ? `${call.to} has no method ${call.method}.` : notInstalled(call.to) } : await answerCall(call.to, api, call))
829
917
  }
830
918
  }
831
919
 
package/src/ui/areas.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Mod, Turn } from '../mod.js'
1
+ import type { Mod, Surface, Turn } from '../mod.js'
2
2
 
3
3
  export const AbovePrompt = 'abovePrompt'
4
4
  export const BelowPrompt = 'belowPrompt'
@@ -10,7 +10,7 @@ export const areas = [AbovePrompt, BelowPrompt, Working, TurnEnd, Dashboard] as
10
10
 
11
11
  export type Area = (typeof areas)[number]
12
12
 
13
- export type WidgetContext = { readonly area: typeof TurnEnd; readonly columns: number; readonly turn: Turn } | { readonly area: Exclude<Area, typeof TurnEnd>; readonly columns: number }
13
+ export type WidgetContext = { readonly area: typeof TurnEnd; readonly columns: number; readonly surface: Surface; readonly turn: Turn } | { readonly area: Exclude<Area, typeof TurnEnd>; readonly columns: number; readonly surface: Surface }
14
14
 
15
15
  export type WidgetInit<State extends object = Record<never, never>> = {
16
16
  readonly id: string