opencode-ghost 1.3.3 → 1.3.5

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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,19 @@ All notable changes to this project are documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.3.5] - 2026-10-10
9
+
10
+ ### Fixed
11
+
12
+ - **tui:** Clean up theme subscriptions and handle cancelled generations
13
+ - **tui:** Handle suggestion acceptance and source registrations safely
14
+
15
+ ## [1.3.4] - 2026-10-09
16
+
17
+ ### Fixed
18
+
19
+ - **tui:** Keep identifiers, normalise accept keys and cache the model catalog
20
+
8
21
  ## [1.3.3] - 2026-10-09
9
22
 
10
23
  ### Fixed
@@ -264,6 +277,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
264
277
  - Options for `model`, `acceptKeys`, `maxChars`, `idleDelayMs`,
265
278
  `recentMessages` and `system`.
266
279
 
280
+ [1.3.5]: https://github.com/ozandogrultan/opencode-ghost/compare/v1.3.4...v1.3.5
281
+ [1.3.4]: https://github.com/ozandogrultan/opencode-ghost/compare/v1.3.3...v1.3.4
267
282
  [1.3.3]: https://github.com/ozandogrultan/opencode-ghost/compare/v1.3.2...v1.3.3
268
283
  [1.3.2]: https://github.com/ozandogrultan/opencode-ghost/compare/v1.3.1...v1.3.2
269
284
  [1.3.1]: https://github.com/ozandogrultan/opencode-ghost/compare/v1.3.0...v1.3.1
package/README.md CHANGED
@@ -87,7 +87,7 @@ copy, use `/absolute/path/to/config/plugins/opencode-ghost`.
87
87
  | ---------------- | ---------- | ------------------- | ------------------------------------------------------------- |
88
88
  | `enabled` | `boolean` | `true` | Initial state; `/suggest` toggles it at runtime (persisted). |
89
89
  | `model` | `string` | OpenCode small default | Explicit `provider/model` override. Otherwise uses the effective title-agent model or OpenCode's small-model selection policy. |
90
- | `acceptKeys` | `string[]` | `["tab", "right"]` | Key names as reported by the terminal (`tab`, `right`, ...). |
90
+ | `acceptKeys` | `string[]` | `["tab", "right"]` | Key names as reported by the terminal (`tab`, `right`, ...). Modifier aliases (`meta`, `option`, `cmd`, `control`) are normalised; keys with unknown modifiers are ignored. |
91
91
  | `maxChars` | `number` | `120` | Maximum suggestion length. |
92
92
  | `idleDelayMs` | `number` | `500` | Debounce after a turn finishes before generating. |
93
93
  | `recentMessages` | `number` | `10` | How many recent messages feed the suggestion prompt. |
@@ -120,8 +120,10 @@ the first enabled, active text-input/text-output catalog model in family order
120
120
  `gpt-luna`, `gemini-flash-lite`, `gemini-flash`, `claude-haiku`.
121
121
  Like OpenCode's title generation, an override, title or small model without a
122
122
  configured variant uses its first supported `none`, `minimal` or `low` variant.
123
- Catalog IDs are used directly. No matching small model means a warning and no
124
- suggestion. Ghost never uses the main model as a generation fallback or retries
123
+ Catalog IDs are used directly. The model catalog is cached for five minutes
124
+ (cleared by `/suggest model` and re-enabling, and refetched once before reporting
125
+ no small model); the agent list is read on every generation. No matching small
126
+ model means a warning and no suggestion. Ghost never uses the main model as a generation fallback or retries
125
127
  with another provider. An explicit override or configured title model may use
126
128
  a different provider from the session's primary model.
127
129
 
@@ -141,7 +143,7 @@ When enabling, a suggestion is generated immediately for the current session.
141
143
  ownership. Host hint/color updates are retained while the ghost is visible;
142
144
  dismissal restores only values still owned by Ghost, including rich hints.
143
145
  - Accepting uses the composer editor's `insertText` directly, without submitting.
144
- - Typing, pasting, navigation, a new execution, disabling and unloading cancel
146
+ - Typing, pasting, undo/redo, leaving the session, a new execution, disabling and unloading cancel
145
147
  pending generation. Duplicate completion events do not generate again.
146
148
  - Retains only one suggestion, bounded by `maxChars`, for the visible session.
