gaard-client 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (20) hide show
  1. {gaard_client-0.2.0 → gaard_client-0.2.2}/PKG-INFO +3 -3
  2. {gaard_client-0.2.0 → gaard_client-0.2.2}/pyproject.toml +3 -3
  3. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client/cli_commands.py +5 -2
  4. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client/client-web/assets/styles.css +1 -0
  5. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client/main.py +18 -11
  6. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client.egg-info/PKG-INFO +3 -3
  7. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client.egg-info/SOURCES.txt +0 -1
  8. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client.egg-info/requires.txt +2 -2
  9. {gaard_client-0.2.0 → gaard_client-0.2.2}/tests/test_client_app.py +1 -1
  10. gaard_client-0.2.0/src/gaard_client/client-web/src/main.ts +0 -885
  11. {gaard_client-0.2.0 → gaard_client-0.2.2}/README.md +0 -0
  12. {gaard_client-0.2.0 → gaard_client-0.2.2}/setup.cfg +0 -0
  13. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client/__init__.py +0 -0
  14. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client/cli.py +0 -0
  15. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client/client-web/assets/main.js +0 -0
  16. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client/client-web/index.html +0 -0
  17. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client.egg-info/dependency_links.txt +0 -0
  18. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client.egg-info/entry_points.txt +0 -0
  19. {gaard_client-0.2.0 → gaard_client-0.2.2}/src/gaard_client.egg-info/top_level.txt +0 -0
  20. {gaard_client-0.2.0 → gaard_client-0.2.2}/tests/test_cli.py +0 -0
@@ -1,14 +1,14 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gaard-client
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: GAARD frontend web services providing client interface
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
7
- Requires-Dist: gaard-plugin-api<0.3.0,>=0.2.0
7
+ Requires-Dist: gaard-plugin-api<0.3.0,>=0.2.2
8
8
  Requires-Dist: fastapi>=0.111.0
9
9
  Requires-Dist: uvicorn[standard]>=0.30.0
10
10
  Requires-Dist: pydantic>=2.7.0
11
- Requires-Dist: httpx>=0.27.0
11
+ Requires-Dist: httpx2>=2.5.0
12
12
  Provides-Extra: dev
13
13
  Requires-Dist: pytest>=8.0.0; extra == "dev"
14
14
  Requires-Dist: ruff>=0.5.0; extra == "dev"
@@ -4,17 +4,17 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "gaard-client"
7
- version = "0.2.0"
7
+ version = "0.2.2"
8
8
  description = "GAARD frontend web services providing client interface"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
11
11
 
12
12
  dependencies = [
13
- "gaard-plugin-api>=0.2.0,<0.3.0",
13
+ "gaard-plugin-api>=0.2.2,<0.3.0",
14
14
  "fastapi>=0.111.0",
15
15
  "uvicorn[standard]>=0.30.0",
16
16
  "pydantic>=2.7.0",
17
- "httpx>=0.27.0",
17
+ "httpx2>=2.5.0",
18
18
  ]
19
19
 
20
20
  [project.optional-dependencies]
@@ -1,7 +1,10 @@
1
+ from __future__ import annotations
2
+
1
3
  import uvicorn
4
+ from argparse import ArgumentParser, Namespace, _SubParsersAction
2
5
 
3
6
 
4
- def register(subparsers):
7
+ def register(subparsers: _SubParsersAction[ArgumentParser]) -> None:
5
8
  parser = subparsers.add_parser("client")
6
9
  parser.add_argument("--host", default="127.0.0.1")
7
10
  parser.add_argument("--port", type=int, default=8001)
@@ -9,7 +12,7 @@ def register(subparsers):
9
12
  parser.set_defaults(func=run_client)
10
13
 
11
14
 
12
- def run_client(args):
15
+ def run_client(args: Namespace) -> None:
13
16
  uvicorn.run(
14
17
  "gaard_client.main:app",
15
18
  host=args.host,
@@ -467,6 +467,7 @@ textarea {
467
467
  }
468
468
 
469
469
  .data-table th {
470
+ overflow-wrap: break-word;
470
471
  background: #f7f9fb;
471
472
  color: var(--muted);
472
473
  font-size: 12px;
@@ -1,22 +1,29 @@
1
1
  import json
2
2
  import os
3
- from typing import Any
3
+
4
+ from collections.abc import AsyncIterator
5
+ from importlib.resources import as_file, files
6
+ from pathlib import Path
7
+
8
+ from typing import Any, cast
4
9
  from urllib.parse import urlparse
5
10
 
6
- import httpx
11
+ import httpx2 as httpx
7
12
  from fastapi import FastAPI, HTTPException
8
13
  from fastapi.responses import FileResponse, Response, StreamingResponse
9
14
  from fastapi.staticfiles import StaticFiles
10
15
  from pydantic import BaseModel, Field
11
- from importlib.resources import files
12
16
 
13
17
 
14
- CLIENT_WEB_DIR = files("gaard_client").joinpath("client-web")
18
+ with as_file(files("gaard_client").joinpath("client-web")) as _path:
19
+ CLIENT_WEB_DIR: Path = Path(_path).absolute()
20
+
15
21
  DEFAULT_BACKEND_URL = "http://localhost:8000"
16
22
 
23
+
17
24
  app = FastAPI(
18
25
  title="GAARD Client",
19
- version="0.2.0",
26
+ version="0.2.2",
20
27
  description="Community client for asking governed natural-language questions.",
21
28
  )
22
29
 
@@ -110,7 +117,7 @@ async def query_backend(request: ClientQueryRequest) -> dict[str, Any]:
110
117
  else response.text,
111
118
  )
112
119
 
113
- return response.json()
120
+ return cast(dict[str, Any], response.json())
114
121
 
115
122
 
116
123
  @app.post("/api/widgets/from-query")
@@ -145,7 +152,7 @@ async def create_widget_from_query(request: ClientWidgetFromQueryRequest) -> dic
145
152
  else response.text,
146
153
  )
