Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
claude-web.tsx14.6 KB · 394 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/**
 * Block CW — Claude on the web.
 *
 *   GET  /:owner/:repo/claude                   — session list + new-session form
 *   POST /:owner/:repo/claude                   — create session, redirect to detail
 *   GET  /:owner/:repo/claude/:sessionId        — chat UI (messages + composer)
 *   GET  /:owner/:repo/claude/:sessionId/stream — SSE stream of a single turn
 *   POST /:owner/:repo/claude/:sessionId/delete — delete session
 *
 * v1 admin-only. The page renders server-side with a small inline
 * EventSource client that POSTs nothing — the SSE GET is parameterised
 * by `?prompt=...` so iPad keyboards (no JS fetch issues) just need to
 * follow a link the form submits to. The endpoint persists the user
 * message before opening the stream, so a flaky network mid-stream
 * still leaves the question in the transcript.
 */

import { Hono } from "hono";
import { and, eq } from "drizzle-orm";
import { db } from "../db";
import { repositories, users } from "../db/schema";
import { Layout } from "../views/layout";
import { softAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { isSiteAdmin } from "../lib/admin";
import {
  appendMessage,
  createSession,
  deleteSession,
  ensureWorkdir,
  getSession,
  listMessages,
  listSessionsForRepo,
  runTurn,
  touchSession,
} from "../lib/claude-web-session";

const claudeWeb = new Hono<AuthEnv>();
claudeWeb.use("*", softAuth);

async function gate(
  c: any
): Promise<{ userId: string; repoId: string; ownerName: string; repoName: string } | Response> {
  const user = c.get("user");
  if (!user) {
    const target = encodeURIComponent(c.req.url);
    return c.redirect(`/login?next=${target}`);
  }
  if (!(await isSiteAdmin(user.id))) {
    return c.html(
      <Layout title="Forbidden" user={user}>
        <main style="max-width:640px;margin:40px auto;padding:0 20px">
          <h1>403 — site admin required</h1>
          <p>Claude on the web is admin-only in v1.</p>
        </main>
      </Layout>,
      403
    );
  }
  const ownerName = c.req.param("owner");
  const repoName = c.req.param("repo");
  const [row] = await db
    .select({ id: repositories.id })
    .from(repositories)
    .innerJoin(users, eq(repositories.ownerId, users.id))
    .where(and(eq(users.username, ownerName), eq(repositories.name, repoName)))
    .limit(1);
  if (!row) return c.notFound();
  return { userId: user.id, repoId: row.id, ownerName, repoName };
}

const wrap =
  "max-width:980px;margin:24px auto;padding:0 16px;color:#e5e7eb;font-family:system-ui,sans-serif";
const card =
  "background:#0e1117;border:1px solid #1f2937;border-radius:10px;padding:16px 18px;margin-bottom:14px";
const inputStyle =
  "width:100%;background:#0b0e13;border:1px solid #1f2937;color:#e5e7eb;padding:10px 12px;border-radius:6px;font-size:16px";
const btn =
  "background:#1f6feb;border:0;color:#fff;padding:10px 16px;border-radius:6px;cursor:pointer;font-size:15px";

// ─── GET /:owner/:repo/claude ───────────────────────────────────────────────

claudeWeb.get("/:owner/:repo/claude", async (c) => {
  const g = await gate(c);
  if (g instanceof Response) return g;
  const user = c.get("user")!;
  const sessions = await listSessionsForRepo(g.repoId);

  return c.html(
    <Layout title={`Claude — ${g.ownerName}/${g.repoName}`} user={user}>
      <main style={wrap}>
        <p style="margin:0 0 6px">
          <a href={`/${g.ownerName}/${g.repoName}`} style="color:#9ca3af;text-decoration:none">
            ← {g.ownerName}/{g.repoName}
          </a>
        </p>
        <h1 style="margin:0 0 6px;font-size:22px">Claude on this repo</h1>
        <p style="margin:0 0 18px;color:#9ca3af;font-size:14px">
          iPad-friendly Claude Code sessions on a per-session clone of the repo.
        </p>

        <form method="post" action={`/${g.ownerName}/${g.repoName}/claude`} style={card}>
          <label style="display:block;font-size:13px;color:#9ca3af;margin-bottom:6px">
            New session title
          </label>
          <div style="display:flex;gap:8px">
            <input name="title" placeholder="What you want to work on" style={inputStyle} />
            <input name="branch" placeholder="main" style={inputStyle + ";max-width:160px"} />
            <button type="submit" style={btn}>Start</button>
          </div>
        </form>

        <div style={card}>
          <h2 style="margin:0 0 10px;font-size:15px;color:#cbd5e1">Sessions</h2>
          {sessions.length === 0 ? (
            <p style="color:#6b7280;margin:0;font-size:14px">None yet.</p>
          ) : (
            <ul style="list-style:none;padding:0;margin:0">
              {sessions.map((s) => (
                <li style="padding:10px 0;border-top:1px solid #1f2937;display:flex;justify-content:space-between;align-items:center">
                  <a
                    href={`/${g.ownerName}/${g.repoName}/claude/${s.id}`}
                    style="color:#7aa2f7;text-decoration:none;font-weight:600"
                  >
                    {s.title}
                  </a>
                  <span style="color:#6b7280;font-size:12px;font-family:ui-monospace,monospace">
                    {s.branch} · {s.status}
                  </span>
                </li>
              ))}
            </ul>
          )}
        </div>
      </main>
    </Layout>
  );
});

// ─── POST /:owner/:repo/claude ──────────────────────────────────────────────

claudeWeb.post("/:owner/:repo/claude", async (c) => {
  const g = await gate(c);
  if (g instanceof Response) return g;
  const form = await c.req.parseBody();
  const title = String(form.title || "").trim() || "New session";
  const branch = String(form.branch || "").trim() || "main";
  const session = await createSession({
    repositoryId: g.repoId,
    ownerUserId: g.userId,
    title,
    branch,
  });
  return c.redirect(`/${g.ownerName}/${g.repoName}/claude/${session.id}`);
});

// ─── GET /:owner/:repo/claude/:sessionId ────────────────────────────────────

claudeWeb.get("/:owner/:repo/claude/:sessionId", async (c) => {
  const g = await gate(c);
  if (g instanceof Response) return g;
  const user = c.get("user")!;
  const sessionId = c.req.param("sessionId");
  const session = await getSession(sessionId, g.userId);
  if (!session || session.repositoryId !== g.repoId) return c.notFound();

  const messages = await listMessages(sessionId);

  // Inline SSE client. ~30 lines of vanilla JS — keeps the bundle empty.
  const clientJs = `
    (function() {
      var f = document.getElementById('cw-composer');
      if (!f) return;
      f.addEventListener('submit', function(ev) {
        ev.preventDefault();
        var input = document.getElementById('cw-prompt');
        var prompt = (input.value || '').trim();
        if (!prompt) return;
        input.value = '';
        var list = document.getElementById('cw-messages');
        var u = document.createElement('div');
        u.className = 'cw-msg cw-msg-user';
        u.textContent = prompt;
        list.appendChild(u);
        var a = document.createElement('pre');
        a.className = 'cw-msg cw-msg-assistant';
        a.textContent = '';
        list.appendChild(a);
        var url = ${JSON.stringify(`/${g.ownerName}/${g.repoName}/claude/${sessionId}/stream`)} + '?prompt=' + encodeURIComponent(prompt);
        var es = new EventSource(url);
        es.addEventListener('chunk', function(e) {
          a.textContent += e.data;
          window.scrollTo(0, document.body.scrollHeight);
        });
        es.addEventListener('done', function() {
          es.close();
        });
        es.addEventListener('error', function() {
          a.textContent += '\\n[stream error — reload to retry]';
          es.close();
        });
      });
    })();
  `;

  const styleCss = `
    .cw-msg { padding:10px 12px;border-radius:8px;margin:8px 0;white-space:pre-wrap;word-wrap:break-word;font-family:ui-monospace,monospace;font-size:14px;line-height:1.5; }
    .cw-msg-user { background:#172033;color:#e5e7eb;border:1px solid #1f6feb55; }
    .cw-msg-assistant { background:#0e1117;color:#cbd5e1;border:1px solid #1f2937; }
    .cw-msg-system { background:#2a1f10;color:#e1c47f;border:1px solid #5a4a1f;font-size:13px; }
  `;

  return c.html(
    <Layout title={`${session.title} — Claude`} user={user}>
      <main style={wrap}>
        <p style="margin:0 0 6px">
          <a href={`/${g.ownerName}/${g.repoName}/claude`} style="color:#9ca3af;text-decoration:none">
            ← Claude sessions
          </a>
        </p>
        <div style="display:flex;justify-content:space-between;align-items:baseline;margin-bottom:6px">
          <h1 style="margin:0;font-size:20px">{session.title}</h1>
          <span style="color:#6b7280;font-size:12px;font-family:ui-monospace,monospace">
            {session.branch} · {session.status}
          </span>
        </div>
        <style dangerouslySetInnerHTML={{ __html: styleCss }} />

        <div id="cw-messages" style="margin-bottom:14px">
          {messages.length === 0 ? (
            <p style="color:#6b7280;font-size:14px">No turns yet. Ask Claude something below.</p>
          ) : (
            messages.map((m) => (
              <div
                class={"cw-msg cw-msg-" + m.role}
                data-role={m.role}
              >
                {m.body}
              </div>
            ))
          )}
        </div>

        <form id="cw-composer" style={card}>
          <textarea
            id="cw-prompt"
            name="prompt"
            placeholder="Ask Claude..."
            rows={3}
            style={inputStyle}
          />
          <div style="margin-top:8px;display:flex;justify-content:space-between;align-items:center">
            <span style="color:#6b7280;font-size:12px">
              Streams over SSE. Long turns cap at 5 minutes.
            </span>
            <button type="submit" style={btn}>Send</button>
          </div>
        </form>

        <form
          method="post"
          action={`/${g.ownerName}/${g.repoName}/claude/${session.id}/delete`}
          style="text-align:right;margin-top:12px"
          onsubmit="return confirm('Delete this session and its transcript?')"
        >
          <button type="submit" style="background:#a02020;border:0;color:#fff;padding:6px 12px;border-radius:6px;cursor:pointer;font-size:13px">
            Delete session
          </button>
        </form>

        <script dangerouslySetInnerHTML={{ __html: clientJs }} />
      </main>
    </Layout>
  );
});

// ─── GET /:owner/:repo/claude/:sessionId/stream ─────────────────────────────

claudeWeb.get("/:owner/:repo/claude/:sessionId/stream", async (c) => {
  const g = await gate(c);
  if (g instanceof Response) return g;
  const sessionId = c.req.param("sessionId");
  const session = await getSession(sessionId, g.userId);
  if (!session || session.repositoryId !== g.repoId) return c.notFound();
  const prompt = (c.req.query("prompt") || "").slice(0, 16_000);
  if (!prompt.trim()) {
    return c.text("missing prompt", 400);
  }

  // Persist the user turn *before* we start the stream so a network blip
  // doesn't lose the question.
  await appendMessage({ sessionId, role: "user", body: prompt });
  await touchSession({ sessionId, status: "running" });

  // Lazily clone the workdir on first turn.
  const workdir = await ensureWorkdir(session, g.ownerName, g.repoName);
  if (!workdir.ok) {
    await appendMessage({
      sessionId,
      role: "system",
      body: `workdir error: ${workdir.error}`,
    });
    await touchSession({ sessionId, status: "failed" });
    return c.text(`workdir: ${workdir.error}`, 500);
  }

  const stream = new ReadableStream<Uint8Array>({
    async start(controller) {
      const enc = new TextEncoder();
      let assistantBody = "";
      let finalExit = 0;
      let finalDuration = 0;
      let finalClaudeId: string | undefined;

      function send(event: string, data: string) {
        controller.enqueue(enc.encode(`event: ${event}\n`));
        // Split data on newlines so we never break the SSE wire format.
        for (const line of data.split("\n")) {
          controller.enqueue(enc.encode(`data: ${line}\n`));
        }
        controller.enqueue(enc.encode(`\n`));
      }

      try {
        for await (const ev of runTurn({
          session,
          ownerName: g.ownerName,
          repoName: g.repoName,
          prompt,
        })) {
          if (ev.chunk) {
            assistantBody += ev.chunk;
            send("chunk", ev.chunk);
          }
          if (ev.done) {
            finalExit = ev.done.exitCode;
            finalDuration = ev.done.durationMs;
            finalClaudeId = ev.done.claudeSessionId;
            if (ev.done.stderr && ev.done.exitCode !== 0) {
              assistantBody += `\n[stderr] ${ev.done.stderr}`;
              send("chunk", `\n[stderr] ${ev.done.stderr}`);
            }
            send("done", String(ev.done.exitCode));
          }
        }
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        assistantBody += `\n[exception] ${msg}`;
        send("error", msg);
      } finally {
        try {
          await appendMessage({
            sessionId,
            role: "assistant",
            body: assistantBody,
            exitCode: finalExit,
            durationMs: finalDuration,
          });
          await touchSession({
            sessionId,
            claudeSessionId: finalClaudeId,
            status: finalExit === 0 ? "ready" : "failed",
          });
        } catch {
          /* persistence errors don't break the response */
        }
        controller.close();
      }
    },
  });

  return new Response(stream, {
    headers: {
      "Content-Type": "text/event-stream; charset=utf-8",
      "Cache-Control": "no-cache, no-transform",
      "Connection": "keep-alive",
      "X-Accel-Buffering": "no",
    },
  });
});

// ─── POST /:owner/:repo/claude/:sessionId/delete ────────────────────────────

claudeWeb.post("/:owner/:repo/claude/:sessionId/delete", async (c) => {
  const g = await gate(c);
  if (g instanceof Response) return g;
  const sessionId = c.req.param("sessionId");
  const session = await getSession(sessionId, g.userId);
  if (!session || session.repositoryId !== g.repoId) return c.notFound();
  await deleteSession(sessionId);
  return c.redirect(`/${g.ownerName}/${g.repoName}/claude`);
});

export default claudeWeb;