147
149
  Acceptance, a new turn, session changes, disabling, model changes and unloading
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-ghost",
3
- "version": "1.3.3",
3
+ "version": "1.3.5",
4
4
  "description": "Stateless inline next-prompt ghosts for the empty OpenCode V2 composer, accepted with Tab or Right.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/composer.ts CHANGED
@@ -1,12 +1,19 @@
1
1
  import type { KeyEvent, KeyHandler, TextareaRenderable } from "@opentui/core"
2
2
 
3
3
  export function editsComposer(event: { name: string; sequence: string; ctrl: boolean; meta: boolean; option?: boolean; super?: boolean; hyper?: boolean }): boolean {
4
- if (event.ctrl && !event.meta && !event.option && !event.super && !event.hyper) return ["v", "h", "d", "k", "u", "w", "j", "m"].includes(event.name)
4
+ if (event.ctrl && !event.meta && !event.option && !event.super && !event.hyper) return ["v", "h", "d", "k", "u", "w", "j", "m", "-", "."].includes(event.name)
5
+ if (event.super && !event.ctrl && !event.meta && !event.option && !event.hyper && event.name === "z") return true
5
6
  if (event.ctrl || event.meta || event.option || event.super || event.hyper) return false
6
7
  if (["return", "enter", "linefeed", "backspace", "delete", "space"].includes(event.name)) return true
7
8
  return [...event.sequence].length === 1 && !/[\u0000-\u001f\u007f]/.test(event.sequence)
8
9
  }
9
10
 
11
+ export function removesOnly(event: { name: string; ctrl: boolean; meta: boolean; option?: boolean; super?: boolean; hyper?: boolean }): boolean {
12
+ if (event.ctrl && !event.meta && !event.option && !event.super && !event.hyper) return ["h", "d", "k", "u", "w"].includes(event.name)
13
+ if (event.ctrl || event.meta || event.option || event.super || event.hyper) return false
14
+ return event.name === "backspace" || event.name === "delete"
15
+ }
16
+
10
17
  export function observeComposerInput(input: KeyHandler, preserve: (event: KeyEvent) => boolean, cancel: () => void): () => void {
11
18
  const onKeypress = (event: KeyEvent) => {
12
19
  if (editsComposer(event) && !preserve(event)) cancel()
@@ -78,19 +85,35 @@ export function composerAction(editor: Editor | undefined, focused: () => unknow
78
85
  if (editor.plainText.length !== 0) return false
79
86
  try {
80
87
  editor.insertText(text)
81
- if (editor.plainText !== text) return false
82
- return true
83
- } catch {
84
- return false
85
- }
88
+ } catch {}
89
+ return true
86
90
  }
87
91
 
88
92
  export function keyName(event: { name: string; ctrl: boolean; meta: boolean; shift: boolean; option?: boolean; super?: boolean; hyper?: boolean }): string {
89
93
  return [event.ctrl && "ctrl", (event.meta || event.option) && "alt", event.shift && "shift", event.super && "super", event.hyper && "hyper", event.name].filter(Boolean).join("+")
90
94
  }
91
95
 
96
+ const MODIFIERS = ["ctrl", "alt", "shift", "super", "hyper"]
97
+
98
+ const KEY_ALIASES: Record<string, string> = {
99
+ control: "ctrl",
100
+ meta: "alt",
101
+ option: "alt",
102
+ opt: "alt",
103
+ cmd: "super",
104
+ command: "super",
105
+ win: "super",
106
+ esc: "escape",
107
+ }
108
+
92
109
  export function canonicalKey(key: string): string {
93
- const parts = key.trim().toLowerCase().split("+")
110
+ const parts = key.trim().toLowerCase().split("+").map((part) => KEY_ALIASES[part] ?? part)
94
111
  const name = parts.pop() ?? ""
95
- return [...["ctrl", "alt", "shift", "super", "hyper"].filter((modifier) => parts.includes(modifier)), name].join("+")
112
+ return [...MODIFIERS.filter((modifier) => parts.includes(modifier)), name].join("+")
113
+ }
114
+
115
+ export function isValidKey(key: string): boolean {
116
+ const parts = key.trim().toLowerCase().split("+").map((part) => part.trim())
117
+ const name = parts.pop()
118
+ return !!name && parts.every((part) => MODIFIERS.includes(KEY_ALIASES[part] ?? part))
96
119
  }
package/src/keymap.ts CHANGED
@@ -22,24 +22,29 @@ export function acceptShortcuts(acceptKeys: readonly string[], shortcuts: (id: s
22
22
  }))
