opencode-ghost 1.3.2 → 1.3.4

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,18 @@ 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.4] - 2026-10-09
9
+
10
+ ### Fixed
11
+
12
+ - **tui:** Keep identifiers, normalise accept keys and cache the model catalog
13
+
14
+ ## [1.3.3] - 2026-10-09
15
+
16
+ ### Fixed
17
+
18
+ - **tui:** Keep the end of long assistant messages in the transcript
19
+
8
20
  ## [1.3.2] - 2026-10-09
9
21
 
10
22
  ### Fixed
@@ -258,6 +270,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
258
270
  - Options for `model`, `acceptKeys`, `maxChars`, `idleDelayMs`,
259
271
  `recentMessages` and `system`.
260
272
 
273
+ [1.3.4]: https://github.com/ozandogrultan/opencode-ghost/compare/v1.3.3...v1.3.4
274
+ [1.3.3]: https://github.com/ozandogrultan/opencode-ghost/compare/v1.3.2...v1.3.3
261
275
  [1.3.2]: https://github.com/ozandogrultan/opencode-ghost/compare/v1.3.1...v1.3.2
262
276
  [1.3.1]: https://github.com/ozandogrultan/opencode-ghost/compare/v1.3.0...v1.3.1
263
277
  [1.3.0]: https://github.com/ozandogrultan/opencode-ghost/compare/v1.2.0...v1.3.0
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; 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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-ghost",
3
- "version": "1.3.2",
3
+ "version": "1.3.4",
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
@@ -7,6 +7,12 @@ export function editsComposer(event: { name: string; sequence: string; ctrl: boo
7
7
  return [...event.sequence].length === 1 && !/[\u0000-\u001f\u007f]/.test(event.sequence)
8
8
  }
9
9
 
10
+ export function removesOnly(event: { name: string; ctrl: boolean; meta: boolean; option?: boolean; super?: boolean; hyper?: boolean }): boolean {
11
+ if (event.ctrl && !event.meta && !event.option && !event.super && !event.hyper) return ["h", "d", "k", "u", "w"].includes(event.name)
12
+ if (event.ctrl || event.meta || event.option || event.super || event.hyper) return false
13
+ return event.name === "backspace" || event.name === "delete"
14
+ }
15
+
10
16
  export function observeComposerInput(input: KeyHandler, preserve: (event: KeyEvent) => boolean, cancel: () => void): () => void {
11
17
  const onKeypress = (event: KeyEvent) => {
12
18
  if (editsComposer(event) && !preserve(event)) cancel()
@@ -89,8 +95,27 @@ export function keyName(event: { name: string; ctrl: boolean; meta: boolean; shi
89
95
  return [event.ctrl && "ctrl", (event.meta || event.option) && "alt", event.shift && "shift", event.super && "super", event.hyper && "hyper", event.name].filter(Boolean).join("+")
90
96
  }
91
97
 
98
+ const MODIFIERS = ["ctrl", "alt", "shift", "super", "hyper"]
99
+
100
+ const KEY_ALIASES: Record<string, string> = {
101
+ control: "ctrl",
102
+ meta: "alt",
103
+ option: "alt",
104
+ opt: "alt",
105
+ cmd: "super",
106
+ command: "super",
107
+ win: "super",
108
+ esc: "escape",
109
+ }
110
+
92
111
  export function canonicalKey(key: string): string {
93
- const parts = key.trim().toLowerCase().split("+")
112
+ const parts = key.trim().toLowerCase().split("+").map((part) => KEY_ALIASES[part] ?? part)
94
113
  const name = parts.pop() ?? ""
95
- return [...["ctrl", "alt", "shift", "super", "hyper"].filter((modifier) => parts.includes(modifier)), name].join("+")
114
+ return [...MODIFIERS.filter((modifier) => parts.includes(modifier)), name].join("+")
115
+ }
116
+
117
+ export function isValidKey(key: string): boolean {
118
+ const parts = key.trim().toLowerCase().split("+").map((part) => part.trim())
119
+ const name = parts.pop()
120
+ return !!name && parts.every((part) => MODIFIERS.includes(KEY_ALIASES[part] ?? part))
96
121
  }
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
@@ -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,13 @@ 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 })
126
+ const listed = await catalog.list(location, signal)
62
127
  if (signal.aborted) return undefined
63
- return withLowEffortVariant(model, catalog.data.find((info) => info.providerID === model.providerID && info.id === model.modelID))
128
+ return withLowEffortVariant(model, listed.models.find((info) => info.providerID === model.providerID && info.id === model.modelID))
64
129
  }
65
130
 
66
131
  const LOW_EFFORT_VARIANTS = ["none", "minimal", "low"]
@@ -92,6 +157,12 @@ export function clip(text: string, max: number): string {
92
157
  return value.slice(0, max - 1).trimEnd() + "…"
93
158
  }
94
159
 
160
+ export function clipTail(text: string, max: number): string {
161
+ const value = collapse(text)
162
+ if (value.length <= max) return value
163
+ return "…" + value.slice(value.length - (max - 1)).trimStart()
164
+ }
165
+
95
166
  export function normalize(raw: string, maxChars: number): string | undefined {
96
167
  const first = raw
97
168
  .split(/\r?\n/)
@@ -99,13 +170,16 @@ export function normalize(raw: string, maxChars: number): string | undefined {
99
170
  .find((line) => line.length > 0)
100
171
  if (!first) return undefined
101
172
  const cleaned = first
173
+ .replace(/\*\*([^*]+)\*\*/g, "$1")
102
174
  .replace(/^[`"'*\-_#\s]+/, "")
103
175
  .replace(/[`"'*_#\s]+$/, "")
104
- .replace(/[*`_]+/g, "")
176
+ .replace(/`+/g, "")
177
+ .replace(/^next user message:\s*/i, "")
105
178
  .trim()
106
179
  if (!cleaned || /^none\.?$/i.test(cleaned)) return undefined
107
- if (cleaned.length <= maxChars) return cleaned
108
- return cleaned.slice(0, maxChars - 1).trimEnd() + "…"
180
+ const points = [...cleaned]
181
+ if (points.length <= maxChars) return cleaned
182
+ return points.slice(0, maxChars - 1).join("").trimEnd() + "…"
109
183
  }
110
184
 
111
185
  export function isEcho(suggestion: string, previous: string): boolean {
package/src/transcript.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { clip } from "./text"
1
+ import { clip, clipTail } from "./text"
2
2
 
3
3
  const MAX_MESSAGE_CHARS = 800
4
4
  const MAX_TRANSCRIPT_CHARS = 6000
@@ -25,7 +25,7 @@ export function buildTranscript(messages: readonly TranscriptMessage[], recentMe
25
25
  const entries = messages.map(messageText).filter((entry) => entry && entry.text.trim())
26
26
  for (const entry of entries.slice(-recentMessages)) {
27
27
  if (!entry) continue
28
- lines.push(`${entry.role}: ${clip(entry.text, MAX_MESSAGE_CHARS)}`)
28
+ lines.push(`${entry.role}: ${(entry.role === "Assistant" ? clipTail : clip)(entry.text, MAX_MESSAGE_CHARS)}`)
29
29
  }
30
30
  if (lines.length === 0) return ""
31
31
  return `${lines.join("\n").slice(-MAX_TRANSCRIPT_CHARS)}\n\nTask: write the user's next message.`
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 }
@@ -44,6 +44,7 @@ export default Plugin.define({
44
44
  const inline = createInlinePlaceholder()
45
45
  const ghostColor = createMemo(() => dimPlaceholderColor(context.theme.text.muted))
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)
@@ -90,13 +91,10 @@ export default Plugin.define({
90
91
  const location = session?.location ?? context.location ?? context.data.location.default()
91
92
  const explicit = suggestionModel(state.model, opts.model)
92
93
  model = explicit
93
- ? await resolveExplicitModel(context.client, location, signal, explicit)
94
- : await resolveSmallModel(context.client, location, signal, session)
94
+ ? await resolveExplicitModel(context.client, location, signal, explicit, catalog)
95
+ : await resolveSmallModel(context.client, location, signal, session, catalog)
95
96
  if (signal.aborted || !canGenerate(sessionID)) return
96
- if (!model) {
97
- note({ sessionID, outcome: "unavailable", durationMs: elapsed() })
98
- return
99
- }
97
+ if (!model) return
100
98
  const raw = await generateSuggestion(
101
99
  context.client,
102
100
  suggestionPrompt(opts.system, transcript),
@@ -115,6 +113,7 @@ export default Plugin.define({
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
  }
@@ -136,7 +135,7 @@ export default Plugin.define({
136
135
  warnGeneration(error)
137
136
  note({
138
137
  sessionID,
139
- outcome: "error",
138
+ outcome: isNoSmallModel(error) ? "unavailable" : "error",
140
139
  ...(model ? { model: modelLabel(model) } : {}),
141
140
  durationMs: elapsed(),
142
141
  detail: errorDetail(error),
@@ -147,7 +146,7 @@ export default Plugin.define({
147
146
  const lifecycle = createLifecycle(opts.idleDelayMs, canGenerate, generate, () => {
148
147
  inline.clear()
149
148
  setSuggestion(undefined)
150
- })
149
+ }, (sessionID) => !disposed && state.enabled && isCurrentSession(sessionID))
151
150
  const cancelSuggestion = lifecycle.cancel
152
151
 
153
152
  const offSucceeded = context.data.on("session.execution.succeeded", (event) => {
@@ -166,23 +165,28 @@ export default Plugin.define({
166
165
  const displayLog = createDiagnostics()
167
166
  let lastDisplay: string | undefined
168
167
 
169
- const displayStatus = (current: Suggestion): string => {
170
- if (!canGenerate(current.sessionID)) return "session busy, hidden or suggestions disabled"
168
+ const inspect = (current: Suggestion) => {
171
169
  const entry = composers.get(current.sessionID)
172
170
  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)"
171
+ const allowed = canGenerate(current.sessionID)
172
+ const blocker = found.editor
173
+ ? composerBlocker(found.editor, context.keymap.mode.current(), entry?.normal() === true, context.renderer.hasSelection)
174
+ : found.reason
175
+ return { editor: found.editor, allowed, blocker }
177
176
  }
178
177
 
179
- const trackDisplay = () => {
180
- const current = suggestion()
178
+ const displayStatus = (current: Suggestion, view = inspect(current)): string => {
179
+ if (!view.allowed) return "session busy, hidden or suggestions disabled"
180
+ if (view.blocker) return view.blocker
181
+ return inline.visible(view.editor, current.text) ? "shown" : "placeholder not applied (host overrode it)"
182
+ }
183
+
184
+ const trackDisplay = (current: Suggestion | undefined, view?: ReturnType<typeof inspect>) => {
181
185
  if (!current) {
182
186
  lastDisplay = undefined
183
187
  return
184
188
  }
185
- const status = displayStatus(current)
189
+ const status = displayStatus(current, view)
186
190
  if (status === lastDisplay) return
187
191
  lastDisplay = status
188
192
  const recorded = displayLog.record({
@@ -202,9 +206,15 @@ export default Plugin.define({
202
206
  const syncInline = () => {
203
207
  composerRevision()
204
208
  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()
209
+ const color = ghostColor()
210
+ if (!current) {
211
+ inline.sync(undefined, undefined, color, false)
212
+ trackDisplay(undefined)
213
+ return
214
+ }
215
+ const view = inspect(current)
216
+ inline.sync(view.editor, current.text, color, view.allowed && !view.blocker)
217
+ trackDisplay(current, view)
208
218
  }
209
219
 
210
220
  const disposeRouteWatcher = createRoot((dispose) => {
@@ -234,22 +244,42 @@ export default Plugin.define({
234
244
  return true
235
245
  }
236
246
 
247
+ const targetedEditor = () => {
248
+ const route = context.ui.router.current()
249
+ if (route.type !== "session") return undefined
250
+ const editor = getComposer(route.sessionID).editor
251
+ return editor && editor === context.renderer.currentFocusedEditor ? editor : undefined
252
+ }
253
+
254
+ const pending = () => lifecycle.active() || suggestion() !== undefined
255
+
237
256
  const offInput = observeComposerInput(context.renderer.keyInput, (event) => {
238
- syncInline()
239
- const key = keyName(event)
257
+ if (!pending()) return true
258
+ const editor = targetedEditor()
259
+ if (!editor) return true
260
+ if (editor.plainText === "" && removesOnly(event)) return true
240
261
  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() })
262
+ if (!current) return false
263
+ syncInline()
264
+ return Boolean(inline.visible(editor, current.text) && acceptShortcuts(opts.acceptKeys, context.keymap.shortcuts).has(keyName(event)) && canGenerate(current.sessionID) && isComposerEmpty(current.sessionID))
265
+ }, () => {
266
+ if (!pending() || !targetedEditor()) return
267
+ lifecycle.interrupt()
268
+ inline.clear()
269
+ })
243
270
 
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) => {
271
+ const acceptLayer = () => ghostBaseLayer(
272
+ opts.acceptKeys.map((key) => acceptCommand(key, () => {
273
+ const route = context.ui.router.current()
274
+ return route.type === "session" ? route.sessionID : undefined
275
+ }, () => suggestion()?.sessionID, act)),
276
+ )
277
+ const suggestLayer = () => ghostSuggestLayer(state.enabled, async (input) => {
250
278
  const command = parseSuggestCommand(input)
251
279
  if (command.type === "model") {
252
280
  cancelSuggestion()
281
+ lifecycle.resetWarning()
282
+ catalog.clear()
253
283
  await updateState((draft) => { draft.model = command.model })
254
284
  context.ui.toast.show({ message: `Suggestion model: ${state.model ?? opts.model ?? "OpenCode small default"}` })
255
285
  return
@@ -296,11 +326,12 @@ export default Plugin.define({
296
326
  return
297
327
  }
298
328
  context.ui.toast.show({ message: "Prompt suggestions: on" })
329
+ catalog.clear()
299
330
  const route = context.ui.router.current()
300
331
  if (route.type === "session") void lifecycle.run(route.sessionID)
301
332
  })
302
- context.keymap.layer(() => commandLayers()[0]!)
303
- context.keymap.layer(() => commandLayers()[1]!)
333
+ context.keymap.layer(acceptLayer)
334
+ context.keymap.layer(suggestLayer)
304
335
 
305
336
  const offComposer = context.ui.slot({
306
337
  append: "prompt.footer",