Open History to see the last commit
1#!/usr/bin/env bun
2/**
3 * Quick test: connect Node to the running Elixir HarnessService
4 * via Phoenix Channel WebSocket protocol.
5 *
6 * Usage: T3CODE_HARNESS_PORT=4321 bun run scripts/test-harness-connection.ts
7 */
8import WebSocket from "ws";
9
10const PORT = process.env.T3CODE_HARNESS_PORT ?? "4321";
11const SECRET = process.env.T3CODE_HARNESS_SECRET ?? "dev-harness-secret";
12const URL = `ws://localhost:${PORT}/socket/websocket?secret=${SECRET}&vsn=2.0.0`;
13
14let nextRef = 1;
15const pending = new Map<string, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();
16
17function send(
18 ws: WebSocket,
19 joinRef: string | null,
20 event: string,
21 payload: Record<string, unknown>,
22 topic = "harness:lobby",
23): Promise<unknown> {
24 const ref = String(nextRef++);
25 const msg = JSON.stringify([joinRef, ref, topic, event, payload]);
26
27 return new Promise((resolve, reject) => {
28 pending.set(ref, { resolve, reject });
29 ws.send(msg);
30 setTimeout(() => {
31 if (pending.has(ref)) {
32 pending.delete(ref);
33 reject(new Error(`Timeout waiting for reply to ${event}`));
34 }
35 }, 10_000);
36 });
37}
38
39async function main() {
40 console.log(`\n🔌 Connecting to ${URL}...\n`);
41
42 const ws = new WebSocket(URL);
43
44 ws.on("error", (err: Error) => {
45 console.error("❌ WebSocket error:", err.message);
46 process.exit(1);
47 });
48
49 ws.on("message", (raw: WebSocket.RawData) => {
50 const text = raw.toString();
51 console.log(` [RAW] ${text.slice(0, 200)}`);
52 let msg: unknown[];
53 try {
54 msg = JSON.parse(text);
55 } catch (err) {
56 console.error(" Failed to parse message:", err);
57 return;
58 }
59 const [, ref, , event, payload] = msg;
60
61 const refStr = typeof ref === "string" ? ref : String(ref);
62 if (event === "phx_reply" && ref && pending.has(refStr)) {
63 const { resolve, reject } = pending.get(refStr)!;
64 pending.delete(refStr);
65 const typedPayload = payload as { status: string; response: unknown };
66 if (typedPayload.status === "ok") {
67 resolve(typedPayload.response);
68 } else {
69 reject(new Error(`Channel error: ${JSON.stringify(typedPayload.response)}`));
70 }
71 return;
72 }
73
74 // Server pushes
75 if (event === "harness.event") {
76 const typedPayload = payload as { method?: string; threadId?: string };
77 console.log(` 📡 Event: ${typedPayload.method} (thread: ${typedPayload.threadId})`);
78 return;
79 }
80
81 if (event === "harness.session.changed") {
82 const typedPayload = payload as { threadId?: string; session?: { status?: string } };
83 console.log(
84 ` 🔄 Session changed: ${typedPayload.threadId} → ${typedPayload.session?.status}`,
85 );
86 return;
87 }
88 });
89
90 await new Promise<void>((resolve) => ws.on("open", resolve));
91 console.log("✅ WebSocket connected\n");
92
93 // 1. Join the channel
94 console.log("── Join harness:lobby ──");
95 const joinResult = await send(ws, "1", "phx_join", { secret: SECRET });
96 console.log("✅ Joined channel\n");
97
98 const JOIN_REF = "1"; // Must match join_ref used for phx_join
99
100 // 2. Get snapshot
101 console.log("── Get snapshot ──");
102 const snapshotResp = (await send(ws, JOIN_REF, "snapshot.get", {})) as {
103 snapshot: { sequence: number; sessions: Record<string, unknown> };
104 };
105 console.log(` Sequence: ${snapshotResp.snapshot.sequence}`);
106 console.log(` Sessions: ${Object.keys(snapshotResp.snapshot.sessions).length}\n`);
107
108 // 3. List sessions
109 console.log("── List sessions ──");
110 const sessions = (await send(ws, JOIN_REF, "session.listSessions", {})) as {
111 sessions: unknown[];
112 };
113 console.log(` Active: ${sessions.sessions.length}\n`);
114
115 // 4. Start an OpenCode session
116 const threadId = `node-test-opencode-${Date.now()}`;
117 console.log(`── Start OpenCode session (${threadId}) ──`);
118 try {
119 const startResult = await send(ws, JOIN_REF, "session.start", {
120 threadId,
121 provider: "opencode",
122 cwd: "/tmp",
123 });
124 console.log("✅ Session started:", JSON.stringify(startResult));
125 } catch (err) {
126 console.log(
127 "⚠️ Session start error (expected if opencode has issues):",
128 (err as Error).message,
129 );
130 }
131
132 // 5. Wait for events
133 console.log("\n⏳ Waiting 8s for provider events...\n");
134 await new Promise((r) => setTimeout(r, 8_000));
135
136 // 6. Check snapshot again
137 console.log("── Snapshot after session ──");
138 const snap2Resp = (await send(ws, JOIN_REF, "snapshot.get", {})) as {
139 snapshot: { sequence: number; sessions: Record<string, { status: string; provider: string }> };
140 };
141 const snapshot2 = snap2Resp.snapshot;
142 console.log(` Sequence: ${snapshot2.sequence}`);
143 for (const [id, s] of Object.entries(snapshot2.sessions)) {
144 console.log(` ${id}: ${s.status} (${s.provider})`);
145 }
146
147 // 7. Stop session
148 console.log(`\n── Stop session ──`);
149 try {
150 await send(ws, JOIN_REF, "session.stop", { threadId });
151 console.log("✅ Session stopped");
152 } catch (err) {
153 console.log("⚠️ Stop error:", (err as Error).message);
154 }
155
156 // 8. Heartbeat test
157 console.log("\n── Heartbeat ──");
158 const hbRef = String(nextRef++);
159 ws.send(JSON.stringify([null, hbRef, "phoenix", "heartbeat", {}]));
160 console.log("✅ Heartbeat sent\n");
161
162 // Done
163 console.log("🎉 All tests passed!\n");
164 ws.close();
165 process.exit(0);
166}
167
168main().catch((err) => {
169 console.error("💥 Fatal:", err);
170 process.exit(1);
171});