23
23
  }
24
24
 
25
+ export function ghostBaseLayer(composerCommands: KeymapCommand[]): KeymapLayer {
26
+ return { mode: "base", priority: 2, commands: composerCommands }
27
+ }
28
+
29
+ export function ghostSuggestLayer(enabled: boolean, suggest: KeymapCommand["run"]): KeymapLayer {
30
+ return {
31
+ mode: "global",
32
+ commands: [{
33
+ id: "ghost.suggest",
34
+ title: `Prompt suggestions: ${enabled ? "on" : "off"}`,
35
+ description: "Toggle the suggested next prompt",
36
+ group: "Prompt",
37
+ palette: true,
38
+ slash: { name: "suggest", arguments: true },
39
+ run: suggest,
40
+ }],
41
+ }
42
+ }
43
+
25
44
  export function ghostKeymapLayers(
26
45
  composerCommands: KeymapCommand[],
27
46
  enabled: boolean,
28
47
  suggest: KeymapCommand["run"],
29
48
  ): KeymapLayer[] {
30
- return [
31
- { mode: "base", priority: 2, commands: composerCommands },
32
- {
33
- mode: "global",
34
- commands: [{
35
- id: "ghost.suggest",
36
- title: `Prompt suggestions: ${enabled ? "on" : "off"}`,
37
- description: "Toggle the suggested next prompt",
38
- group: "Prompt",
39
- palette: true,
40
- slash: { name: "suggest", arguments: true },
41
- run: suggest,
42
- }],
43
- },
44
- ]
49
+ return [ghostBaseLayer(composerCommands), ghostSuggestLayer(enabled, suggest)]
45
50
  }