147
154
 
148
- return response.json()
155
+ return cast(dict[str, Any], response.json())
149
156
 
150
157
 
151
158
  @app.post("/api/query/stream")
@@ -153,7 +160,7 @@ async def query_backend_stream(request: ClientQueryRequest) -> StreamingResponse
153
160
  backend_url = normalize_backend_url(request.backend_url or get_default_backend_url())
154
161
  query_url = f"{backend_url}/api/v1/query/stream"
155
162
 
156
- async def stream_backend():
163
+ async def stream_backend() -> AsyncIterator[str]:
157
164
  try:
158
165
  async with httpx.AsyncClient(timeout=120.0) as client:
159
166
  async with client.stream(
@@ -201,7 +208,7 @@ async def analysis_backend_stream(request: ClientQueryRequest) -> StreamingRespo
201
208
  backend_url = normalize_backend_url(request.backend_url or get_default_backend_url())
202
209
  analysis_url = f"{backend_url}/api/v1/analysis/stream"
203
210
 
204
- async def stream_backend():
211
+ async def stream_backend() -> AsyncIterator[str]:
205
212
  async for chunk in proxy_stream(
206
213
  url=analysis_url,
207
214
  payload={
@@ -222,7 +229,7 @@ async def analysis_message_backend_stream(
222
229
  backend_url = normalize_backend_url(request.backend_url or get_default_backend_url())
223
230
  analysis_url = f"{backend_url}/api/v1/analysis/{session_id}/messages/stream"
224
231
 
225
- async def stream_backend():
232
+ async def stream_backend() -> AsyncIterator[str]:
226
233
  async for chunk in proxy_stream(
227
234
  url=analysis_url,
228
235
  payload={
@@ -234,7 +241,7 @@ async def analysis_message_backend_stream(
234
241
  return StreamingResponse(stream_backend(), media_type="application/x-ndjson")
235
242
 
236
243
 
237
- async def proxy_stream(url: str, payload: dict[str, Any]):
244
+ async def proxy_stream(url: str, payload: dict[str, Any]) -> AsyncIterator[str]:
238
245
  try:
239
246
  async with httpx.AsyncClient(timeout=120.0) as client:
240
247
  async with client.stream("POST", url, json=payload) as response:
@@ -1,14 +1,14 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gaard-client
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: GAARD frontend web services providing client interface
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
7
- Requires-Dist: gaard-plugin-api<0.3.0,>=0.2.0
7
+ Requires-Dist: gaard-plugin-api<0.3.0,>=0.2.2
8
8
  Requires-Dist: fastapi>=0.111.0
9
9
  Requires-Dist: uvicorn[standard]>=0.30.0
10
10
  Requires-Dist: pydantic>=2.7.0
11
- Requires-Dist: httpx>=0.27.0
11
+ Requires-Dist: httpx2>=2.5.0
12
12
  Provides-Extra: dev
13
13
  Requires-Dist: pytest>=8.0.0; extra == "dev"
14
14
  Requires-Dist: ruff>=0.5.0; extra == "dev"
@@ -13,6 +13,5 @@ src/gaard_client.egg-info/top_level.txt
13
13
  src/gaard_client/client-web/index.html
14
14
  src/gaard_client/client-web/assets/main.js
15
15
  src/gaard_client/client-web/assets/styles.css
16
- src/gaard_client/client-web/src/main.ts
17
16
  tests/test_cli.py
18
17
  tests/test_client_app.py
@@ -1,8 +1,8 @@
1
- gaard-plugin-api<0.3.0,>=0.2.0
1
+ gaard-plugin-api<0.3.0,>=0.2.2
2
2
  fastapi>=0.111.0
3
3
  uvicorn[standard]>=0.30.0
4
4
  pydantic>=2.7.0
5
- httpx>=0.27.0
5
+ httpx2>=2.5.0
6
6
 
7
7
  [dev]
8
8
  pytest>=8.0.0
@@ -1,6 +1,6 @@
1
1
  import json
2
2
 
3
- import httpx
3
+ import httpx2 as httpx
4
4
  from fastapi.testclient import TestClient
5
5
 
6
6
  from gaard_client.main import app
@@ -1,885 +0,0 @@
1
- type QueryMetadata = {
2
- duration_ms?: number;
3
- datasource_id?: string;
4
- query_mode?: string;
5
- analysis_mode?: string;
6
- analysis_session_id?: string;
7
- analysis_status?: string;
8
- analysis_supporting_data?: boolean;
9
- analysis_supporting_question?: string;
10
- analysis_supporting_step?: string;
11
- output_classification?: string;
12
- output_classification_mode?: string;
13
- result_interpretation_mode?: string;
14
- sql_generation_mode?: string;
15
- };
16
-
17
- type QueryMode = "sql" | "analysis";
18
-
19
- type QueryResponse = {
20
- answer: string;
21
- sql?: string;
22
- rows?: Record<string, unknown>[];
23
- metadata?: QueryMetadata;
24
- };
25
-
26
- type ProgressUpdate = {
27
- event: string;
28
- title: string;
29
- detail: string;
30
- items: string[];
31
- };
32
-
33
- type Message = {
34
- id: number;
35
- question: string;
36
- mode: QueryMode;
37
- status: "pending" | "waiting" | "ok" | "error";
38
- response: QueryResponse | null;
39
- error: string;
40
- dataOpen: boolean;
41
- saveStatus: "idle" | "saving" | "saved" | "error";
42
- saveError: string;
43
- progress: ProgressUpdate[];
44
- progressOpen: boolean;
45
- analysisSessionId: string;
46
- userQuestion: string;
47
- };
48
-
49
- declare global {
50
- interface Window {
51
- GAARD_CLIENT_CONFIG?: {
52
- backendUrl?: string;
53
- };
54
- }
55
- }
56
-
57
- const app = document.querySelector<HTMLDivElement>("#app");
58
-
59
- const params = new URLSearchParams(window.location.search);
60
- const configuredBackendUrl = (
61
- params.get("backendUrl") ||
62
- params.get("apiUrl") ||
63
- window.GAARD_CLIENT_CONFIG?.backendUrl ||
64
- "http://localhost:8000"
65
- ).replace(/\/+$/, "");
66
-
67
- const state: {
68
- backendUrl: string;
69
- queryMode: QueryMode;
70
- messages: Message[];
71
- nextMessageId: number;
72
- pending: boolean;
73
- error: string;
74
- } = {
75
- backendUrl: configuredBackendUrl,
76
- queryMode: normalizeQueryMode(params.get("mode")),
77
- messages: [],
78
- nextMessageId: 1,
79
- pending: false,
80
- error: "",
81
- };
82
-
83
- function escapeHtml(value: unknown): string {
84
- return String(value ?? "")
85
- .replaceAll("&", "&amp;")
86
- .replaceAll("<", "&lt;")
87
- .replaceAll(">", "&gt;")
88
- .replaceAll('"', "&quot;")
89
- .replaceAll("'", "&#039;");
90
- }
91
-
92
- function render(options: { scrollToLatest?: boolean } = {}): void {
93
- if (!app) return;
94
-
95
- app.innerHTML = `
96
- <main class="shell">
97
- <header class="header">
98
- <h1>GAARD - Governed AI Access to Relational Data</h1>
99
- </header>
100
- <section class="history" aria-live="polite">
101
- ${state.messages.length ? state.messages.map(renderMessage).join("") : `<div class="empty-state">Ask a governed data question.</div>`}
102
- </section>
103
- <form id="query-form" class="query-bar">
104
- <fieldset class="mode-control" ${state.pending ? "disabled" : ""}>
105
- <legend>Mode</legend>
106
- <label class="${state.queryMode === "sql" ? "active" : ""}">
107
- <input type="radio" name="mode" value="sql" ${state.queryMode === "sql" ? "checked" : ""}>
108
- <span>SQL</span>
109
- </label>
110
- <label class="${state.queryMode === "analysis" ? "active" : ""}">
111
- <input type="radio" name="mode" value="analysis" ${state.queryMode === "analysis" ? "checked" : ""}>
112
- <span>Analysis</span>
113
- </label>
114
- </fieldset>
115
- <textarea id="question-input" name="question" placeholder="Ask a question" rows="1" ${state.pending ? "disabled" : ""}></textarea>
116
- <button class="send-button" type="submit" aria-label="Send question" title="Send" ${state.pending ? "disabled" : ""}>
117
- <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
118
- <path d="M22 2 11 13" />
119
- <path d="m22 2-7 20-4-9-9-4Z" />
120
- </svg>
121
- </button>
122
- </form>
123
- </main>`;
124
-
125
- document.querySelector<HTMLFormElement>("#query-form")?.addEventListener("submit", submitQuestion);
126
- document.querySelectorAll<HTMLInputElement>('input[name="mode"]').forEach((input) => {
127
- input.addEventListener("change", handleModeChange);
128
- });
129
- document.querySelectorAll<HTMLButtonElement>("[data-toggle-data]").forEach((button) => {
130
- button.addEventListener("click", toggleDataTable);
131
- });
132
- document.querySelectorAll<HTMLButtonElement>("[data-retry-question]").forEach((button) => {
133
- button.addEventListener("click", retryQuestion);
134
- });
135
- document.querySelectorAll<HTMLButtonElement>("[data-save-widget]").forEach((button) => {
136
- button.addEventListener("click", saveWidgetFromMessage);
137
- });
138
- document.querySelectorAll<HTMLFormElement>("[data-analysis-reply-form]").forEach((form) => {
139
- form.addEventListener("submit", submitAnalysisReply);
140
- });
141
- document.querySelectorAll<HTMLDetailsElement>("[data-analysis-progress]").forEach((details) => {
142
- details.addEventListener("toggle", toggleAnalysisProgress);
143
- });
144
- const input = document.querySelector<HTMLTextAreaElement>("#question-input");
145
- input?.addEventListener("keydown", handleQuestionKeydown);
146
- input?.focus();
147
-
148
- if (options.scrollToLatest) {
149
- scrollToLatest();
150
- }
151
- }
152
-
153
- function renderMessage(message: Message): string {
154
- const rows = getRows(message.response);
155
- const meta = message.status === "ok" ? renderMeta(message, rows) : "";
156
- const answer = message.status === "pending"
157
- ? "Processing..."
158
- : message.status === "waiting"
159
- ? "Waiting for your answer."
160
- : message.status === "error"
161
- ? message.error
162
- : message.response?.answer || "";
163
- const dataTable = message.status === "ok" && message.dataOpen ? renderDataTable(rows) : "";
164
- const mockWarning = message.status === "ok" ? renderMockWarning(message.response?.metadata) : "";
165
- const saveNotice = renderSaveNotice(message);
166
- const progress = message.mode === "analysis"
167
- ? renderAnalysisProgress(message)
168
- : "";
169
- const analysisReply = message.status === "waiting" ? renderAnalysisReply(message) : "";
170
-
171
- return `
172
- <article class="exchange ${message.status}">
173
- <div class="exchange-top">
174
- <div class="question">
175
- <span>Question · ${escapeHtml(formatMode(message.mode))}</span>
176
- <p>${escapeHtml(message.question)}</p>
177
- </div>
178
- ${renderMessageActions(message)}
179
- </div>
180
- <div class="answer">
181
- <span>Answer</span>
182
- <p>${escapeHtml(answer)}</p>
183
- </div>
184
- ${progress}
185
- ${analysisReply}
186
- ${mockWarning}
187
- ${saveNotice}
188
- ${meta}
189
- ${dataTable}
190
- </article>`;
191
- }
192
-
193
- function renderMessageActions(message: Message): string {
194
- const saveDisabled = state.pending || message.saveStatus === "saving" || message.saveStatus === "saved";
195
- const saveTitle = message.saveStatus === "saved"
196
- ? "Saved as widget"
197
- : message.saveStatus === "saving"
198
- ? "Saving widget"
199
- : "Save as widget";
200
-
201
- return `
202
- <div class="message-actions">
203
- <button class="retry-button" type="button" data-retry-question="${message.id}" aria-label="Copy question to input" title="Retry question" ${state.pending ? "disabled" : ""}>
204
- <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
205
- <path d="M3 12a9 9 0 1 0 2.64-6.36L3 8" />
206
- <path d="M3 3v5h5" />
207
- </svg>
208
- </button>
209
- ${canSaveWidget(message) ? `
210
- <button class="save-widget-button" type="button" data-save-widget="${message.id}" aria-label="Save question as widget" title="${escapeHtml(saveTitle)}" ${saveDisabled ? "disabled" : ""}>
211
- <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
212
- <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z" />
213
- <path d="M17 21v-8H7v8" />
214
- <path d="M7 3v5h8" />
215
- </svg>
216
- </button>` : ""}
217
- </div>`;
218
- }
219
-
220
- function canSaveWidget(message: Message): boolean {
221
- return message.status === "ok" && Boolean(message.response?.sql?.trim());
222
- }
223
-
224
- function renderSaveNotice(message: Message): string {
225
- if (message.saveStatus === "saved") {
226
- return `<div class="save-notice success" role="status">Saved as inactive widget.</div>`;
227
- }
228
-
229
- if (message.saveStatus === "error") {
230
- return `<div class="save-notice error" role="alert">${escapeHtml(message.saveError || "Widget could not be saved.")}</div>`;
231
- }
232
-
233
- return "";
234
- }
235
-
236
- function renderAnalysisProgress(message: Message): string {
237
- if (!message.progress.length) {
238
- return "";
239
- }
240
-
241
- const latest = message.progress[message.progress.length - 1];
242
- return `
243
- <details class="analysis-log" data-analysis-progress="${message.id}" ${message.progressOpen ? "open" : ""}>
244
- <summary>
245
- <span>Analysis</span>
246
- <strong>${escapeHtml(latest.title)}</strong>
247
- ${latest.detail ? `<small>${escapeHtml(latest.detail)}</small>` : ""}
248
- </summary>
249
- <ol class="analysis-progress" aria-label="Analysis progress">
250
- ${message.progress.map((update, index) => `
251
- <li class="${index === message.progress.length - 1 ? "active" : "done"}">
252
- <div>
253
- <p>${escapeHtml(update.title)}</p>
254
- ${update.detail ? `<p class="progress-detail">${escapeHtml(update.detail)}</p>` : ""}
255
- ${renderProgressDecisions(update.items)}
256
- </div>
257
- </li>`).join("")}
258
- </ol>
259
- </details>`;
260
- }
261
-
262
- function renderAnalysisReply(message: Message): string {
263
- return `
264
- <form class="analysis-reply" data-analysis-reply-form="${message.id}">
265
- <div class="analysis-reply-question">${escapeHtml(message.userQuestion || "GAARD needs a clarification.")}</div>
266
- <label>
267
- <span>Your answer</span>
268
- <textarea name="reply" rows="2" placeholder="Answer GAARD" ${state.pending ? "disabled" : ""}></textarea>
269
- </label>
270
- <button type="submit" ${state.pending ? "disabled" : ""}>Continue analysis</button>
271
- </form>`;
272
- }
273
-
274
- function renderProgressDecisions(decisions: string[]): string {
275
- const visible = decisions.filter((decision) => decision.trim()).slice(0, 3);
276
-
277
- if (!visible.length) {
278
- return "";
279
- }
280
-
281
- return `<ul>${visible.map((decision) => `<li>${escapeHtml(decision)}</li>`).join("")}</ul>`;
282
- }
283
-
284
- function renderMockWarning(metadata?: QueryMetadata): string {
285
- const mockModes = [
286
- ["SQL generation", metadata?.sql_generation_mode],
287
- ["Result interpretation", metadata?.result_interpretation_mode],
288
- ["Output classification", metadata?.output_classification_mode],
289
- ]
290
- .filter(([, mode]) => mode === "mock")
291
- .map(([label]) => label);
292
-
293
- if (!mockModes.length) {
294
- return "";
295
- }
296
-
297
- return `
298
- <div class="mock-warning" role="status">
299
- This response used mock data processing: ${escapeHtml(mockModes.join(", "))}.
300
- </div>`;
301
- }
302
-
303
- function renderMeta(message: Message, rows: Record<string, unknown>[]): string {
304
- const metadata = message.response?.metadata || {};
305
- const buttonText = message.dataOpen ? "Hide data" : `Data (${rows.length})`;
306
- const mode = metadata.analysis_mode === "analysis" ? "analysis" : metadata.query_mode || message.mode;
307
-
308
- return `
309
- <div class="meta-row">
310
- <dl class="meta">
311
- <div><dt>Time</dt><dd>${escapeHtml(formatDuration(metadata.duration_ms))}</dd></div>
312
- <div><dt>Datasource</dt><dd>${escapeHtml(metadata.datasource_id || "-")}</dd></div>
313
- <div><dt>Mode</dt><dd>${escapeHtml(formatMode(mode))}</dd></div>
314
- <div><dt>Output</dt><dd>${escapeHtml(metadata.output_classification || "unknown")}</dd></div>
315
- </dl>
316
- <button class="data-toggle" type="button" data-toggle-data="${message.id}" aria-expanded="${message.dataOpen ? "true" : "false"}">
317
- ${escapeHtml(buttonText)}
318
- </button>
319
- </div>`;
320
- }
321
-
322
- function formatDuration(value: unknown): string {
323
- const numeric = Number(value);
324
-
325
- if (!Number.isFinite(numeric)) {
326
- return "-";
327
- }
328
-
329
- return `${numeric} ms`;
330
- }
331
-
332
- function formatMode(value: unknown): string {
333
- return value === "analysis" ? "Analysis" : "SQL";
334
- }
335
-
336
- function normalizeQueryMode(value: unknown): QueryMode {
337
- return value === "analysis" ? "analysis" : "sql";
338
- }
339
-
340
- function handleModeChange(event: Event): void {
341
- state.queryMode = normalizeQueryMode((event.currentTarget as HTMLInputElement).value);
342
- render();
343
- }
344
-
345
- function handleQuestionKeydown(event: KeyboardEvent): void {
346
- if (event.key === "Enter" && !event.shiftKey) {
347
- event.preventDefault();
348
- (event.currentTarget as HTMLTextAreaElement).form?.requestSubmit();
349
- }
350
- }
351
-
352
- function toggleDataTable(event: Event): void {
353
- const id = Number((event.currentTarget as HTMLButtonElement).dataset.toggleData);
354
- const message = state.messages.find((item) => item.id === id);
355
-
356
- if (!message) return;
357
-
358
- message.dataOpen = !message.dataOpen;
359
- const latestMessage = state.messages[state.messages.length - 1];
360
-
361
- render({
362
- scrollToLatest: message.dataOpen && latestMessage?.id === message.id,
363
- });
364
- }
365
-
366
- function toggleAnalysisProgress(event: Event): void {
367
- const details = event.currentTarget as HTMLDetailsElement;
368
- const id = Number(details.dataset.analysisProgress);
369
- const message = state.messages.find((item) => item.id === id);
370
-
371
- if (message) {
372
- message.progressOpen = details.open;
373
- }
374
- }
375
-
376
- function retryQuestion(event: Event): void {
377
- const id = Number((event.currentTarget as HTMLButtonElement).dataset.retryQuestion);
378
- const message = state.messages.find((item) => item.id === id);
379
-
380
- if (!message || state.pending) return;
381
-
382
- state.queryMode = message.mode;
383
- render();
384
- const refreshedInput = document.querySelector<HTMLTextAreaElement>("#question-input");
385
-
386
- if (!refreshedInput || refreshedInput.disabled) return;
387
-
388
- refreshedInput.value = message.question;
389
- refreshedInput.focus();
390
- refreshedInput.setSelectionRange(refreshedInput.value.length, refreshedInput.value.length);
391
- }
392
-
393
- async function saveWidgetFromMessage(event: Event): Promise<void> {
394
- const id = Number((event.currentTarget as HTMLButtonElement).dataset.saveWidget);
395
- const message = state.messages.find((item) => item.id === id);
396
- const sql = message?.response?.sql?.trim() || "";
397
-
398
- if (!message || !sql || message.saveStatus === "saving" || message.saveStatus === "saved") {
399
- return;
400
- }
401
-
402
- message.saveStatus = "saving";
403
- message.saveError = "";
404
- render();
405
-
406
- try {
407
- const response = await fetch("/api/widgets/from-query", {
408
- method: "POST",
409
- headers: {
410
- "Content-Type": "application/json",
411
- },
412
- body: JSON.stringify({
413
- label: buildWidgetLabel(message.question),
414
- widget_type: inferWidgetType(getRows(message.response)),
415
- datasource_key: message.response?.metadata?.datasource_id || "default",
416
- question: message.question,
417
- sql,
418
- result_mode: "data",
419
- backend_url: state.backendUrl,
420
- }),
421
- });
422
- const payload = await response.json().catch(() => ({}));
423
-
424
- if (!response.ok) {
425
- throw new Error(extractErrorMessage(payload));
426
- }
427
-
428
- message.saveStatus = "saved";
429
- } catch (error) {
430
- message.saveStatus = "error";
431
- message.saveError = (error as Error).message || "Widget could not be saved.";
432
- } finally {
433
- render();
434
- }
435
- }
436
-
437
- function buildWidgetLabel(question: string): string {
438
- const compact = question.replace(/\s+/g, " ").trim();
439
-
440
- return compact.length > 64 ? `${compact.slice(0, 61)}...` : compact || "Saved query";
441
- }
442
-
443
- function inferWidgetType(rows: Record<string, unknown>[]): "scalar" | "table" {
444
- if (rows.length === 1 && Object.keys(rows[0] || {}).length === 1) {
445
- return "scalar";
446
- }
447
-
448
- return "table";
449
- }
450
-
451
- function getSelectedMode(form: HTMLFormElement): QueryMode {
452
- const value = new FormData(form).get("mode");
453
-
454
- return normalizeQueryMode(value);
455
- }
456
-
457
- async function submitQuestion(event: Event): Promise<void> {
458
- event.preventDefault();
459
-
460
- if (state.pending) return;
461
-
462
- const form = event.currentTarget as HTMLFormElement;
463
- const input = form.elements.namedItem("question") as HTMLTextAreaElement | null;
464
- const question = String(input?.value || "").trim();
465
- const mode = getSelectedMode(form);
466
-
467
- if (!question) return;
468
-
469
- if (input) input.value = "";
470
-
471
- state.error = "";
472
- state.pending = true;
473
- const message: Message = {
474
- id: state.nextMessageId,
475
- question,
476
- mode,
477
- status: "pending",
478
- response: null,
479
- error: "",
480
- dataOpen: false,
481
- saveStatus: "idle",
482
- saveError: "",
483
- progress: [],
484
- progressOpen: false,
485
- analysisSessionId: "",
486
- userQuestion: "",
487
- };
488
- state.nextMessageId += 1;
489
- state.messages.push(message);
490
- render({ scrollToLatest: true });
491
-
492
- try {
493
- if (mode === "analysis") {
494
- await submitAnalysisQuestion(message, question);
495
- } else {
496
- const response = await fetch("/api/query", {
497
- method: "POST",
498
- headers: {
499
- "Content-Type": "application/json",
500
- },
501
- body: JSON.stringify({
502
- question,
503
- mode,
504
- backend_url: state.backendUrl,
505
- }),
506
- });
507
- const payload = await response.json().catch(() => ({}));
508
-
509
- if (!response.ok) {
510
- throw new Error(extractErrorMessage(payload));
511
- }
512
-
513
- message.status = "ok";
514
- message.response = payload;
515
- }
516
- } catch (error) {
517
- message.status = "error";
518
- message.error = (error as Error).message || "Request failed.";
519
- } finally {
520
- state.pending = false;
521
- render({ scrollToLatest: true });
522
- }
523
- }
524
-
525
- async function submitAnalysisQuestion(
526
- message: Message,
527
- question: string,
528
- ): Promise<void> {
529
- const response = await fetch("/api/analysis/stream", {
530
- method: "POST",
531
- headers: {
532
- "Content-Type": "application/json",
533
- },
534
- body: JSON.stringify({
535
- question,
536
- backend_url: state.backendUrl,
537
- }),
538
- });
539
-
540
- if (!response.ok) {
541
- const payload = await response.json().catch(() => ({}));
542
- throw new Error(extractErrorMessage(payload));
543
- }
544
-
545
- await readAnalysisStream(message, response);
546
- }
547
-
548
- async function submitAnalysisReply(event: Event): Promise<void> {
549
- event.preventDefault();
550
-
551
- if (state.pending) return;
552
-
553
- const form = event.currentTarget as HTMLFormElement;
554
- const id = Number(form.dataset.analysisReplyForm);
555
- const message = state.messages.find((item) => item.id === id);
556
- const input = form.elements.namedItem("reply") as HTMLTextAreaElement | null;
557
- const reply = String(input?.value || "").trim();
558
-
559
- if (!message || !message.analysisSessionId || !reply) return;
560
-
561
- state.pending = true;
562
- message.status = "pending";
563
- message.userQuestion = "";
564
- render({ scrollToLatest: true });
565
-
566
- try {
567
- await continueAnalysis(message, reply);
568
- } catch (error) {
569
- message.status = "error";
570
- message.error = (error as Error).message || "Request failed.";
571
- } finally {
572
- state.pending = false;
573
- render({ scrollToLatest: true });
574
- }
575
- }
576
-
577
- async function continueAnalysis(message: Message, reply: string): Promise<void> {
578
- const response = await fetch(`/api/analysis/${encodeURIComponent(message.analysisSessionId)}/messages/stream`, {
579
- method: "POST",
580
- headers: {
581
- "Content-Type": "application/json",
582
- },
583
- body: JSON.stringify({
584
- message: reply,
585
- backend_url: state.backendUrl,
586
- }),
587
- });
588
-
589
- if (!response.ok) {
590
- const payload = await response.json().catch(() => ({}));
591
- throw new Error(extractErrorMessage(payload));
592
- }
593
-
594
- await readAnalysisStream(message, response);
595
- }
596
-
597
- async function readAnalysisStream(message: Message, response: Response): Promise<void> {
598
- if (!response.body) {
599
- throw new Error("Streaming response is not available.");
600
- }
601
-
602
- const reader = response.body.getReader();
603
- const decoder = new TextDecoder();
604
- let buffer = "";
605
- let finalReceived = false;
606
-
607
- while (true) {
608
- const { done, value } = await reader.read();
609
- if (done) break;
610
-
611
- buffer += decoder.decode(value, { stream: true });
612
- const lines = buffer.split("\n");
613
- buffer = lines.pop() || "";
614
-
615
- for (const line of lines) {
616
- finalReceived = handleAnalysisStreamLine(message, line) || finalReceived;
617
- }
618
- }
619
-
620
- buffer += decoder.decode();
621
- if (buffer.trim()) {
622
- finalReceived = handleAnalysisStreamLine(message, buffer) || finalReceived;
623
- }
624
-
625
- if (!finalReceived && message.status !== "waiting") {
626
- throw new Error("Analysis stream ended without a final response.");
627
- }
628
- }
629
-
630
- function handleAnalysisStreamLine(message: Message, line: string): boolean {
631
- const trimmed = line.trim();
632
-
633
- if (!trimmed) return false;
634
-
635
- const payload = JSON.parse(trimmed);
636
-
637
- if (payload?.error?.message) {
638
- throw new Error(payload.error.message);
639
- }
640
-
641
- if (payload?.final) {
642
- message.status = "ok";
643
- message.response = payload.final;
644
- message.dataOpen = message.mode === "analysis" && getRows(payload.final).length > 0;
645
- message.userQuestion = "";
646
- render({ scrollToLatest: true });
647
- return true;
648
- }
649
-
650
- if (payload?.session_id && !message.analysisSessionId) {
651
- message.analysisSessionId = String(payload.session_id);
652
- }
653
-
654
- if (payload?.event === "user_question") {
655
- const question = extractUserQuestion(payload);
656
- message.status = "waiting";
657
- message.userQuestion = question;
658
- message.progress = [
659
- ...message.progress,
660
- {
661
- event: "user_question",
662
- title: "GAARD needs your clarification",
663
- detail: question,
664
- items: [],
665
- },
666
- ];
667
- render({ scrollToLatest: true });
668
- return false;
669
- }
670
-
671
- const progress = progressFromAnalysisEvent(payload);
672
- if (progress) {
673
- message.progress = [...message.progress, progress];
674
- render({ scrollToLatest: true });
675
- }
676
-
677
- return false;
678
- }
679
-
680
- function firstText(...values: unknown[]): string {
681
- for (const value of values) {
682
- const text = String(value || "").trim();
683
- if (text) return text;
684
- }
685
-
686
- return "";
687
- }
688
-
689
- function extractUserQuestion(payload: any): string {
690
- const userQuestion = payload?.user_question;
691
-
692
- return firstText(
693
- typeof userQuestion === "string" ? userQuestion : "",
694
- userQuestion?.question,
695
- userQuestion?.message,
696
- userQuestion?.visible_question,
697
- payload?.question,
698
- payload?.decision?.user_question,
699
- payload?.decision?.visible_question,
700
- "GAARD needs a clarification.",
701
- );
702
- }
703
-
704
- function progressFromAnalysisEvent(payload: any): ProgressUpdate | null {
705
- const event = String(payload?.event || "");
706
-
707
- if (event === "analysis_step") {
708
- const step = payload.analysis_step || {};
709
- return {
710
- event,
711
- title: step.visible_question || "GAARD is checking the next analysis step.",
712
- detail: step.visible_reasoning || "",
713
- items: [`Iteration ${step.iteration || payload.sequence || ""}`].filter(Boolean),
714
- };
715
- }
716
-
717
- if (event === "decision") {
718
- const decision = payload.decision || {};
719
- return {
720
- event,
721
- title: `Decision: ${formatAnalysisAction(decision.action)}`,
722
- detail: decision.visible_reasoning || decision.visible_question || "",
723
- items: [
724
- decision.user_question ? `Question for you: ${decision.user_question}` : "",
725
- decision.database_question ? `Database question: ${decision.database_question}` : "",
726
- decision.final_question ? `Final query question: ${decision.final_question}` : "",
727
- decision.answer ? `Context answer prepared.` : "",
728
- ].filter(Boolean),
729
- };
730
- }
731
-
732
- if (event === "database_question") {
733
- const question = payload.database_question || {};
734
- return {
735
- event,
736
- title: question.final ? "GAARD asks the final database question" : "GAARD asks the database",
737
- detail: question.question || "",
738
- items: [],
739
- };
740
- }
741
-
742
- if (event === "database_result") {
743
- const result = payload.database_result || {};
744
- return {
745
- event,
746
- title: "Database result received",
747
- detail: result.answer || "",
748
- items: [
749
- result.sql ? `SQL: ${result.sql}` : "",
750
- Array.isArray(result.rows) ? `Rows: ${result.rows.length}` : "",
751
- ].filter(Boolean),
752
- };
753
- }
754
-
755
- if (event === "business_logic_suggestion") {
756
- const suggestion = payload.business_logic_suggestion || {};
757
- return {
758
- event,
759
- title: suggestion.enabled
760
- ? "Business logic finding enabled"
761
- : "Business logic finding saved for review",
762
- detail: suggestion.title || suggestion.rule_text || "",
763
- items: [
764
- suggestion.error_category ? `Type: ${suggestion.error_category}` : "",
765
- suggestion.confidence !== undefined ? `Confidence: ${suggestion.confidence}` : "",
766
- ].filter(Boolean),
767
- };
768
- }
769
-
770
- if (event === "limit_reached") {
771
- return {
772
- event,
773
- title: "Analysis loop limit reached",
774
- detail: `Limit: ${payload.limit_reached?.analysis_loop_count || "-"}`,
775
- items: [],
776
- };
777
- }
778
-
779
- if (event === "session_started" || event === "session_resumed") {
780
- return null;
781
- }
782
-
783
- return null;
784
- }
785
-
786
- function formatAnalysisAction(value: unknown): string {
787
- return String(value || "unknown").replaceAll("_", " ");
788
- }
789
-
790
- function extractErrorMessage(payload: any): string {
791
- const detail = payload?.detail;
792
-
793
- if (typeof detail === "string") {
794
- return detail;
795
- }
796
-
797
- if (detail?.error?.message) {
798
- return detail.error.message;
799
- }
800
-
801
- if (payload?.error?.message) {
802
- return payload.error.message;
803
- }
804
-
805
- return "Request failed.";
806
- }
807
-
808
- function getRows(response: QueryResponse | null): Record<string, unknown>[] {
809
- return Array.isArray(response?.rows) ? response.rows : [];
810
- }
811
-
812
- function getColumns(rows: Record<string, unknown>[]): string[] {
813
- const columns: string[] = [];
814
-
815
- rows.forEach((row) => {
816
- if (!row || typeof row !== "object" || Array.isArray(row)) return;
817
-
818
- Object.keys(row).forEach((column) => {
819
- if (!columns.includes(column)) {
820
- columns.push(column);
821
- }
822
- });
823
- });
824
-
825
- return columns;
826
- }
827
-
828
- function renderDataTable(rows: Record<string, unknown>[]): string {
829
- const columns = getColumns(rows);
830
-
831
- if (!rows.length) {
832
- return `<div class="data-table-empty">No rows returned.</div>`;
833
- }
834
-
835
- if (!columns.length) {
836
- return `<div class="data-table-empty">Rows are not table-shaped.</div>`;
837
- }
838
-
839
- return `
840
- <div class="data-table-wrap" tabindex="0">
841
- <table class="data-table">
842
- <thead>
843
- <tr>${columns.map((column) => `<th scope="col">${escapeHtml(column)}</th>`).join("")}</tr>
844
- </thead>
845
- <tbody>
846
- ${rows.map((row) => `
847
- <tr>
848
- ${columns.map((column) => `<td>${escapeHtml(formatCellValue(row?.[column]))}</td>`).join("")}
849
- </tr>`).join("")}
850
- </tbody>
851
- </table>
852
- </div>`;
853
- }
854
-
855
- function formatCellValue(value: unknown): string {
856
- if (value === null) {
857
- return "null";
858
- }
859
-
860
- if (typeof value === "object") {
861
- return JSON.stringify(value);
862
- }
863
-
864
- return String(value ?? "");
865
- }
866
-
867
- function scrollToLatest(): void {
868
- const scroll = () => {
869
- const history = document.querySelector<HTMLElement>(".history");
870
-
871
- if (!history) return;
872
-
873
- history.scrollTo({
874
- top: history.scrollHeight,
875
- behavior: "auto",
876
- });
877
- };
878
-
879
- requestAnimationFrame(() => {
880
- scroll();
881
- requestAnimationFrame(scroll);
882
- });
883
- }
884
-
885
- render();
File without changes
File without changes