@tangle-network/create-agent-app 0.50.29 → 0.50.31
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.
- package/README.md +91 -78
- package/package.json +1 -1
- package/template-chat/AGENTS.md +14 -1
- package/template-chat/CUSTOMIZE.md +83 -102
- package/template-chat/README.md +83 -41
- package/template-chat/_package.json +18 -3
- package/template-chat/_wrangler.toml +10 -3
- package/template-chat/tailwind.config.mjs +3 -0
- package/template-chat/vite.config.mjs +11 -0
- package/template-chat/web/App.tsx +104 -0
- package/template-chat/web/Conversation.tsx +210 -0
- package/template-chat/web/api.ts +63 -0
- package/template-chat/web/env.d.ts +1 -0
- package/template-chat/web/index.html +12 -0
- package/template-chat/web/main.tsx +7 -0
- package/template-chat/web/styles.css +17 -0
- package/template-chat/web/tsconfig.json +16 -0
- package/template-chat/web/uploads.ts +55 -0
- package/template-chat/public/index.html +0 -255
package/template-chat/README.md
CHANGED
|
@@ -1,61 +1,103 @@
|
|
|
1
1
|
# __PROJECT_NAME__
|
|
2
2
|
|
|
3
|
-
A
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
3
|
+
A React chat workspace scaffolded with `create-agent-app --chat`, built on
|
|
4
|
+
`@tangle-network/agent-app` and its public UI packages. The maintained
|
|
5
|
+
`AgentWorkspaceLayout` owns the rail and History. `ChatComposer`, `ChatMessages`,
|
|
6
|
+
and the interaction cards supply the conversation surface.
|
|
7
|
+
|
|
8
|
+
The existing server vertical supplies better-auth sessions, D1 thread/message
|
|
9
|
+
persistence with typed parts and usage receipts, buffered streaming/replay,
|
|
10
|
+
file uploads, human-in-the-loop asks, personal API keys, and OpenAI-compatible
|
|
11
|
+
access. The agent runs in a real Tangle sandbox. Missing provider credentials
|
|
12
|
+
fail explicitly, not through a demo response.
|
|
11
13
|
|
|
12
14
|
## Layout
|
|
13
15
|
|
|
14
|
-
| Path |
|
|
15
|
-
|
|
16
|
-
| `agent.config.ts` |
|
|
17
|
-
| `
|
|
18
|
-
| `
|
|
19
|
-
| `
|
|
20
|
-
| `
|
|
21
|
-
| `
|
|
22
|
-
| `src/
|
|
23
|
-
| `
|
|
24
|
-
| `migrations/` |
|
|
25
|
-
| `
|
|
26
|
-
| `tests/` | the e2e turn gate this app ships with | extending coverage |
|
|
16
|
+
| Path | Owns |
|
|
17
|
+
|---|---|
|
|
18
|
+
| `agent.config.ts`, `prompts/system.md` | Agent identity, model, harness, and persona |
|
|
19
|
+
| `web/App.tsx` | Real session auth, workspace navigation, and full History |
|
|
20
|
+
| `web/Conversation.tsx` | Conversation assembly and existing chat/replay callbacks |
|
|
21
|
+
| `web/api.ts`, `web/uploads.ts` | Product URL, JSON, transcript, and inline-upload adapters |
|
|
22
|
+
| `web/styles.css`, `tailwind.config.mjs` | Public styles, maintained preset, installed-package class scanning |
|
|
23
|
+
| `vite.config.mjs`, `web/tsconfig.json` | Standalone browser build and browser-only types |
|
|
24
|
+
| `src/chat.ts` | Authentication, store, turn, upload, and interaction factories |
|
|
25
|
+
| `src/gateway.ts`, `src/sandbox.ts`, `src/worker.ts` | Existing API gateway, sandbox lane, and HTTP routes |
|
|
26
|
+
| `src/db/schema.ts`, `migrations/` | Durable schema and migrations |
|
|
27
|
+
| `tests/` | Real server assembly with an explicitly fake sandbox producer |
|
|
27
28
|
|
|
28
29
|
## Get started
|
|
29
30
|
|
|
31
|
+
Use the Node and pnpm versions in `.nvmrc` and `package.json`.
|
|
32
|
+
|
|
30
33
|
```bash
|
|
31
34
|
pnpm install
|
|
32
|
-
pnpm
|
|
35
|
+
pnpm build
|
|
36
|
+
pnpm test
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Read `AGENTS.md` and follow `CUSTOMIZE.md`. Set up the development D1 binding
|
|
40
|
+
and `.dev.vars`, then:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pnpm db:migrate:local
|
|
44
|
+
pnpm dev
|
|
33
45
|
```
|
|
34
46
|
|
|
35
|
-
|
|
47
|
+
Open the Worker origin, normally `http://localhost:8787`. Do not put a second
|
|
48
|
+
Vite origin in front of cookie auth. Wrangler builds and watches the browser
|
|
49
|
+
sources and serves `dist/client`; refresh after a rebuild. `pnpm deploy` uses
|
|
50
|
+
the same build hook. Source TSX is never the deployed asset payload.
|
|
51
|
+
|
|
52
|
+
`pnpm typecheck` checks Worker and browser configurations separately. `pnpm build`
|
|
53
|
+
adds the Vite production build. `pnpm exec wrangler deploy --dry-run` checks the
|
|
54
|
+
Worker bundle without deployment. `pnpm db:migrate` is the remote migration
|
|
55
|
+
command, not part of the local walkthrough.
|
|
56
|
+
|
|
57
|
+
## Workspace behavior
|
|
58
|
+
|
|
59
|
+
New thread is `/`; full History is `/?view=history`. Saved conversations keep
|
|
60
|
+
`/?threadId=...`, including URLs returned by the API gateway. Native links
|
|
61
|
+
support browser back/forward and fresh-process reloads without a second router
|
|
62
|
+
or a client-side store of record. Search and sorting cover all pages of the
|
|
63
|
+
existing thread API, not just the capped rail.
|
|
64
|
+
|
|
65
|
+
Auth uses the existing same-origin better-auth endpoints. A successful sign-out
|
|
66
|
+
reloads the document. An unavailable session endpoint is an error, not a fake
|
|
67
|
+
signed-out or signed-in state. The server remains the only identity authority.
|
|
68
|
+
|
|
69
|
+
A live send uses the public `chatTurnRequestInit` and `streamChatTurn` helpers.
|
|
70
|
+
Reopening a running thread discovers its existing replay handles and refreshes
|
|
71
|
+
durable rows rather than appending replay text twice. A failed or ambiguous
|
|
72
|
+
accepted POST offers reload, not an automatic second model request.
|
|
36
73
|
|
|
37
|
-
|
|
38
|
-
|
|
74
|
+
The template uses `ChatComposer`'s `onSendParts` upload contract. Its upload
|
|
75
|
+
endpoint returns inline/sandbox file parts, **not** the stored attachment
|
|
76
|
+
records expected by `EntryComposer.uploadUrl`/`useComposerAttachments`.
|
|
77
|
+
Do not change that contract just to swap composers. Attachment labels are not
|
|
78
|
+
download links. Model, effort, profile, plan-mode, and unsupported thread-action
|
|
79
|
+
controls remain absent until their real data and callbacks exist.
|
|
39
80
|
|
|
40
|
-
##
|
|
81
|
+
## Proof boundaries
|
|
41
82
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
- `pnpm test` — vitest, including the end-to-end turn gate (fake sandbox
|
|
46
|
-
producer → streamed turn → persisted transcript → replay).
|
|
47
|
-
- `pnpm deploy` — `wrangler deploy`.
|
|
83
|
+
The generated server suite executes real migrations, auth, upload, turn,
|
|
84
|
+
stored messages, and replay with a fake sandbox producer. It is not a live
|
|
85
|
+
model or hosted proof.
|
|
48
86
|
|
|
49
|
-
|
|
87
|
+
The Agent App repository's `pnpm test:generated` additionally installs fresh
|
|
88
|
+
packed packages, builds this standalone frontend, and runs Chromium against a
|
|
89
|
+
local Worker and D1. It exercises signup, thread creation, History, URL reload,
|
|
90
|
+
sign-out, and reopening the same thread after a fresh Worker process and browser
|
|
91
|
+
login. It makes no model-turn requests. See the repository's
|
|
92
|
+
`create-agent-app/proof/README.md` for evidence and prerequisites.
|
|
50
93
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
94
|
+
Before production, complete a real model turn, reload its saved text and usage,
|
|
95
|
+
and check live disconnect/replay on the deployed origin. Those checks are not
|
|
96
|
+
implied by a local build or no-model browser proof.
|
|
54
97
|
|
|
55
98
|
## Artifact index
|
|
56
99
|
|
|
57
|
-
`GET /api/files` lists files under `/home/agent/artifacts` for the signed-in
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
Hidden files and paths outside the artifact root are excluded.
|
|
100
|
+
`GET /api/files` lists files under `/home/agent/artifacts` for the signed-in
|
|
101
|
+
workspace. It returns metadata or `warming`, never provisions a sandbox, and
|
|
102
|
+
has no file-download behavior. Reopening saved bytes requires a product-owned,
|
|
103
|
+
authorized file reader. Preserve the server access checks and storage semantics.
|
|
@@ -9,12 +9,14 @@
|
|
|
9
9
|
"packageManager": "pnpm@11.24.0",
|
|
10
10
|
"scripts": {
|
|
11
11
|
"dev": "wrangler dev",
|
|
12
|
+
"build": "pnpm run typecheck && pnpm run build:web",
|
|
13
|
+
"build:web": "vite build",
|
|
12
14
|
"deploy": "pnpm run peer-check && wrangler deploy",
|
|
13
15
|
"db:migrate": "wrangler d1 migrations apply __PACKAGE_NAME__ --remote",
|
|
14
16
|
"db:migrate:local": "wrangler d1 migrations apply __PACKAGE_NAME__ --local",
|
|
15
17
|
"peer-check": "agent-app-peer-check",
|
|
16
18
|
"signoff": "agent-app-signoff",
|
|
17
|
-
"typecheck": "tsc --noEmit",
|
|
19
|
+
"typecheck": "tsc --noEmit && tsc -p web/tsconfig.json",
|
|
18
20
|
"test": "vitest run",
|
|
19
21
|
"test:watch": "vitest"
|
|
20
22
|
},
|
|
@@ -27,7 +29,13 @@
|
|
|
27
29
|
"better-auth": "^1.7.2",
|
|
28
30
|
"drizzle-orm": "^0.45.2",
|
|
29
31
|
"hono": "^4.13.5",
|
|
30
|
-
"viem": "^2.0.0"
|
|
32
|
+
"viem": "^2.0.0",
|
|
33
|
+
"@tangle-network/brand": "1.9.1",
|
|
34
|
+
"@tangle-network/sandbox-ui": "0.116.8",
|
|
35
|
+
"@tangle-network/ui": "11.12.0",
|
|
36
|
+
"lucide-react": "^1.35.0",
|
|
37
|
+
"react": "^19.2.8",
|
|
38
|
+
"react-dom": "^19.2.8"
|
|
31
39
|
},
|
|
32
40
|
"peerDependencies": {
|
|
33
41
|
"@tangle-network/agent-eval": ">=0.201.0 <0.204.0",
|
|
@@ -43,6 +51,13 @@
|
|
|
43
51
|
"better-sqlite3": "^12.11.1",
|
|
44
52
|
"typescript": "^7.0.2",
|
|
45
53
|
"vitest": "^4.1.11",
|
|
46
|
-
"wrangler": "4.126.0"
|
|
54
|
+
"wrangler": "4.126.0",
|
|
55
|
+
"@types/react": "^19.2.18",
|
|
56
|
+
"@types/react-dom": "19.2.5",
|
|
57
|
+
"@vitejs/plugin-react": "^6.1.1",
|
|
58
|
+
"vite": "^8.2.2",
|
|
59
|
+
"@tailwindcss/postcss": "^4.3.3",
|
|
60
|
+
"tailwindcss": "^4.3.3",
|
|
61
|
+
"postcss": "^8.5.26"
|
|
47
62
|
}
|
|
48
63
|
}
|
|
@@ -3,10 +3,17 @@ main = "src/worker.ts"
|
|
|
3
3
|
compatibility_date = "2025-01-01"
|
|
4
4
|
compatibility_flags = ["nodejs_compat"]
|
|
5
5
|
|
|
6
|
-
#
|
|
7
|
-
#
|
|
6
|
+
# Compile the same browser assets for dev and deploy. Only web sources trigger
|
|
7
|
+
# a frontend rebuild; Worker source keeps Wrangler's ordinary watch behavior.
|
|
8
|
+
[build]
|
|
9
|
+
command = "pnpm run build:web"
|
|
10
|
+
watch_dir = ["web", "vite.config.mjs", "tailwind.config.mjs"]
|
|
11
|
+
|
|
12
|
+
# Same-origin cookie auth. Query-based thread URLs need no SPA fallback.
|
|
13
|
+
# Never let an asset or HTML fallback swallow an API/gateway request.
|
|
8
14
|
[assets]
|
|
9
|
-
directory = "
|
|
15
|
+
directory = "dist/client"
|
|
16
|
+
run_worker_first = ["/api/*", "/v1/*"]
|
|
10
17
|
|
|
11
18
|
# D1 holds everything durable: auth, threads/messages, the turn buffer.
|
|
12
19
|
# Setup: `wrangler d1 create __PACKAGE_NAME__`, paste the database_id, then
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { defineConfig } from 'vite'
|
|
2
|
+
import react from '@vitejs/plugin-react'
|
|
3
|
+
import tailwindcss from '@tailwindcss/postcss'
|
|
4
|
+
|
|
5
|
+
export default defineConfig({
|
|
6
|
+
root: 'web',
|
|
7
|
+
publicDir: false,
|
|
8
|
+
plugins: [react()],
|
|
9
|
+
css: { postcss: { plugins: [tailwindcss()] } },
|
|
10
|
+
build: { outDir: '../dist/client', emptyOutDir: true },
|
|
11
|
+
})
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { useCallback, useEffect, useState, type FormEvent } from 'react'
|
|
2
|
+
import { CirclePlus, History } from 'lucide-react'
|
|
3
|
+
import { AgentWorkspaceLayout } from '@tangle-network/agent-app/workspace-react'
|
|
4
|
+
import { SessionHistoryPanel, useSessionHistory, type FetchSessionPage } from '@tangle-network/agent-app/web-react'
|
|
5
|
+
import type { SessionSort } from '@tangle-network/agent-app/session-shell'
|
|
6
|
+
import { Conversation } from './Conversation'
|
|
7
|
+
import { historyHref, json, listThreads, post, threadHref, type Session, type Thread } from './api'
|
|
8
|
+
|
|
9
|
+
const productName = document.title
|
|
10
|
+
const initialThreadId = new URL(location.href).searchParams.get('threadId')
|
|
11
|
+
const showHistory = !initialThreadId && new URL(location.href).searchParams.get('view') === 'history'
|
|
12
|
+
|
|
13
|
+
function Auth({ onAuthenticated }: { onAuthenticated: () => Promise<void> }) {
|
|
14
|
+
const [signUp, setSignUp] = useState(false)
|
|
15
|
+
const [busy, setBusy] = useState(false)
|
|
16
|
+
const [error, setError] = useState<string | null>(null)
|
|
17
|
+
async function submit(event: FormEvent<HTMLFormElement>) {
|
|
18
|
+
event.preventDefault()
|
|
19
|
+
if (busy) return
|
|
20
|
+
const data = new FormData(event.currentTarget)
|
|
21
|
+
const email = String(data.get('email') ?? '')
|
|
22
|
+
setBusy(true); setError(null)
|
|
23
|
+
try {
|
|
24
|
+
await json(`/api/auth/sign-${signUp ? 'up' : 'in'}/email`, post({
|
|
25
|
+
email, password: String(data.get('password') ?? ''), ...(signUp ? { name: email.split('@')[0] } : {}),
|
|
26
|
+
}))
|
|
27
|
+
await onAuthenticated()
|
|
28
|
+
} catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)) }
|
|
29
|
+
finally { setBusy(false) }
|
|
30
|
+
}
|
|
31
|
+
return <main className="flex min-h-dvh items-center justify-center bg-background p-6">
|
|
32
|
+
<form onSubmit={(event) => void submit(event)} className="w-full max-w-sm space-y-5 rounded-xl border border-border bg-card p-6">
|
|
33
|
+
<p className="text-sm text-muted-foreground">{productName}</p>
|
|
34
|
+
<h1 className="text-2xl font-medium">{signUp ? 'Create your account' : 'Sign in'}</h1>
|
|
35
|
+
<label className="block text-sm">Email<input className="mt-2 w-full rounded-lg border border-input bg-background px-3 py-2" name="email" type="email" autoComplete="email" required disabled={busy} /></label>
|
|
36
|
+
<label className="block text-sm">Password<input className="mt-2 w-full rounded-lg border border-input bg-background px-3 py-2" name="password" type="password" minLength={8} autoComplete={signUp ? 'new-password' : 'current-password'} required disabled={busy} /></label>
|
|
37
|
+
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
|
38
|
+
<button className="w-full rounded-lg bg-primary px-3 py-2 text-primary-foreground disabled:opacity-50" disabled={busy}>{busy ? 'Signing in…' : 'Continue'}</button>
|
|
39
|
+
<button type="button" className="text-sm text-muted-foreground underline" disabled={busy} onClick={() => { setSignUp(!signUp); setError(null) }}>{signUp ? 'Have an account? Sign in' : 'No account? Sign up'}</button>
|
|
40
|
+
</form>
|
|
41
|
+
</main>
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const fetchHistory: FetchSessionPage = async ({ q, sort, signal }) => {
|
|
45
|
+
const threads = await listThreads(signal)
|
|
46
|
+
const items = threads.filter((thread) => (thread.title ?? '').toLocaleLowerCase().includes(q.toLocaleLowerCase()))
|
|
47
|
+
.sort((a, b) => (Date.parse(a.updatedAt ?? '') - Date.parse(b.updatedAt ?? '')) * (sort === 'oldest' ? 1 : -1))
|
|
48
|
+
return { items, nextCursor: null }
|
|
49
|
+
}
|
|
50
|
+
function HistoryPage({ threads }: { threads: Thread[] }) {
|
|
51
|
+
const [query, setQuery] = useState('')
|
|
52
|
+
const [sort, setSort] = useState<SessionSort>('newest')
|
|
53
|
+
const history = useSessionHistory({ fetchPage: fetchHistory, q: query.trim(), sort, initialPage: { items: threads, nextCursor: null } })
|
|
54
|
+
return <div className="h-full min-h-0"><SessionHistoryPanel history={history} hasAnySessions={threads.length > 0}
|
|
55
|
+
query={query} onQueryChange={setQuery} sort={sort} onSortChange={setSort}
|
|
56
|
+
hrefForSession={threadHref} newSessionHref="/" emptyTitle="No conversations yet" /></div>
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function Workspace({ session }: { session: Session }) {
|
|
60
|
+
const [threads, setThreads] = useState<Thread[]>([])
|
|
61
|
+
const [loaded, setLoaded] = useState(false)
|
|
62
|
+
const [activeId, setActiveId] = useState(initialThreadId)
|
|
63
|
+
const [error, setError] = useState<string | null>(null)
|
|
64
|
+
const refreshThreads = useCallback(async () => {
|
|
65
|
+
setThreads(await listThreads()); setLoaded(true)
|
|
66
|
+
}, [])
|
|
67
|
+
useEffect(() => {
|
|
68
|
+
const controller = new AbortController()
|
|
69
|
+
void listThreads(controller.signal).then((rows) => { setThreads(rows); setLoaded(true) }).catch((cause) => {
|
|
70
|
+
if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : String(cause))
|
|
71
|
+
})
|
|
72
|
+
return () => controller.abort()
|
|
73
|
+
}, [])
|
|
74
|
+
async function logout() {
|
|
75
|
+
try { await json('/api/auth/sign-out', post({})); location.reload() }
|
|
76
|
+
catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)) }
|
|
77
|
+
}
|
|
78
|
+
return <AgentWorkspaceLayout
|
|
79
|
+
navItems={[{ id: 'new', label: 'New thread', icon: CirclePlus, href: '/', variant: 'primary' }]}
|
|
80
|
+
sessions={{ icon: History, href: historyHref, hrefForSession: threadHref, sessions: threads,
|
|
81
|
+
totalCount: threads.length, activeSessionId: activeId }}
|
|
82
|
+
activeId={showHistory ? 'history' : activeId ? undefined : 'new'}
|
|
83
|
+
logo={<span className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-primary-foreground" title={productName}>{productName.slice(0, 1)}</span>}
|
|
84
|
+
logoHref="/" user={session.user} settingsHref={null} onLogout={() => void logout()}
|
|
85
|
+
contentClassName="h-dvh min-h-0 overflow-hidden" defaultRailCollapsed={false}>
|
|
86
|
+
{error && <div role="alert" className="p-4 text-sm text-destructive">{error} <button className="underline" onClick={() => location.reload()}>Reload</button></div>}
|
|
87
|
+
{showHistory ? loaded ? <HistoryPage threads={threads} /> : <p role="status" className="p-6">Loading History…</p>
|
|
88
|
+
: <Conversation initialThreadId={initialThreadId} onThread={setActiveId} onChanged={refreshThreads} />}
|
|
89
|
+
</AgentWorkspaceLayout>
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function App() {
|
|
93
|
+
const [session, setSession] = useState<Session | null>()
|
|
94
|
+
const [error, setError] = useState<string | null>(null)
|
|
95
|
+
const loadSession = useCallback(async () => {
|
|
96
|
+
const next = await json<Session | null>('/api/auth/get-session')
|
|
97
|
+
setSession(next?.user ? next : null); setError(null)
|
|
98
|
+
}, [])
|
|
99
|
+
useEffect(() => { void loadSession().catch((cause) => setError(String(cause))) }, [loadSession])
|
|
100
|
+
if (session === undefined) return <main className="p-6">{error
|
|
101
|
+
? <p role="alert">{error} <button className="underline" onClick={() => void loadSession().catch((cause) => setError(String(cause)))}>Retry session</button></p>
|
|
102
|
+
: <p role="status">Loading your workspace…</p>}</main>
|
|
103
|
+
return session ? <Workspace session={session} /> : <Auth onAuthenticated={loadSession} />
|
|
104
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { useEffect, useMemo, useRef, useState } from 'react'
|
|
2
|
+
import {
|
|
3
|
+
ChatComposer, ChatMessages, InteractionPlanCard, InteractionQuestionCard,
|
|
4
|
+
chatTurnRequestInit, createInteractionAnswerSubmitter, persistedPartToInteraction,
|
|
5
|
+
streamChatTurn, useChatInteractions,
|
|
6
|
+
type ChatUiMessage, type ChatStreamCallbacks, type ComposerFilePart,
|
|
7
|
+
} from '@tangle-network/agent-app/web-react'
|
|
8
|
+
import { json, post, threadHref, toUiMessage, type Message, type Thread } from './api'
|
|
9
|
+
import { useInlineUploads } from './uploads'
|
|
10
|
+
|
|
11
|
+
export function Conversation({ initialThreadId, onThread, onChanged }: {
|
|
12
|
+
initialThreadId: string | null
|
|
13
|
+
onThread: (id: string) => void
|
|
14
|
+
onChanged: () => Promise<void>
|
|
15
|
+
}) {
|
|
16
|
+
const [threadId, setThreadId] = useState(initialThreadId)
|
|
17
|
+
const [messages, setMessages] = useState<ChatUiMessage[]>([])
|
|
18
|
+
const [draft, setDraft] = useState('')
|
|
19
|
+
const [busy, setBusy] = useState(false)
|
|
20
|
+
const [opening, setOpening] = useState(Boolean(initialThreadId))
|
|
21
|
+
const [error, setError] = useState<string | null>(null)
|
|
22
|
+
const [needsReload, setNeedsReload] = useState(false)
|
|
23
|
+
const locked = useRef(Boolean(initialThreadId))
|
|
24
|
+
const lifetime = useRef<AbortController | null>(null)
|
|
25
|
+
const snapshot = useRef(0)
|
|
26
|
+
const productName = useRef(document.title)
|
|
27
|
+
const asks = useChatInteractions({ mode: 'durable' })
|
|
28
|
+
const uploads = useInlineUploads()
|
|
29
|
+
const submitAnswer = useMemo(() => createInteractionAnswerSubmitter({
|
|
30
|
+
url: '/api/chat/interactions', body: { threadId },
|
|
31
|
+
}), [threadId])
|
|
32
|
+
|
|
33
|
+
async function refresh(id: string, signal: AbortSignal) {
|
|
34
|
+
const sequence = ++snapshot.current
|
|
35
|
+
const data = await json<{ thread: Thread; messages: Message[] }>(
|
|
36
|
+
`/api/threads/${encodeURIComponent(id)}/messages`, { signal },
|
|
37
|
+
)
|
|
38
|
+
if (signal.aborted || sequence !== snapshot.current) return
|
|
39
|
+
const next = data.messages.map(toUiMessage)
|
|
40
|
+
setMessages(next)
|
|
41
|
+
asks.hydrate(next.flatMap((message) => (message.parts ?? []).flatMap((part) => {
|
|
42
|
+
const interaction = persistedPartToInteraction(part)
|
|
43
|
+
return interaction ? [interaction] : []
|
|
44
|
+
})))
|
|
45
|
+
document.title = `${data.thread.title || 'New thread'} · ${productName.current}`
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const replay = (id: string, fromSeq: number, signal: AbortSignal) => {
|
|
49
|
+
signal.throwIfAborted()
|
|
50
|
+
return fetch(`/api/chat/replay/${encodeURIComponent(id)}?fromSeq=${fromSeq}`, { credentials: 'same-origin', signal })
|
|
51
|
+
}
|
|
52
|
+
const interactionCallbacks: ChatStreamCallbacks = {
|
|
53
|
+
onInteraction: asks.upsert,
|
|
54
|
+
onInteractionCancel: asks.applyCancel,
|
|
55
|
+
onErrorEvent: (message) => setError(message),
|
|
56
|
+
onNotice: (notice) => setError(notice.text),
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
useEffect(() => {
|
|
60
|
+
const controller = new AbortController()
|
|
61
|
+
lifetime.current = controller
|
|
62
|
+
const { signal } = controller
|
|
63
|
+
let poll: ReturnType<typeof setInterval> | undefined
|
|
64
|
+
let refreshing = false
|
|
65
|
+
async function open() {
|
|
66
|
+
if (!initialThreadId) return
|
|
67
|
+
try {
|
|
68
|
+
await refresh(initialThreadId, signal)
|
|
69
|
+
const { running } = await json<{ running: string[] }>(
|
|
70
|
+
`/api/chat/running?threadId=${encodeURIComponent(initialThreadId)}`, { signal },
|
|
71
|
+
)
|
|
72
|
+
if (running.length) {
|
|
73
|
+
setBusy(true)
|
|
74
|
+
// Replay is an event view, not a second transcript. On reload, keep
|
|
75
|
+
// refreshing the durable rows instead of appending replay deltas to
|
|
76
|
+
// a partly persisted assistant message (which would duplicate it).
|
|
77
|
+
poll = setInterval(() => {
|
|
78
|
+
if (refreshing) return
|
|
79
|
+
refreshing = true
|
|
80
|
+
void refresh(initialThreadId, signal).catch((cause) => {
|
|
81
|
+
if (!signal.aborted) setError(String(cause))
|
|
82
|
+
}).finally(() => { refreshing = false })
|
|
83
|
+
}, 1000)
|
|
84
|
+
await Promise.all(running.map((id) => streamChatTurn({
|
|
85
|
+
start: () => replay(id, 0, signal),
|
|
86
|
+
resume: (turn, from) => replay(turn, from, signal),
|
|
87
|
+
callbacks: interactionCallbacks,
|
|
88
|
+
})))
|
|
89
|
+
clearInterval(poll)
|
|
90
|
+
await refresh(initialThreadId, signal)
|
|
91
|
+
}
|
|
92
|
+
} catch (cause) {
|
|
93
|
+
if (!signal.aborted) { setError(cause instanceof Error ? cause.message : String(cause)); setNeedsReload(true) }
|
|
94
|
+
} finally {
|
|
95
|
+
clearInterval(poll)
|
|
96
|
+
if (!signal.aborted) { locked.current = false; setBusy(false); setOpening(false) }
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
void open()
|
|
100
|
+
return () => { clearInterval(poll); controller.abort() }
|
|
101
|
+
// Native links remount the document; this boot runs once for its URL.
|
|
102
|
+
}, [])
|
|
103
|
+
|
|
104
|
+
async function send(content: string, parts: ComposerFilePart[]) {
|
|
105
|
+
if (locked.current || needsReload) return { ok: false as const, error: 'Reload the thread before sending again.' }
|
|
106
|
+
if (uploads.files.some((file) => file.status !== 'ready')) {
|
|
107
|
+
return { ok: false as const, error: 'Finish, retry, or remove the uploads before sending.' }
|
|
108
|
+
}
|
|
109
|
+
const signal = lifetime.current!.signal
|
|
110
|
+
locked.current = true; setBusy(true); setError(null)
|
|
111
|
+
const before = messages
|
|
112
|
+
let accepted = false
|
|
113
|
+
let id = threadId
|
|
114
|
+
let requestStarted = false
|
|
115
|
+
let responseReceived = false
|
|
116
|
+
try {
|
|
117
|
+
if (!id) {
|
|
118
|
+
const { thread } = await json<{ thread: Thread }>('/api/threads', { ...post({ firstMessage: content || 'New thread' }), signal })
|
|
119
|
+
id = thread.id
|
|
120
|
+
setThreadId(id); onThread(id)
|
|
121
|
+
history.replaceState(null, '', threadHref(id))
|
|
122
|
+
}
|
|
123
|
+
const liveId = crypto.randomUUID()
|
|
124
|
+
let live: ChatUiMessage = { id: liveId, role: 'assistant', content: '', toolCalls: [] }
|
|
125
|
+
const user: ChatUiMessage = { id: crypto.randomUUID(), role: 'user', content, parts: parts.map((part) => ({ ...part })) }
|
|
126
|
+
const paint = () => { if (!signal.aborted) setMessages([...before, user, { ...live }]) }
|
|
127
|
+
paint()
|
|
128
|
+
await streamChatTurn({
|
|
129
|
+
start: async () => {
|
|
130
|
+
requestStarted = true
|
|
131
|
+
const response = await fetch('/api/chat', {
|
|
132
|
+
...chatTurnRequestInit({ threadId: id!, content, parts }), credentials: 'same-origin', signal,
|
|
133
|
+
})
|
|
134
|
+
responseReceived = true
|
|
135
|
+
accepted = response.ok
|
|
136
|
+
if (accepted) uploads.clear()
|
|
137
|
+
return response
|
|
138
|
+
},
|
|
139
|
+
resume: (turn, from) => replay(turn, from, signal),
|
|
140
|
+
onResetForResume: () => { live = { id: liveId, role: 'assistant', content: '', toolCalls: [] }; paint() },
|
|
141
|
+
callbacks: {
|
|
142
|
+
...interactionCallbacks,
|
|
143
|
+
onText: (text) => { live.content += text; paint() },
|
|
144
|
+
onReasoning: (text) => { live.reasoning = (live.reasoning ?? '') + text; paint() },
|
|
145
|
+
onToolCall: (call) => {
|
|
146
|
+
live.toolCalls = [...(live.toolCalls ?? []), { id: call.toolCallId ?? crypto.randomUUID(), name: call.toolName, status: 'running', args: call.args }]
|
|
147
|
+
paint()
|
|
148
|
+
},
|
|
149
|
+
onToolResult: (result) => {
|
|
150
|
+
live.toolCalls = live.toolCalls?.map((call) => call.id === result.toolCallId
|
|
151
|
+
? { ...call, status: result.outcome.ok ? 'done' : 'error', result: result.outcome } : call)
|
|
152
|
+
paint()
|
|
153
|
+
},
|
|
154
|
+
onUsage: (usage) => { live.promptTokens = usage.promptTokens; live.completionTokens = usage.completionTokens; paint() },
|
|
155
|
+
},
|
|
156
|
+
})
|
|
157
|
+
await refresh(id, signal)
|
|
158
|
+
await onChanged()
|
|
159
|
+
return { ok: true as const }
|
|
160
|
+
} catch (cause) {
|
|
161
|
+
const message = cause instanceof Error ? cause.message : String(cause)
|
|
162
|
+
if (!signal.aborted) {
|
|
163
|
+
setError(message)
|
|
164
|
+
if (accepted || (requestStarted && !responseReceived)) {
|
|
165
|
+
// An accepted/ambiguous POST must never be retried automatically.
|
|
166
|
+
// The Worker may still be running; reload discovers its replay id.
|
|
167
|
+
setNeedsReload(true)
|
|
168
|
+
setError(`${message}. Reload this thread to check the saved result before sending again.`)
|
|
169
|
+
}
|
|
170
|
+
if (!accepted) setMessages(before)
|
|
171
|
+
}
|
|
172
|
+
// Only a known refusal restores the draft. Ambiguous admission keeps
|
|
173
|
+
// it visible in ChatComposer, but the reload gate prevents a duplicate.
|
|
174
|
+
return accepted ? { ok: true as const } : { ok: false as const, error: message }
|
|
175
|
+
} finally {
|
|
176
|
+
if (!signal.aborted) { locked.current = false; setBusy(false); setOpening(false) }
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const empty = !threadId && messages.length === 0
|
|
181
|
+
return (
|
|
182
|
+
<div className="flex h-full min-h-0 flex-col">
|
|
183
|
+
{!empty && <div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4 pt-4" aria-label="Conversation">
|
|
184
|
+
<div className="mx-auto w-full max-w-[820px]">
|
|
185
|
+
<>{opening && <p role="status" className="text-sm text-muted-foreground">Loading conversation…</p>}</>
|
|
186
|
+
<ChatMessages messages={messages} loading={busy && asks.pending.length === 0} error={error} renderExtras={(message) => {
|
|
187
|
+
const names = (message.parts ?? []).filter((part) => part.type === 'file' || part.type === 'image')
|
|
188
|
+
.map((part) => String(part.filename ?? part.name ?? 'Attachment'))
|
|
189
|
+
return names.length ? <p className="mt-2 text-xs text-muted-foreground">Attachments: {names.join(', ')}</p> : null
|
|
190
|
+
}} onRetry={() => location.reload()} chrome="quiet" renderEmpty={() => busy || opening ? null : <p className="text-muted-foreground">Send a message to continue this thread.</p>} />
|
|
191
|
+
{asks.interactions.map((interaction) => interaction.kind === 'plan'
|
|
192
|
+
? <InteractionPlanCard key={interaction.id} interaction={interaction} canWrite={!needsReload} submitAnswer={submitAnswer} onResolved={asks.markResolved} />
|
|
193
|
+
: <InteractionQuestionCard key={interaction.id} interaction={interaction} canWrite={!needsReload} submitAnswer={submitAnswer} onResolved={asks.markResolved} />)}
|
|
194
|
+
</div>
|
|
195
|
+
</div>}
|
|
196
|
+
<div className={empty ? 'flex flex-1 flex-col items-center justify-center px-5' : 'shrink-0 px-4 pb-4'}>
|
|
197
|
+
<div className="mx-auto w-full max-w-[820px]">
|
|
198
|
+
{empty && <h1 className="mb-7 text-center text-3xl font-medium tracking-tight">What can we work on?</h1>}
|
|
199
|
+
{empty && error && <p role="alert" className="mb-3 text-sm text-destructive">{error}</p>}
|
|
200
|
+
<ChatComposer value={draft} onValueChange={setDraft} onSendParts={send}
|
|
201
|
+
placeholder="Message the agent…" sendLabel="Send" sendVariant="icon" autoFocus={empty}
|
|
202
|
+
disabled={busy || opening || needsReload} canSubmitAttachmentsOnly accept="*/*"
|
|
203
|
+
pendingFiles={uploads.files} onAttach={uploads.add} onRemoveFile={uploads.remove} onRetryFile={uploads.retry}
|
|
204
|
+
onRejectFiles={(rejections) => setError(rejections.map((item) => item.reason).join('; '))} />
|
|
205
|
+
{empty && <p className="mt-4 text-center text-sm text-muted-foreground">Your conversations are saved in History.</p>}
|
|
206
|
+
</div>
|
|
207
|
+
</div>
|
|
208
|
+
</div>
|
|
209
|
+
)
|
|
210
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { ChatMessageRow, ChatThreadRow } from '@tangle-network/agent-app/chat-store'
|
|
2
|
+
import type { ChatUiMessage, ChatToolCallInfo } from '@tangle-network/agent-app/web-react'
|
|
3
|
+
|
|
4
|
+
// JSON dates, not a competing storage schema. These are read-only projections
|
|
5
|
+
// of the public store types; identity and authorization stay in src/chat.ts.
|
|
6
|
+
type Json<T> = T extends Date ? string : T extends Array<infer U> ? Json<U>[]
|
|
7
|
+
: T extends object ? { [K in keyof T]: Json<T[K]> } : T
|
|
8
|
+
export type Thread = Json<ChatThreadRow>
|
|
9
|
+
export type Message = Json<ChatMessageRow>
|
|
10
|
+
export interface Session { user: { id: string; name: string; email: string; image?: string | null } }
|
|
11
|
+
export const threadHref = (id: string) => `/?threadId=${encodeURIComponent(id)}`
|
|
12
|
+
export const historyHref = '/?view=history'
|
|
13
|
+
|
|
14
|
+
export async function json<T>(path: string, init: RequestInit = {}): Promise<T> {
|
|
15
|
+
const response = await fetch(path, { credentials: 'same-origin', ...init })
|
|
16
|
+
const body = await response.json().catch(() => null)
|
|
17
|
+
if (!response.ok) {
|
|
18
|
+
const detail = typeof body?.error === 'string' ? body.error : body?.error?.message ?? body?.message
|
|
19
|
+
throw new Error(detail || `Request failed (${response.status})`)
|
|
20
|
+
}
|
|
21
|
+
return body as T
|
|
22
|
+
}
|
|
23
|
+
export const post = (body: unknown): RequestInit => ({
|
|
24
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
// The existing API supports offset/limit, not server-side search or sorting.
|
|
28
|
+
// Load its pages before filtering History so older matches are not hidden.
|
|
29
|
+
export async function listThreads(signal?: AbortSignal): Promise<Thread[]> {
|
|
30
|
+
const items = new Map<string, Thread>()
|
|
31
|
+
let offset = 0
|
|
32
|
+
for (;;) {
|
|
33
|
+
const page = await json<{ threads: Thread[]; total: number }>(
|
|
34
|
+
`/api/threads?limit=200&offset=${offset}`, { signal },
|
|
35
|
+
)
|
|
36
|
+
for (const thread of page.threads) items.set(thread.id, thread)
|
|
37
|
+
offset += page.threads.length
|
|
38
|
+
if (offset >= page.total) return [...items.values()]
|
|
39
|
+
if (!page.threads.length) throw new Error('Thread list changed while loading. Reload History.')
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function toUiMessage(row: Message): ChatUiMessage {
|
|
44
|
+
const parts = (row.parts ?? []) as Array<Record<string, unknown>>
|
|
45
|
+
const toolCalls: ChatToolCallInfo[] = parts.filter((part) => part.type === 'tool').map((part, index) => {
|
|
46
|
+
const state = part.state as { status?: string; input?: Record<string, unknown>; output?: unknown; error?: unknown } | undefined
|
|
47
|
+
return {
|
|
48
|
+
id: String(part.callID ?? part.id ?? `${row.id}:tool:${index}`),
|
|
49
|
+
name: String(part.tool ?? 'tool'),
|
|
50
|
+
status: state?.status === 'error' || state?.status === 'failed' ? 'error' : state?.status === 'completed' ? 'done' : 'running',
|
|
51
|
+
args: state?.input,
|
|
52
|
+
result: state?.status === 'completed' ? { ok: true, result: state.output }
|
|
53
|
+
: state?.status === 'error' || state?.status === 'failed' ? { ok: false, message: state.error } : undefined,
|
|
54
|
+
}
|
|
55
|
+
})
|
|
56
|
+
return {
|
|
57
|
+
id: row.id, role: row.role === 'tool' ? 'assistant' : row.role,
|
|
58
|
+
content: row.content, parts, toolCalls,
|
|
59
|
+
reasoning: parts.filter((part) => part.type === 'reasoning').map((part) => String(part.text ?? '')).join(''),
|
|
60
|
+
modelUsed: row.model ?? undefined,
|
|
61
|
+
promptTokens: row.inputTokens ?? undefined, completionTokens: row.outputTokens ?? undefined,
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
declare module '*.css'
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
|
+
<title>__PROJECT_NAME__</title>
|
|
7
|
+
</head>
|
|
8
|
+
<body>
|
|
9
|
+
<div id="root"></div>
|
|
10
|
+
<script type="module" src="/main.tsx"></script>
|
|
11
|
+
</body>
|
|
12
|
+
</html>
|