-
-
Save tak2-08/017e32bc7c5429a9229d258eef09849b to your computer and use it in GitHub Desktop.
Workaround proxy: makes CLI/TUI sessions visible in opencode web Home (auto-seeds the client-side project registry)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # opencode-web — launcher: ensures an opencode server is running, then starts | |
| # the injecting proxy. Sessions created from the shell become visible in the | |
| # web Home without manually adding each project. | |
| # | |
| # opencode-web [ui-port] (default 46000) | |
| # OPENCODE_BACKEND_PORT=46017 opencode-web | |
| set -euo pipefail | |
| UI_PORT="${1:-${WEB_FIX_PORT:-46000}}" | |
| BACKEND_PORT="${OPENCODE_BACKEND_PORT:-46017}" | |
| if ! curl -sf "http://127.0.0.1:${BACKEND_PORT}/api/health" >/dev/null 2>&1; then | |
| echo "[opencode-web] starting opencode server on 127.0.0.1:${BACKEND_PORT} ..." | |
| nohup opencode serve --port "${BACKEND_PORT}" --hostname 127.0.0.1 >/dev/null 2>&1 & | |
| for _ in $(seq 1 60); do | |
| curl -sf "http://127.0.0.1:${BACKEND_PORT}/api/health" >/dev/null 2>&1 && break | |
| sleep 0.5 | |
| done | |
| fi | |
| exec node "$HOME/.local/bin/opencode-web-proxy.mjs" "${UI_PORT}" "http://127.0.0.1:${BACKEND_PORT}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env node | |
| // opencode-web proxy — makes CLI/TUI sessions visible in the opencode web Home. | |
| // | |
| // Problem: the web Home renders its project list exclusively from a | |
| // browser-localStorage registry ("opencode.global.dat:server" -> projects.local). | |
| // Projects that were never opened through the web UI are absent, so sessions | |
| // created from the shell (TUI / `opencode run` / agents) never show up. | |
| // | |
| // Fix: this zero-dependency reverse proxy injects a same-origin <script> into | |
| // the served index.html. Before the app boots, the seeder reads /api/session | |
| // and /project and merges every directory that has sessions into the registry | |
| // (idempotent). | |
| // | |
| // CSP note: opencode web ships `script-src 'self' 'wasm-unsafe-eval' 'sha256-…'`. | |
| // Inline injected scripts are silently blocked, so the seeder MUST be served as | |
| // an external same-origin script (done here via /__webfix__/seed.js). | |
| // | |
| // Usage: node opencode-web-proxy.mjs <listen-port> <target-url> | |
| // e.g. node opencode-web-proxy.mjs 46000 http://127.0.0.1:46017 | |
| import http from "node:http"; | |
| import net from "node:net"; | |
| const argv = process.argv.slice(2); | |
| const listenPort = Number(argv[0] || process.env.WEB_FIX_PORT || 46000); | |
| const target = new URL(argv[1] || process.env.WEB_FIX_TARGET || "http://127.0.0.1:46017"); | |
| const SEED_PATH = "/__webfix__/seed.js"; | |
| const SEED_JS = `(function(){ | |
| try{ | |
| function xhr(u){var x=new XMLHttpRequest();x.open("GET",u,false);x.send(null);return x.status===200?x.responseText:null} | |
| var raw=xhr("/api/session?limit=5000&order=desc");if(!raw)return; | |
| var d=JSON.parse(raw);if(Array.isArray(d))d={data:d}; | |
| var dirs={}; | |
| (d.data||[]).forEach(function(s){var loc=s.location||s;var dir=loc.directory;if(dir){var t=(s.time&&s.time.updated)||0;dirs[dir]=Math.max(dirs[dir]||0,t)}}); | |
| var praw=xhr("/project"); | |
| if(praw){JSON.parse(praw).forEach(function(p){if(p.worktree&&p.worktree!=="/"&&!dirs[p.worktree])dirs[p.worktree]=(p.time&&p.time.updated)||0})} | |
| var entries=Object.keys(dirs).map(function(k){return{worktree:k,updated:dirs[k]}}).sort(function(a,b){return b.updated-a.updated}); | |
| if(!entries.length)return; | |
| var KEY="opencode.global.dat:server",st=null; | |
| try{st=JSON.parse(localStorage.getItem(KEY)||"null")}catch(e){st=null} | |
| if(!st||typeof st!=="object")st={list:[],projects:{},lastProject:{},recentlyClosed:{}}; | |
| if(!st.projects||typeof st.projects!=="object")st.projects={}; | |
| if(!st.lastProject||typeof st.lastProject!=="object")st.lastProject={}; | |
| if(!Array.isArray(st.list))st.list=[]; | |
| var cur=Array.isArray(st.projects.local)?st.projects.local:[]; | |
| var have={};cur.forEach(function(p){if(p&&typeof p.worktree==="string")have[p.worktree]=p}); | |
| var added=0; | |
| entries.forEach(function(e2){if(!have[e2.worktree]){cur.push({worktree:e2.worktree,expanded:true});added++}}); | |
| if(added||!cur.length){st.projects.local=cur} | |
| if(typeof st.lastProject.local!=="string"&&cur.length)st.lastProject.local=cur[0].worktree; | |
| if(added||typeof st.lastProject.local!=="string")localStorage.setItem(KEY,JSON.stringify(st)); | |
| }catch(e){console.warn("[web-fix] seed failed:",e)} | |
| })();`; | |
| function inject(buf) { | |
| let html = buf.toString("utf8"); | |
| if (html.includes(SEED_PATH)) return Buffer.from(html, "utf8"); | |
| html = html.replace(/<head[^>]*>/i, (m) => m + `<script src="${SEED_PATH}"></script>`); | |
| return Buffer.from(html, "utf8"); | |
| } | |
| const server = http.createServer((req, res) => { | |
| if (req.url === SEED_PATH || req.url.startsWith(`${SEED_PATH}?`)) { | |
| const body = Buffer.from(SEED_JS, "utf8"); | |
| res.writeHead(200, { | |
| "content-type": "application/javascript; charset=utf-8", | |
| "content-length": String(body.length), | |
| "cache-control": "no-store", | |
| }); | |
| res.end(body); | |
| return; | |
| } | |
| const headers = { ...req.headers }; | |
| delete headers["accept-encoding"]; // force identity so HTML can be injected | |
| headers.host = target.host; | |
| const preq = http.request( | |
| { | |
| protocol: target.protocol, | |
| hostname: target.hostname, | |
| port: target.port || 80, | |
| method: req.method, | |
| path: req.url, | |
| headers, | |
| }, | |
| (pres) => { | |
| const ct = pres.headers["content-type"] || ""; | |
| if (req.method === "GET" && ct.includes("text/html")) { | |
| const chunks = []; | |
| pres.on("data", (c) => chunks.push(c)); | |
| pres.on("end", () => { | |
| const body = inject(Buffer.concat(chunks)); | |
| const h = { ...pres.headers }; | |
| delete h["content-encoding"]; | |
| delete h["transfer-encoding"]; | |
| h["content-length"] = String(body.length); | |
| res.writeHead(pres.statusCode || 500, h); | |
| res.end(body); | |
| }); | |
| pres.on("error", () => res.destroy()); | |
| } else { | |
| res.writeHead(pres.statusCode || 500, pres.headers); | |
| pres.pipe(res); // streams SSE etc. untouched | |
| } | |
| } | |
| ); | |
| preq.on("error", (err) => { | |
| if (!res.headersSent) res.writeHead(502, { "content-type": "text/plain" }); | |
| res.end("opencode-web proxy error: " + err.message); | |
| }); | |
| req.pipe(preq); | |
| }); | |
| // WebSocket (pty etc.) tunneling | |
| server.on("upgrade", (req, socket, head) => { | |
| const t = net.connect(target.port || 80, target.hostname, () => { | |
| let raw = `${req.method} ${req.url} HTTP/1.1\r\n`; | |
| for (let i = 0; i < req.rawHeaders.length; i += 2) { | |
| if (/^host$/i.test(req.rawHeaders[i])) raw += `Host: ${target.host}\r\n`; | |
| else raw += `${req.rawHeaders[i]}: ${req.rawHeaders[i + 1]}\r\n`; | |
| } | |
| raw += "\r\n"; | |
| t.write(raw); | |
| if (head?.length) t.write(head); | |
| t.pipe(socket); | |
| socket.pipe(t); | |
| }); | |
| socket.on("error", () => t.destroy()); | |
| t.on("error", () => socket.destroy()); | |
| }); | |
| server.listen(listenPort, "0.0.0.0", () => { | |
| console.log(`[opencode-web-fix] http://0.0.0.0:${listenPort} -> ${target.origin}`); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment