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
ask.tsx12.2 KB · 425 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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/**
 * AI chat assistant — global + per-repo.
 *
 *   GET  /ask                         — global assistant (platform Q&A)
 *   GET  /ask/:chatId                 — resume a saved chat
 *   POST /ask                         — send a message (global)
 *   GET  /:owner/:repo/ask            — repo-grounded chat
 *   POST /:owner/:repo/ask            — send a repo-grounded message
 *   POST /:owner/:repo/explain        — "Explain this file" helper
 *
 * Chats are persisted to `ai_chats` so users can return to them.
 * Form-based — works even with JS disabled.
 */

import { Hono } from "hono";
import { eq, and, desc } from "drizzle-orm";
import { db } from "../db";
import { aiChats, repositories, users } from "../db/schema";
import { Layout } from "../views/layout";
import { requireAuth, softAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { chat, explainFile } from "../lib/ai-chat";
import type { ChatMessage } from "../lib/ai-chat";
import { getUnreadCount } from "../lib/unread";
import { isAiAvailable } from "../lib/ai-client";

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

function loadMessages(raw: string | null | undefined): ChatMessage[] {
  if (!raw) return [];
  try {
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed)) {
      return parsed.filter(
        (m): m is ChatMessage =>
          m && typeof m === "object" && typeof m.content === "string" &&
          (m.role === "user" || m.role === "assistant")
      );
    }
  } catch {
    /* ignore */
  }
  return [];
}

function renderChatView(
  c: any,
  {
    messages,
    postUrl,
    title,
    subtitle,
    placeholder,
    recentChats,
    user,
    unreadCount,
  }: {
    messages: ChatMessage[];
    postUrl: string;
    title: string;
    subtitle?: string;
    placeholder: string;
    recentChats?: Array<{ id: string; title: string | null; updatedAt: Date }>;
    user: any;
    unreadCount: number;
  }
) {
  return c.html(
    <Layout title={title} user={user} notificationCount={unreadCount}>
      <div class="ask-container">
        <div style="display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 8px">
          <h2>{title}</h2>
          {!isAiAvailable() && (
            <span class="badge" style="color: var(--yellow); border-color: var(--yellow)">
              AI unavailable — set ANTHROPIC_API_KEY
            </span>
          )}
        </div>
        {subtitle && (
          <p style="color: var(--text-muted); margin-bottom: 16px">{subtitle}</p>
        )}

        <div class="chat-log">
          {messages.length === 0 ? (
            <div class="panel-empty">
              Ask anything. Reference files with @path/to/file.ext.
            </div>
          ) : (
            messages.map((m) => (
              <div class={`chat-message ${m.role}`}>
                <div class="role">{m.role === "user" ? "You" : "GlueCron AI"}</div>
                {m.content}
              </div>
            ))
          )}
        </div>

        <form method="POST" action={postUrl} class="chat-form">
          <textarea
            name="message"
            placeholder={placeholder}
            required
            autofocus
          ></textarea>
          <div
            style="display: flex; justify-content: space-between; align-items: center; margin-top: 8px"
          >
            <div class="chat-hint">
              {"\u21B5"} Enter + Ctrl/Cmd to send. Mention files with
              <span class="chat-cited" style="margin-left: 4px">@src/file.ts</span>
            </div>
            <button type="submit" class="btn btn-primary">
              Send
            </button>
          </div>
        </form>

        {recentChats && recentChats.length > 0 && (
          <div style="margin-top: 32px">
            <h3 style="font-size: 14px; text-transform: uppercase; letter-spacing: 0.5px; color: var(--text-muted); margin-bottom: 12px">
              Recent chats
            </h3>
            <div class="panel">
              {recentChats.map((ch) => (
                <div class="panel-item">
                  <div class="dot blue"></div>
                  <div style="flex: 1">
                    <a href={`/ask/${ch.id}`}>
                      {ch.title || "(untitled)"}
                    </a>
                    <div class="meta">
                      {new Date(ch.updatedAt).toLocaleString()}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </Layout>
  );
}

// Backwards-compat alias retained so external imports keep working.
const ChatView = renderChatView;

async function resumeChat(
  userId: string,
  chatId: string
): Promise<{
  messages: ChatMessage[];
  repoOwner: string | null;
  repoName: string | null;
} | null> {
  try {
    const [row] = await db
      .select({
        messages: aiChats.messages,
        userId: aiChats.userId,
        repositoryId: aiChats.repositoryId,
      })
      .from(aiChats)
      .where(eq(aiChats.id, chatId))
      .limit(1);
    if (!row || row.userId !== userId) return null;

    let repoOwner: string | null = null;
    let repoName: string | null = null;
    if (row.repositoryId) {
      const [repo] = await db
        .select({ name: repositories.name, username: users.username })
        .from(repositories)
        .innerJoin(users, eq(repositories.ownerId, users.id))
        .where(eq(repositories.id, row.repositoryId))
        .limit(1);
      if (repo) {
        repoOwner = repo.username;
        repoName = repo.name;
      }
    }

    return {
      messages: loadMessages(row.messages),
      repoOwner,
      repoName,
    };
  } catch {
    return null;
  }
}

async function appendMessage(opts: {
  userId: string;
  chatId: string | null;
  repositoryId: string | null;
  userMessage: string;
  aiReply: string;
  history: ChatMessage[];
  title: string;
}): Promise<string> {
  const newHistory: ChatMessage[] = [
    ...opts.history,
    { role: "user", content: opts.userMessage },
    { role: "assistant", content: opts.aiReply },
  ];
  try {
    if (opts.chatId) {
      await db
        .update(aiChats)
        .set({ messages: JSON.stringify(newHistory), updatedAt: new Date() })
        .where(eq(aiChats.id, opts.chatId));
      return opts.chatId;
    }
    const [row] = await db
      .insert(aiChats)
      .values({
        userId: opts.userId,
        repositoryId: opts.repositoryId ?? undefined,
        title: opts.title.slice(0, 80),
        messages: JSON.stringify(newHistory),
      })
      .returning();
    return row?.id || "";
  } catch (err) {
    console.error("[ask] persist failed:", err);
    return opts.chatId || "";
  }
}

// ---------- Global assistant ----------

ask.get("/ask", requireAuth, async (c) => {
  const user = c.get("user")!;
  const unread = await getUnreadCount(user.id);
  let recent: Array<{ id: string; title: string | null; updatedAt: Date }> = [];
  try {
    recent = await db
      .select({
        id: aiChats.id,
        title: aiChats.title,
        updatedAt: aiChats.updatedAt,
      })
      .from(aiChats)
      .where(eq(aiChats.userId, user.id))
      .orderBy(desc(aiChats.updatedAt))
      .limit(10);
  } catch {
    /* ignore */
  }

  return renderChatView(c, {
    messages: [],
    postUrl: "/ask",
    title: "Ask AI",
    subtitle:
      "Ask about GlueCron, your repos, or paste a diff to review. Claude is grounded in your repo when visiting /:owner/:repo/ask.",
    placeholder: "Ask anything...",
    recentChats: recent,
    user,
    unreadCount: unread,
  });
});

ask.get("/ask/:chatId", requireAuth, async (c) => {
  const user = c.get("user")!;
  const chatId = c.req.param("chatId");
  const resumed = await resumeChat(user.id, chatId);
  if (!resumed) return c.redirect("/ask");
  const unread = await getUnreadCount(user.id);
  return renderChatView(c, {
    messages: resumed.messages,
    postUrl:
      resumed.repoOwner && resumed.repoName
        ? `/${resumed.repoOwner}/${resumed.repoName}/ask?chatId=${chatId}`
        : `/ask?chatId=${chatId}`,
    title:
      resumed.repoOwner && resumed.repoName
        ? `${resumed.repoOwner}/${resumed.repoName} — AI chat`
        : "Ask AI",
    placeholder: "Continue the conversation...",
    user,
    unreadCount: unread,
  });
});

ask.post("/ask", requireAuth, async (c) => {
  const user = c.get("user")!;
  const body = await c.req.parseBody();
  const userMessage = String(body.message || "").trim();
  const chatId = (c.req.query("chatId") || "").trim();
  if (!userMessage) return c.redirect("/ask");

  let history: ChatMessage[] = [];
  if (chatId) {
    const existing = await resumeChat(user.id, chatId);
    if (existing) history = existing.messages;
  }

  const response = await chat(user.username, null, history, userMessage);
  const nextId = await appendMessage({
    userId: user.id,
    chatId: chatId || null,
    repositoryId: null,
    userMessage,
    aiReply: response.reply,
    history,
    title: userMessage,
  });

  return c.redirect(nextId ? `/ask/${nextId}` : "/ask");
});

// ---------- Repo-grounded assistant ----------

ask.get("/:owner/:repo/ask", requireAuth, async (c) => {
  const user = c.get("user")!;
  const { owner, repo } = c.req.param();

  // Verify repo exists
  const [repoRow] = await db
    .select({ id: repositories.id })
    .from(repositories)
    .innerJoin(users, eq(repositories.ownerId, users.id))
    .where(and(eq(users.username, owner), eq(repositories.name, repo)))
    .limit(1);
  if (!repoRow) return c.notFound();

  const unread = await getUnreadCount(user.id);

  let recent: Array<{ id: string; title: string | null; updatedAt: Date }> = [];
  try {
    recent = await db
      .select({
        id: aiChats.id,
        title: aiChats.title,
        updatedAt: aiChats.updatedAt,
      })
      .from(aiChats)
      .where(
        and(
          eq(aiChats.userId, user.id),
          eq(aiChats.repositoryId, repoRow.id)
        )
      )
      .orderBy(desc(aiChats.updatedAt))
      .limit(10);
  } catch {
    /* ignore */
  }

  return renderChatView(c, {
    messages: [],
    postUrl: `/${owner}/${repo}/ask`,
    title: `Ask about ${owner}/${repo}`,
    subtitle:
      "Claude has access to this repository's README, tree, and recent commits. Reference files with @path/to/file.",
    placeholder: `Ask about ${repo}...`,
    recentChats: recent,
    user,
    unreadCount: unread,
  });
});

ask.post("/:owner/:repo/ask", requireAuth, async (c) => {
  const user = c.get("user")!;
  const { owner, repo } = c.req.param();
  const body = await c.req.parseBody();
  const userMessage = String(body.message || "").trim();
  const chatId = (c.req.query("chatId") || "").trim();
  if (!userMessage) return c.redirect(`/${owner}/${repo}/ask`);

  const [repoRow] = await db
    .select({ id: repositories.id })
    .from(repositories)
    .innerJoin(users, eq(repositories.ownerId, users.id))
    .where(and(eq(users.username, owner), eq(repositories.name, repo)))
    .limit(1);
  if (!repoRow) return c.notFound();

  let history: ChatMessage[] = [];
  if (chatId) {
    const existing = await resumeChat(user.id, chatId);
    if (existing) history = existing.messages;
  }

  const response = await chat(owner, repo, history, userMessage);
  const nextId = await appendMessage({
    userId: user.id,
    chatId: chatId || null,
    repositoryId: repoRow.id,
    userMessage,
    aiReply: response.reply,
    history,
    title: userMessage,
  });

  return c.redirect(
    nextId ? `/ask/${nextId}` : `/${owner}/${repo}/ask`
  );
});

// ---------- Explain-this-file helper ----------

ask.post("/:owner/:repo/explain", requireAuth, async (c) => {
  const { owner, repo } = c.req.param();
  const body = await c.req.parseBody().catch(() => ({}));
  const filePath = String((body as any).file || c.req.query("file") || "");
  const ref = String((body as any).ref || c.req.query("ref") || "");
  if (!filePath || !ref) {
    return c.json({ error: "file and ref required" }, 400);
  }

  const { getBlob } = await import("../git/repository");
  const blob = await getBlob(owner, repo, ref, filePath);
  if (!blob || blob.isBinary) {
    return c.json({ error: "file not found or binary" }, 404);
  }

  const explanation = await explainFile(owner, repo, filePath, blob.content);
  return c.json({ explanation });
});

export default ask;