Skip to content

Commit a3eaeea

Browse files
opencode: TUI-inject mode — make interactive sessions injectable
Adds EDC_OPENCODE_TUI=1: instead of spawning a headless server + session, the adapter attaches to a shared opencode server (EDC_OPENCODE_URL) and delivers each /inject event by typing it into the attached TUI via POST /tui/append-prompt + /tui/submit-prompt — so the human SEES the injected turn (works around anomalyco/opencode#8564). In TUI mode edc skips session creation + self-registration (the plugin owns registration). Verified e2e: /inject -> visible turn -> reply.
1 parent 0491a3f commit a3eaeea

2 files changed

Lines changed: 74 additions & 33 deletions

File tree

‎README.md‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -149,10 +149,14 @@ Mechanism (from the [OpenCode server](https://opencode.ai/docs/server/) + [SDK](
149149
reliable process-exit hook ([sst/opencode#14863](https://github.com/sst/opencode/issues/14863)),
150150
so teardown falls to the tmux launcher + `presence ttyd reap` / TTL prune.
151151

152-
**Known gap.** An externally-injected turn is processed by the model but may not render in the raw
153-
TUI ([sst/opencode#8564](https://github.com/sst/opencode/issues/8564)). Route visible injects
154-
through `POST /tui/appendPrompt` + `/tui/submitPrompt` (enters as if typed), or watch via the
155-
presence cockpit / SSE rather than the raw TUI.
152+
**Known gap → solved for interactive sessions.** An externally-injected turn is processed by the
153+
model but may not render in the raw TUI ([sst/opencode#8564](https://github.com/sst/opencode/issues/8564)).
154+
`edc opencode serve` in **TUI mode** (`EDC_OPENCODE_TUI=1` + `EDC_OPENCODE_URL=<shared server>`)
155+
works around it: instead of `prompt_async`, it types each `/inject` event into the attached session
156+
via `POST /tui/append-prompt` + `/tui/submit-prompt`, so the human **sees** the turn land.
157+
`presence`'s `mesh opencode [dir]` wires this automatically — a decoupled `opencode serve` +
158+
`opencode attach` + a TUI-mode sidecar on a fixed inject port — making an interactive OpenCode
159+
session attachable **and** injectable via `edc /inject`.
156160

157161
**Trust boundary.** Like Codex, OpenCode has no native `source=system` marker — an injected event
158162
arrives as ordinary user input. `edc` reconstructs the boundary in text, but treat every injected

‎opencode.go‎

Lines changed: 66 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -34,22 +34,27 @@ type opencodeClient struct {
3434
base string // http://127.0.0.1:PORT
3535
hc *http.Client
3636
auth string // "Basic …" (OPENCODE_SERVER_PASSWORD) or ""
37-
session string // ses_…
37+
session string // ses_… (daemon mode only; TUI mode uses the attached TUI's active session)
3838
model string // optional explicit model (EDC_OPENCODE_MODEL)
3939
agent string // optional explicit agent (EDC_OPENCODE_AGENT)
40+
tui bool // TUI mode: inject into the attached interactive TUI via /tui/* (visible)
4041
serve *exec.Cmd // the spawned `opencode serve`, or nil if we connect to an existing one
4142
logger *log.Logger
4243
}
4344

4445
// newOpenCodeClient connects to EDC_OPENCODE_URL if set, else spawns `opencode serve` on a free
4546
// port (Dir=cwd so created sessions belong to the target repo) and waits until it is healthy.
46-
func newOpenCodeClient(cwd, model, agent, password string, logger *log.Logger) (*opencodeClient, error) {
47-
c := &opencodeClient{hc: &http.Client{Timeout: 30 * time.Second}, model: model, agent: agent, logger: logger}
47+
// In TUI mode it never spawns — it attaches to the already-running server (EDC_OPENCODE_URL
48+
// required) that an interactive `opencode attach` shares, and injects into that live TUI.
49+
func newOpenCodeClient(cwd, model, agent, password string, tui bool, logger *log.Logger) (*opencodeClient, error) {
50+
c := &opencodeClient{hc: &http.Client{Timeout: 30 * time.Second}, model: model, agent: agent, tui: tui, logger: logger}
4851
if password != "" {
4952
c.auth = "Basic " + base64.StdEncoding.EncodeToString([]byte("opencode:"+password))
5053
}
5154
if url := os.Getenv("EDC_OPENCODE_URL"); url != "" {
5255
c.base = strings.TrimRight(url, "/")
56+
} else if tui {
57+
return nil, fmt.Errorf("TUI mode requires EDC_OPENCODE_URL (the shared opencode server)")
5358
} else {
5459
port, err := freeTCPPort()
5560
if err != nil {
@@ -154,9 +159,14 @@ func (c *opencodeClient) messageBody(text string) map[string]any {
154159
return body
155160
}
156161

157-
// injectTurn posts the event as a fire-and-forget turn (prompt_async) so /inject returns
158-
// immediately instead of blocking for the whole model turn.
162+
// injectTurn delivers the event as a turn. In TUI mode it drives the attached interactive TUI
163+
// (/tui/append-prompt + /tui/submit-prompt) so the human *sees* the injected turn land in the
164+
// session they're watching — the workaround for OpenCode not rendering prompt_async turns
165+
// (sst/opencode#8564). In daemon mode it posts prompt_async to its own headless session.
159166
func (c *opencodeClient) injectTurn(ctx context.Context, req injectRequest) error {
167+
if c.tui {
168+
return c.tuiInject(ctx, wrapEvent(req))
169+
}
160170
if c.session == "" {
161171
return fmt.Errorf("no active session")
162172
}
@@ -170,6 +180,22 @@ func (c *opencodeClient) injectTurn(ctx context.Context, req injectRequest) erro
170180
return nil
171181
}
172182

183+
// tuiInject types the event into the attached TUI's prompt box and submits it, so it renders in
184+
// the human's view and runs against whatever session/agent/model the TUI currently has active.
185+
func (c *opencodeClient) tuiInject(ctx context.Context, text string) error {
186+
if out, code, err := c.do(ctx, http.MethodPost, "/tui/append-prompt", map[string]any{"text": text}); err != nil {
187+
return err
188+
} else if code >= 300 {
189+
return fmt.Errorf("append-prompt HTTP %d: %s", code, truncate(string(out), 200))
190+
}
191+
if out, code, err := c.do(ctx, http.MethodPost, "/tui/submit-prompt", map[string]any{}); err != nil {
192+
return err
193+
} else if code >= 300 {
194+
return fmt.Errorf("submit-prompt HTTP %d: %s", code, truncate(string(out), 200))
195+
}
196+
return nil
197+
}
198+
173199
func (c *opencodeClient) kill() {
174200
if c.serve != nil && c.serve.Process != nil {
175201
_ = c.serve.Process.Kill()
@@ -202,24 +228,31 @@ func runOpenCode(args []string) int {
202228
model := os.Getenv("EDC_OPENCODE_MODEL")
203229
agent := os.Getenv("EDC_OPENCODE_AGENT")
204230
password := os.Getenv("OPENCODE_SERVER_PASSWORD")
231+
// TUI mode: attach to a shared opencode server (the interactive `opencode attach` session) and
232+
// inject into it visibly, instead of spawning a headless server + session.
233+
tui := os.Getenv("EDC_OPENCODE_TUI") != ""
205234

206235
ctx, stop := signalContext()
207236
defer stop()
208237

209-
client, err := newOpenCodeClient(cwd, model, agent, password, logger)
238+
client, err := newOpenCodeClient(cwd, model, agent, password, tui, logger)
210239
if err != nil {
211240
logger.Printf("opencode: %v", err)
212241
return 1
213242
}
214-
sctx, cancel := context.WithTimeout(ctx, 30*time.Second)
215-
err = client.startSession(sctx)
216-
cancel()
217-
if err != nil {
218-
logger.Printf("opencode: bootstrap failed: %v", err)
219-
client.kill()
220-
return 1
243+
if tui {
244+
logger.Printf("opencode: TUI mode — injecting into the attached session at %s", client.base)
245+
} else {
246+
sctx, cancel := context.WithTimeout(ctx, 30*time.Second)
247+
err = client.startSession(sctx)
248+
cancel()
249+
if err != nil {
250+
logger.Printf("opencode: bootstrap failed: %v", err)
251+
client.kill()
252+
return 1
253+
}
254+
logger.Printf("opencode: server %s session %s ready", client.base, client.session)
221255
}
222-
logger.Printf("opencode: server %s session %s ready", client.base, client.session)
223256

224257
ln, err := bindInject(cfg, logger)
225258
if err != nil {
@@ -228,22 +261,26 @@ func runOpenCode(args []string) int {
228261
return 1
229262
}
230263

231-
// Own our presence lifecycle: register now, heartbeat while serving, deregister on exit.
232-
pres := &presenceReg{sessionID: client.session, port: ln.Addr().(*net.TCPAddr).Port, cwd: cwd, agent: "opencode", logger: logger}
233-
pres.register()
234-
defer pres.deregister()
235-
go func() {
236-
t := time.NewTicker(30 * time.Second)
237-
defer t.Stop()
238-
for {
239-
select {
240-
case <-ctx.Done():
241-
return
242-
case <-t.C:
243-
pres.heartbeat()
264+
// Daemon mode owns its presence lifecycle (register/heartbeat/deregister). TUI mode leaves that
265+
// to the OpenCode plugin — it knows the real interactive session id and reads the inject port
266+
// from EDC_INJECT_PORT (which the launcher fixes for both this process and the TUI).
267+
if !tui {
268+
pres := &presenceReg{sessionID: client.session, port: ln.Addr().(*net.TCPAddr).Port, cwd: cwd, agent: "opencode", logger: logger}
269+
pres.register()
270+
defer pres.deregister()
271+
go func() {
272+
t := time.NewTicker(30 * time.Second)
273+
defer t.Stop()
274+
for {
275+
select {
276+
case <-ctx.Done():
277+
return
278+
case <-t.C:
279+
pres.heartbeat()
280+
}
244281
}
245-
}
246-
}()
282+
}()
283+
}
247284

248285
mux := http.NewServeMux()
249286
mux.HandleFunc("/inject", func(w http.ResponseWriter, r *http.Request) {

0 commit comments

Comments
 (0)