Skip to content

Commit de5b146

Browse files
fix(server): opts.port testing and auto-add --port flag to terminal.cmd (#63)
Co-authored-by: Nick van Dyke <nickjvandyke15@gmail.com>
1 parent b51972a commit de5b146

File tree

2 files changed

+18
-12
lines changed

2 files changed

+18
-12
lines changed

lua/opencode/cli/server.lua

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -126,28 +126,29 @@ local function poll_for_port(fn, callback)
126126
100,
127127
vim.schedule_wrap(function()
128128
local ok, find_port_result = pcall(fn)
129-
if ok then
130-
timer:stop()
131-
timer:close()
132-
callback(true, find_port_result)
133-
elseif retries >= 20 then
129+
if ok or retries >= 20 then
134130
timer:stop()
135131
timer:close()
136-
callback(false, find_port_result)
132+
callback(ok, find_port_result)
137133
else
138134
retries = retries + 1
139135
end
140136
end)
141137
)
142138
end
143139

144-
---Test if an opencode process is responding on the given port.
145-
---Uses `curl` for better availability than `lsof`.
140+
---Test if a process is responding on `port`.
146141
---@param port number
147-
---@return number
142+
---@return number port
148143
local function test_port(port)
149-
vim.cmd("silent !curl -s http://localhost:" .. port)
150-
return vim.v.shell_error == 0 and port or error("Couldn't find an `opencode` process on port: " .. port, 0)
144+
-- TODO: `curl` "/app" endpoint to verify it's actually an opencode server.
145+
local chan = vim.fn.sockconnect("tcp", ("localhost:%d"):format(port), { rpc = false, timeout = 200 })
146+
if chan == 0 then
147+
error(("Couldn't find a process listening on port: %d"):format(port), 0)
148+
else
149+
pcall(vim.fn.chanclose, chan)
150+
return port
151+
end
151152
end
152153

153154
---Attempt to get the `opencode` server's port. Tries, in order:

lua/opencode/config.lua

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ vim.g.opencode_opts = vim.g.opencode_opts
1515
---
1616
---The port `opencode` is running on.
1717
---If `nil`, searches for an `opencode` process inside Neovim's CWD (requires `lsof` to be installed on your system).
18-
---Recommend launching `opencode` with `--port <port>` when setting this.
18+
---Launch `opencode` with `--port <port>` when this is set (the embedded terminal will automatically do so).
1919
---@field port? number
2020
---
2121
---Reload buffers edited by `opencode` in real-time.
@@ -164,4 +164,9 @@ for _, field in ipairs({ "prompts", "contexts" }) do
164164
end
165165
end
166166

167+
-- Auto-add `--port <port>` to embedded terminal command if set and not already present.
168+
if M.opts.port and not M.opts.terminal.cmd:find("--port") then
169+
M.opts.terminal.cmd = M.opts.terminal.cmd .. " --port " .. tostring(M.opts.port)
170+
end
171+
167172
return M

0 commit comments

Comments
 (0)