package/src/lifecycle.ts CHANGED
@@ -1,4 +1,4 @@
1
- export function createLifecycle(delay: number, allowed: (sessionID: string) => boolean, generate: (sessionID: string, signal: AbortSignal) => Promise<void>, clear: () => void) {
1
+ export function createLifecycle(delay: number, allowed: (sessionID: string) => boolean, generate: (sessionID: string, signal: AbortSignal) => Promise<void>, clear: () => void, observed: (sessionID: string) => boolean = allowed) {
2
2
  let timer: ReturnType<typeof setTimeout> | undefined
3
3
  let controller: AbortController | undefined
4
4
  let disposed = false
@@ -27,12 +27,14 @@ export function createLifecycle(delay: number, allowed: (sessionID: string) => b
27
27
  cancel,
28
28
  run,
29
29
  succeeded(id: string, sessionID: string) {
30
- if (disposed || !allowed(sessionID) || completed.has(id)) return
30
+ if (disposed || !observed(sessionID) || completed.has(id)) return
31
31
  completed.add(id)
32
32
  if (completed.size > COMPLETION_HISTORY_LIMIT) completed.delete(completed.values().next().value!)
33
33
  cancel()
34
34
  timer = setTimeout(() => { timer = undefined; void run(sessionID) }, delay)
35
35
  },
36
+ active: () => timer !== undefined || controller !== undefined,
37
+ resetWarning() { warned = false },
36
38
  warn(show: () => void) {
37
39
  if (disposed || warned) return
38
40
  warned = true
package/src/options.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { parseModel } from "./text"
2
- import { canonicalKey } from "./composer"
2
+ import { canonicalKey, isValidKey } from "./composer"
3
3
 
4
4
  export type GhostOptions = {
5
5
  enabled?: boolean
@@ -57,7 +57,7 @@ const DEFAULTS = {
57
57
  recentMessages: 10,
58
58
  }
59
59
 
60
- const REMOVED_OPTION_KEYS = ["endpoint", "apiKey", "internalSessionMarkerDir", "argHints", "backOnEmptyLeft"] as const
60
+ const REMOVED_OPTION_KEYS = ["endpoint", "apiKey", "internalSessionMarkerDir", "argHints"] as const
61
61
 
62
62
  export function removedOptionKeys(raw: Readonly<Record<string, unknown>> | undefined): string[] {
63
63
  if (!raw) return []
@@ -70,7 +70,7 @@ export function resolveOptions(options: Readonly<Record<string, unknown>> | unde
70
70
  const idleDelayMs = input.idleDelayMs
71
71
  const recentMessages = input.recentMessages
72
72
  const acceptKeys = Array.isArray(input.acceptKeys)
73
- ? [...new Set(input.acceptKeys.filter((key) => typeof key === "string" && key.trim() && key.trim().split("+").every((part) => part.trim())).map(canonicalKey))]
73
+ ? [...new Set(input.acceptKeys.filter((key) => typeof key === "string" && key.trim() && isValidKey(key)).map(canonicalKey))]
74
74
  : []
75
75
  return {
76
76
  enabled: typeof input.enabled === "boolean" ? input.enabled : DEFAULTS.enabled,
package/src/text.ts CHANGED
@@ -4,6 +4,10 @@ export type SuggestionModel = { providerID: string; modelID: string; variant?: s
4
4
 
5
5
  export const NO_SMALL_MODEL = "No default small model available; set /suggest model provider/model"
6
6
 
7
+ export function isNoSmallModel(error: unknown): boolean {
8
+ return error instanceof Error && error.message === NO_SMALL_MODEL
9
+ }
10
+
7
11
  export type SmallModelClient = {
8
12
  agent: Pick<OpenCodeClient["agent"], "list">
9
13
  model: Pick<OpenCodeClient["model"], "default" | "list">
@@ -20,11 +24,71 @@ export function selectSmallModel(models: readonly ModelInfo[], providerID: strin
20
24
  return undefined
21
25
  }
22
26
 
27
+ export type Catalog = {
28
+ list(location: LocationRef, signal: AbortSignal, fresh?: boolean): Promise<{ models: readonly ModelInfo[]; cached: boolean }>
29
+ clear(): void
30
+ }
31
+
32
+ export const CATALOG_TTL_MS = 5 * 60_000
33
+
34
+ export function createCatalog(
35
+ client: Pick<SmallModelClient, "model">,
36
+ ttlMs: number = CATALOG_TTL_MS,
37
+ now: () => number = Date.now,
38
+ ): Catalog {
39
+ const entries = new Map<string, { at: number; models: readonly ModelInfo[] }>()
40
+ return {
41
+ async list(location, signal, fresh = false) {
42
+ const key = JSON.stringify(location)
43
+ const hit = entries.get(key)
44
+ if (hit && !fresh && now() - hit.at < ttlMs) return { models: hit.models, cached: true }
45
+ const result = await client.model.list({ location }, { signal })
46
+ entries.set(key, { at: now(), models: result.data })
47
+ return { models: result.data, cached: false }
48
+ },
49
+ clear: () => entries.clear(),
50
+ }
51
+ }
52
+
53
+ function directCatalog(client: Pick<SmallModelClient, "model">): Catalog {
54
+ return {
55
+ async list(location, signal) {
56
+ return { models: (await client.model.list({ location }, { signal })).data, cached: false }
57
+ },
58
+ clear() {},
59
+ }
60
+ }
61
+
23
62
  export async function resolveSmallModel(
24
63
  client: SmallModelClient,
25
64
  location: LocationRef,
26
65
  signal: AbortSignal,
27
66
  session?: { model?: { providerID: string }; agent?: string },
67
+ catalog: Catalog = directCatalog(client),
68
+ ): Promise<SuggestionModel | undefined> {
69
+ const attempt = async (fresh: boolean) => {
70
+ let cached = false
71
+ try {
72
+ return { model: await resolveFromCatalog(client, location, signal, session, async (...args) => {
73
+ const listed = await catalog.list(args[0], args[1], fresh)
74
+ cached = listed.cached
75
+ return listed.models
76
+ }) }
77
+ } catch (error) {
78
+ if (cached && isNoSmallModel(error) && !signal.aborted) return undefined
79
+ throw error
80
+ }
81
+ }
82
+ const first = await attempt(false)
83
+ return first ? first.model : (await attempt(true))?.model
84
+ }
85
+
86
+ async function resolveFromCatalog(
87
+ client: SmallModelClient,
88
+ location: LocationRef,
89
+ signal: AbortSignal,
90
+ session: { model?: { providerID: string }; agent?: string } | undefined,
91
+ models: (location: LocationRef, signal: AbortSignal) => Promise<readonly ModelInfo[]>,
28
92
  ): Promise<SuggestionModel | undefined> {
29
93
  if (signal.aborted) return undefined
30
94
  const agents = await client.agent.list({ location }, { signal })
@@ -37,17 +101,17 @@ export async function resolveSmallModel(
37
101
  if (signal.aborted) return undefined
38
102
  providerID = primary.data?.providerID
39
103
  }
40
- const catalog = await client.model.list({ location }, { signal })
104
+ const catalog = await models(location, signal)
41
105
  if (signal.aborted) return undefined
42
106
  if (configured) {
43
- const info = catalog.data.find((model) => model.providerID === configured.providerID && model.id === configured.id)
107
+ const info = catalog.find((model) => model.providerID === configured.providerID && model.id === configured.id)
44
108
  return withLowEffortVariant({ providerID: configured.providerID, modelID: configured.id }, info)
45
109
  }
46
- providerID ??= catalog.data.find((model) => model.enabled && isTextModel(model))?.providerID
110
+ providerID ??= catalog.find((model) => model.enabled && isTextModel(model))?.providerID
47
111
  if (!providerID) throw new Error(NO_SMALL_MODEL)
48
- const model = selectSmallModel(catalog.data, providerID)
112
+ const model = selectSmallModel(catalog, providerID)
49
113
  if (!model) throw new Error(NO_SMALL_MODEL)
50
- return withLowEffortVariant(model, catalog.data.find((info) => info.providerID === model.providerID && info.id === model.modelID))
114
+ return withLowEffortVariant(model, catalog.find((info) => info.providerID === model.providerID && info.id === model.modelID))
51
115
  }
52
116
 
53
117
  export async function resolveExplicitModel(
@@ -55,12 +119,17 @@ export async function resolveExplicitModel(
55
119
  location: LocationRef,
56
120
  signal: AbortSignal,
57
121
  model: SuggestionModel,
122
+ catalog: Catalog = directCatalog(client),
58
123
  ): Promise<SuggestionModel | undefined> {
59
124
  if (signal.aborted) return undefined
60
125
  if (model.variant) return model
61
- const catalog = await client.model.list({ location }, { signal })
62
- if (signal.aborted) return undefined
63
- return withLowEffortVariant(model, catalog.data.find((info) => info.providerID === model.providerID && info.id === model.modelID))
126
+ try {
127
+ const listed = await catalog.list(location, signal)
128
+ if (signal.aborted) return undefined
129
+ return withLowEffortVariant(model, listed.models.find((info) => info.providerID === model.providerID && info.id === model.modelID))
130
+ } catch {
131
+ return signal.aborted ? undefined : model
132
+ }
64
133
  }
65
134
 
66
135
  const LOW_EFFORT_VARIANTS = ["none", "minimal", "low"]
@@ -105,13 +174,16 @@ export function normalize(raw: string, maxChars: number): string | undefined {
105
174
  .find((line) => line.length > 0)
106
175
  if (!first) return undefined
107
176
  const cleaned = first
177
+ .replace(/\*\*([^*]+)\*\*/g, "$1")
108
178
  .replace(/^[`"'*\-_#\s]+/, "")
109
179
  .replace(/[`"'*_#\s]+$/, "")
110
- .replace(/[*`_]+/g, "")
180
+ .replace(/`+/g, "")
181
+ .replace(/^next user message:\s*/i, "")
111
182
  .trim()
112
183
  if (!cleaned || /^none\.?$/i.test(cleaned)) return undefined
113
- if (cleaned.length <= maxChars) return cleaned
114
- return cleaned.slice(0, maxChars - 1).trimEnd() + "…"
184
+ const points = [...cleaned]
185
+ if (points.length <= maxChars) return cleaned
186
+ return points.slice(0, maxChars - 1).join("").trimEnd() + "…"
115
187
  }
116
188
 
117
189
  export function isEcho(suggestion: string, previous: string): boolean {
package/src/tui.tsx CHANGED
@@ -2,14 +2,14 @@
2
2
  import { Plugin } from "@opencode/plugin/tui"
3
3
  import { TextareaRenderable, InputRenderable, type BoxRenderable, type Renderable } from "@opentui/core"
4
4
  import { createEffect, createMemo, createRoot, createSignal, on, onCleanup } from "solid-js"
5
- import { composerAction, composerBlocker, isEmptyComposer, keyName, locateComposerEditor, observeComposerInput, type ComposerLookup } from "./composer"
5
+ import { composerAction, composerBlocker, isEmptyComposer, keyName, locateComposerEditor, observeComposerInput, removesOnly, type ComposerLookup } from "./composer"
6
6
  import { createDiagnostics, errorDetail, formatDiagnostic, formatDiagnostics, modelLabel, type DiagnosticEntry } from "./diagnostics"
7
7
  import { createLifecycle } from "./lifecycle"
8
- import { acceptCommand, acceptShortcuts, ghostKeymapLayers } from "./keymap"
8
+ import { acceptCommand, acceptShortcuts, ghostBaseLayer, ghostSuggestLayer } from "./keymap"
9
9
  import { parseSuggestCommand, removedOptionKeys, resolveOptions, suggestionModel } from "./options"
10
10
  import { createInlinePlaceholder, dimPlaceholderColor } from "./placeholder"
11
11
  import { generateSuggestion } from "./stateless"
12
- import { isEcho, normalize, resolveExplicitModel, resolveSmallModel, type SuggestionModel } from "./text"
12
+ import { createCatalog, isEcho, isNoSmallModel, normalize, resolveExplicitModel, resolveSmallModel, type SuggestionModel } from "./text"
13
13
  import { buildTranscript, lastUserText, suggestionPrompt, type TranscriptMessage } from "./transcript"
14
14
 
15
15
  type Suggestion = { sessionID: string; text: string }
@@ -42,8 +42,9 @@ export default Plugin.define({
42
42
  const [suggestion, setSuggestion] = createSignal<Suggestion | undefined>()
43
43
  const [composerRevision, setComposerRevision] = createSignal(0)
44
44
  const inline = createInlinePlaceholder()
45
- const ghostColor = createMemo(() => dimPlaceholderColor(context.theme.text.muted))
45
+ let ghostColor: () => ReturnType<typeof dimPlaceholderColor>
46
46
  const diagnostics = createDiagnostics()
47
+ const catalog = createCatalog(context.client)
47
48
 
48
49
  const note = (entry: Omit<DiagnosticEntry, "at">) => {
49
50
  const recorded = diagnostics.record(entry)
@@ -54,6 +55,7 @@ export default Plugin.define({
54
55
  }
55
56
 
56
57
  let disposed = false
58
+ let syncWarned = false
57
59
  const composers = new Map<string, { marker: BoxRenderable; normal: () => boolean }>()
58
60
 
59
61
  const isCurrentSession = (sessionID: string) => {
@@ -80,8 +82,10 @@ export default Plugin.define({
80
82
  const elapsed = () => Date.now() - started
81
83
  let model: SuggestionModel | undefined
82
84
  let failure: unknown
85
+ let syncing = true
83
86
  try {
84
87
  await context.data.session.message.sync(sessionID)
88
+ syncing = false
85
89
  if (signal.aborted || !canGenerate(sessionID)) return
86
90
  const messages = context.data.session.message.list(sessionID) as readonly TranscriptMessage[]
87
91
  const transcript = buildTranscript(messages, opts.recentMessages)
@@ -90,13 +94,10 @@ export default Plugin.define({
90
94
  const location = session?.location ?? context.location ?? context.data.location.default()
91
95
  const explicit = suggestionModel(state.model, opts.model)
92
96
  model = explicit
93
- ? await resolveExplicitModel(context.client, location, signal, explicit)
94
- : await resolveSmallModel(context.client, location, signal, session)
97
+ ? await resolveExplicitModel(context.client, location, signal, explicit, catalog)
98
+ : await resolveSmallModel(context.client, location, signal, session, catalog)
95
99
  if (signal.aborted || !canGenerate(sessionID)) return
96
- if (!model) {
97
- note({ sessionID, outcome: "unavailable", durationMs: elapsed() })
98
- return
99
- }
100
+ if (!model) return
100
101
  const raw = await generateSuggestion(
101
102
  context.client,
102
103
  suggestionPrompt(opts.system, transcript),
@@ -106,15 +107,13 @@ export default Plugin.define({
106
107
  () => canGenerate(sessionID),
107
108
  )
108
109
  const label = modelLabel(model)
109
- if (signal.aborted) {
110
- note({ sessionID, outcome: "aborted", model: label, durationMs: elapsed() })
111
- return
112
- }
110
+ if (signal.aborted) return
113
111
  if (failure) {
114
112
  note({ sessionID, outcome: "error", model: label, durationMs: elapsed(), detail: errorDetail(failure) })
115
113
  return
116
114
  }
117
115
  if (!raw) {
116
+ if (!canGenerate(sessionID)) return
118
117
  note({ sessionID, outcome: "empty", model: label, durationMs: elapsed() })
119
118
  return
120
119
  }
@@ -133,21 +132,28 @@ export default Plugin.define({
133
132
  note({ sessionID, outcome: "ok", model: label, durationMs: elapsed(), chars: clean.length })
134
133
  } catch (error) {
135
134
  if (signal.aborted) return
136
- warnGeneration(error)
135
+ if (syncing) {
136
+ if (!disposed && !syncWarned) {
137
+ syncWarned = true
138
+ context.ui.toast.show({ title: "Ghost", message: "Suggestions unavailable: session messages could not sync.", variant: "warning" })
139
+ }
140
+ } else warnGeneration(error)
137
141
  note({
138
142
  sessionID,
139
- outcome: "error",
143
+ outcome: isNoSmallModel(error) ? "unavailable" : "error",
140
144
  ...(model ? { model: modelLabel(model) } : {}),
141
145
  durationMs: elapsed(),
142
146
  detail: errorDetail(error),
143
147
  })
148
+ } finally {
149
+ if (signal.aborted) note({ sessionID, outcome: "aborted", ...(model ? { model: modelLabel(model) } : {}), durationMs: elapsed() })
144
150
  }
145
151
  }
146
152
 
147
153
  const lifecycle = createLifecycle(opts.idleDelayMs, canGenerate, generate, () => {
148
154
  inline.clear()
149
155
  setSuggestion(undefined)
150
- })
156
+ }, (sessionID) => !disposed && state.enabled && isCurrentSession(sessionID))
151
157
  const cancelSuggestion = lifecycle.cancel
152
158
 
153
159
  const offSucceeded = context.data.on("session.execution.succeeded", (event) => {
@@ -166,23 +172,28 @@ export default Plugin.define({
166
172
  const displayLog = createDiagnostics()
167
173
  let lastDisplay: string | undefined
168
174
 
169
- const displayStatus = (current: Suggestion): string => {
170
- if (!canGenerate(current.sessionID)) return "session busy, hidden or suggestions disabled"
175
+ const inspect = (current: Suggestion) => {
171
176
  const entry = composers.get(current.sessionID)
172
177
  const found = lookupComposer(entry?.marker)
173
- if (!found.editor) return found.reason
174
- const blocker = composerBlocker(found.editor, context.keymap.mode.current(), entry?.normal() === true, context.renderer.hasSelection)
175
- if (blocker) return blocker
176
- return inline.visible(found.editor, current.text) ? "shown" : "placeholder not applied (host overrode it)"
178
+ const allowed = canGenerate(current.sessionID)
179
+ const blocker = found.editor
180
+ ? composerBlocker(found.editor, context.keymap.mode.current(), entry?.normal() === true, context.renderer.hasSelection)
181
+ : found.reason
182
+ return { editor: found.editor, allowed, blocker }
177
183
  }
178
184
 
179
- const trackDisplay = () => {
180
- const current = suggestion()
185
+ const displayStatus = (current: Suggestion, view = inspect(current)): string => {
186
+ if (!view.allowed) return "session busy, hidden or suggestions disabled"
187
+ if (view.blocker) return view.blocker
188
+ return inline.visible(view.editor, current.text) ? "shown" : "placeholder not applied (host overrode it)"
189
+ }
190
+
191
+ const trackDisplay = (current: Suggestion | undefined, view?: ReturnType<typeof inspect>) => {
181
192
  if (!current) {
182
193
  lastDisplay = undefined
183
194
  return
184
195
  }
185
- const status = displayStatus(current)
196
+ const status = displayStatus(current, view)
186
197
  if (status === lastDisplay) return
187
198
  lastDisplay = status
188
199
  const recorded = displayLog.record({
@@ -202,12 +213,19 @@ export default Plugin.define({
202
213
  const syncInline = () => {
203
214
  composerRevision()
204
215
  const current = suggestion()
205
- const { editor, normal } = current ? getComposer(current.sessionID) : { editor: undefined, normal: false }
206
- inline.sync(editor, current?.text, ghostColor(), !!current && canGenerate(current.sessionID) && !composerBlocker(editor, context.keymap.mode.current(), normal, context.renderer.hasSelection))
207
- trackDisplay()
216
+ const color = ghostColor()
217
+ if (!current) {
218
+ inline.sync(undefined, undefined, color, false)
219
+ trackDisplay(undefined)
220
+ return
221
+ }
222
+ const view = inspect(current)
223
+ inline.sync(view.editor, current.text, color, view.allowed && !view.blocker)
224
+ trackDisplay(current, view)
208
225
  }
209
226
 
210
227
  const disposeRouteWatcher = createRoot((dispose) => {
228
+ ghostColor = createMemo(() => dimPlaceholderColor(context.theme.text.muted))
211
229
  createEffect(on(() => {
212
230
  const route = context.ui.router.current()
213
231
  return route.type === "session" ? route.sessionID : route.type
@@ -234,22 +252,42 @@ export default Plugin.define({
234
252
  return true
235
253
  }
236
254
 
255
+ const targetedEditor = () => {
256
+ const route = context.ui.router.current()
257
+ if (route.type !== "session") return undefined
258
+ const editor = getComposer(route.sessionID).editor
259
+ return editor && editor === context.renderer.currentFocusedEditor ? editor : undefined
260
+ }
261
+
262
+ const pending = () => lifecycle.active() || suggestion() !== undefined
263
+
237
264
  const offInput = observeComposerInput(context.renderer.keyInput, (event) => {
238
- syncInline()
239
- const key = keyName(event)
265
+ if (!pending()) return true
266
+ const editor = targetedEditor()
267
+ if (!editor) return true
268
+ if (editor.plainText === "" && removesOnly(event)) return true
240
269
  const current = suggestion()
241
- return Boolean(current && inline.visible(getComposer(current.sessionID).editor, current.text) && acceptShortcuts(opts.acceptKeys, context.keymap.shortcuts).has(key) && canGenerate(current.sessionID) && isComposerEmpty(current.sessionID))
242
- }, () => { lifecycle.interrupt(); inline.clear() })
270
+ if (!current) return false
271
+ syncInline()
272
+ return Boolean(inline.visible(editor, current.text) && acceptShortcuts(opts.acceptKeys, context.keymap.shortcuts).has(keyName(event)) && canGenerate(current.sessionID) && isComposerEmpty(current.sessionID))
273
+ }, () => {
274
+ if (!pending() || !targetedEditor()) return
275
+ lifecycle.interrupt()
276
+ inline.clear()
277
+ })
243
278
 
244
- const commandLayers = () => ghostKeymapLayers([
245
- ...opts.acceptKeys.map((key) => acceptCommand(key, () => {
246
- const route = context.ui.router.current()
247
- return route.type === "session" ? route.sessionID : undefined
248
- }, () => suggestion()?.sessionID, act)),
249
- ], state.enabled, async (input) => {
279
+ const acceptLayer = () => ghostBaseLayer(
280
+ opts.acceptKeys.map((key) => acceptCommand(key, () => {
281
+ const route = context.ui.router.current()
282
+ return route.type === "session" ? route.sessionID : undefined
283
+ }, () => suggestion()?.sessionID, act)),
284
+ )
285
+ const suggestLayer = () => ghostSuggestLayer(state.enabled, async (input) => {
250
286
  const command = parseSuggestCommand(input)
251
287
  if (command.type === "model") {
252
288
  cancelSuggestion()
289
+ lifecycle.resetWarning()
290
+ catalog.clear()
253
291
  await updateState((draft) => { draft.model = command.model })
254
292
  context.ui.toast.show({ message: `Suggestion model: ${state.model ?? opts.model ?? "OpenCode small default"}` })
255
293
  return
@@ -296,11 +334,12 @@ export default Plugin.define({
296
334
  return
297
335
  }
298
336
  context.ui.toast.show({ message: "Prompt suggestions: on" })
337
+ catalog.clear()
299
338
  const route = context.ui.router.current()
300
339
  if (route.type === "session") void lifecycle.run(route.sessionID)
301
340
  })
302
- context.keymap.layer(() => commandLayers()[0]!)
303
- context.keymap.layer(() => commandLayers()[1]!)
341
+ context.keymap.layer(acceptLayer)
342
+ context.keymap.layer(suggestLayer)
304
343
 
305
344
  const offComposer = context.ui.slot({
306
345
  append: "prompt.footer",