codeblog-app 2.1.1 → 2.1.3
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/drizzle/0000_init.sql +34 -0
- package/drizzle/meta/_journal.json +13 -0
- package/drizzle.config.ts +10 -0
- package/package.json +71 -8
- package/src/ai/__tests__/chat.test.ts +110 -0
- package/src/ai/__tests__/provider.test.ts +184 -0
- package/src/ai/__tests__/tools.test.ts +90 -0
- package/src/ai/chat.ts +169 -0
- package/src/ai/configure.ts +134 -0
- package/src/ai/provider.ts +238 -0
- package/src/ai/tools.ts +336 -0
- package/src/auth/index.ts +47 -0
- package/src/auth/oauth.ts +94 -0
- package/src/cli/__tests__/commands.test.ts +225 -0
- package/src/cli/cmd/agent.ts +97 -0
- package/src/cli/cmd/chat.ts +190 -0
- package/src/cli/cmd/comment.ts +67 -0
- package/src/cli/cmd/config.ts +153 -0
- package/src/cli/cmd/feed.ts +53 -0
- package/src/cli/cmd/forum.ts +106 -0
- package/src/cli/cmd/login.ts +45 -0
- package/src/cli/cmd/logout.ts +12 -0
- package/src/cli/cmd/me.ts +188 -0
- package/src/cli/cmd/post.ts +25 -0
- package/src/cli/cmd/publish.ts +64 -0
- package/src/cli/cmd/scan.ts +78 -0
- package/src/cli/cmd/search.ts +35 -0
- package/src/cli/cmd/setup.ts +273 -0
- package/src/cli/cmd/tui.ts +20 -0
- package/src/cli/cmd/uninstall.ts +156 -0
- package/src/cli/cmd/update.ts +78 -0
- package/src/cli/cmd/vote.ts +50 -0
- package/src/cli/cmd/whoami.ts +18 -0
- package/src/cli/mcp-print.ts +6 -0
- package/src/cli/ui.ts +195 -0
- package/src/config/index.ts +54 -0
- package/src/flag/index.ts +23 -0
- package/src/global/index.ts +38 -0
- package/src/id/index.ts +20 -0
- package/src/index.ts +200 -0
- package/src/mcp/__tests__/client.test.ts +149 -0
- package/src/mcp/__tests__/e2e.ts +327 -0
- package/src/mcp/__tests__/integration.ts +148 -0
- package/src/mcp/client.ts +148 -0
- package/src/server/index.ts +48 -0
- package/src/storage/chat.ts +71 -0
- package/src/storage/db.ts +85 -0
- package/src/storage/schema.sql.ts +39 -0
- package/src/storage/schema.ts +1 -0
- package/src/tui/app.tsx +179 -0
- package/src/tui/commands.ts +187 -0
- package/src/tui/context/exit.tsx +15 -0
- package/src/tui/context/helper.tsx +25 -0
- package/src/tui/context/route.tsx +24 -0
- package/src/tui/context/theme.tsx +470 -0
- package/src/tui/routes/home.tsx +508 -0
- package/src/tui/routes/model.tsx +207 -0
- package/src/tui/routes/notifications.tsx +87 -0
- package/src/tui/routes/post.tsx +102 -0
- package/src/tui/routes/search.tsx +105 -0
- package/src/tui/routes/setup.tsx +255 -0
- package/src/tui/routes/trending.tsx +107 -0
- package/src/util/__tests__/context.test.ts +31 -0
- package/src/util/__tests__/lazy.test.ts +37 -0
- package/src/util/context.ts +23 -0
- package/src/util/error.ts +46 -0
- package/src/util/lazy.ts +18 -0
- package/src/util/log.ts +142 -0
- package/tsconfig.json +11 -0
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
|
|
2
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
|
|
3
|
+
import { resolve, dirname } from "path"
|
|
4
|
+
import { Log } from "../util/log"
|
|
5
|
+
|
|
6
|
+
const log = Log.create({ service: "mcp" })
|
|
7
|
+
|
|
8
|
+
const CONNECTION_TIMEOUT_MS = 30_000
|
|
9
|
+
|
|
10
|
+
let client: Client | null = null
|
|
11
|
+
let transport: StdioClientTransport | null = null
|
|
12
|
+
let connecting: Promise<Client> | null = null
|
|
13
|
+
|
|
14
|
+
function getMcpBinaryPath(): string {
|
|
15
|
+
try {
|
|
16
|
+
const resolved = require.resolve("codeblog-mcp/dist/index.js")
|
|
17
|
+
return resolved
|
|
18
|
+
} catch {
|
|
19
|
+
return resolve(dirname(new URL(import.meta.url).pathname), "../../node_modules/codeblog-mcp/dist/index.js")
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
|
|
24
|
+
return new Promise<T>((resolve, reject) => {
|
|
25
|
+
const timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)
|
|
26
|
+
promise.then(
|
|
27
|
+
(v) => { clearTimeout(timer); resolve(v) },
|
|
28
|
+
(e) => { clearTimeout(timer); reject(e) },
|
|
29
|
+
)
|
|
30
|
+
})
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function connect(): Promise<Client> {
|
|
34
|
+
if (client) return client
|
|
35
|
+
|
|
36
|
+
// If another caller is already connecting, reuse that promise
|
|
37
|
+
if (connecting) return connecting
|
|
38
|
+
|
|
39
|
+
connecting = (async (): Promise<Client> => {
|
|
40
|
+
const mcpPath = getMcpBinaryPath()
|
|
41
|
+
log.debug("connecting", { path: mcpPath })
|
|
42
|
+
|
|
43
|
+
const env: Record<string, string> = {}
|
|
44
|
+
for (const [k, v] of Object.entries(process.env)) {
|
|
45
|
+
if (v !== undefined) env[k] = v
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const t = new StdioClientTransport({
|
|
49
|
+
command: "node",
|
|
50
|
+
args: [mcpPath],
|
|
51
|
+
env,
|
|
52
|
+
stderr: "pipe",
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
const c = new Client({ name: "codeblog-cli", version: "2.0.0" })
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
await withTimeout(c.connect(t), CONNECTION_TIMEOUT_MS, "MCP connection")
|
|
59
|
+
} catch (err) {
|
|
60
|
+
// Clean up on failure so next call can retry
|
|
61
|
+
await t.close().catch(() => {})
|
|
62
|
+
throw err
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
log.debug("connected", {
|
|
66
|
+
server: c.getServerVersion()?.name,
|
|
67
|
+
version: c.getServerVersion()?.version,
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
// Only assign to module-level vars after successful connection
|
|
71
|
+
transport = t
|
|
72
|
+
client = c
|
|
73
|
+
return c
|
|
74
|
+
})()
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
return await connecting
|
|
78
|
+
} catch (err) {
|
|
79
|
+
// Reset connecting so next call can retry
|
|
80
|
+
connecting = null
|
|
81
|
+
throw err
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export namespace McpBridge {
|
|
86
|
+
/**
|
|
87
|
+
* Call an MCP tool by name with arguments.
|
|
88
|
+
* Returns the text content from the tool result.
|
|
89
|
+
*/
|
|
90
|
+
export async function callTool(
|
|
91
|
+
name: string,
|
|
92
|
+
args: Record<string, unknown> = {},
|
|
93
|
+
): Promise<string> {
|
|
94
|
+
const c = await connect()
|
|
95
|
+
const result = await c.callTool({ name, arguments: args })
|
|
96
|
+
|
|
97
|
+
if (result.isError) {
|
|
98
|
+
const text = extractText(result)
|
|
99
|
+
throw new Error(text || `MCP tool "${name}" returned an error`)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return extractText(result)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Call an MCP tool and parse the result as JSON.
|
|
107
|
+
*/
|
|
108
|
+
export async function callToolJSON<T = unknown>(
|
|
109
|
+
name: string,
|
|
110
|
+
args: Record<string, unknown> = {},
|
|
111
|
+
): Promise<T> {
|
|
112
|
+
const text = await callTool(name, args)
|
|
113
|
+
try {
|
|
114
|
+
return JSON.parse(text) as T
|
|
115
|
+
} catch {
|
|
116
|
+
return text as unknown as T
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* List all available MCP tools.
|
|
122
|
+
*/
|
|
123
|
+
export async function listTools() {
|
|
124
|
+
const c = await connect()
|
|
125
|
+
return c.listTools()
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Disconnect the MCP client and kill the subprocess.
|
|
130
|
+
*/
|
|
131
|
+
export async function disconnect(): Promise<void> {
|
|
132
|
+
connecting = null
|
|
133
|
+
if (transport) {
|
|
134
|
+
await transport.close().catch(() => {})
|
|
135
|
+
transport = null
|
|
136
|
+
}
|
|
137
|
+
client = null
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function extractText(result: unknown): string {
|
|
142
|
+
const r = result as { content?: Array<{ type: string; text?: string }> }
|
|
143
|
+
if (!r.content || !Array.isArray(r.content)) return ""
|
|
144
|
+
return r.content
|
|
145
|
+
.filter((c) => c.type === "text" && c.text)
|
|
146
|
+
.map((c) => c.text!)
|
|
147
|
+
.join("\n")
|
|
148
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { Hono } from "hono"
|
|
2
|
+
import { Log } from "../util/log"
|
|
3
|
+
|
|
4
|
+
const log = Log.create({ service: "server" })
|
|
5
|
+
|
|
6
|
+
export namespace Server {
|
|
7
|
+
let instance: ReturnType<typeof Bun.serve> | null = null
|
|
8
|
+
|
|
9
|
+
export function start(app: Hono, port: number): ReturnType<typeof Bun.serve> {
|
|
10
|
+
if (instance) {
|
|
11
|
+
log.warn("server already running, stopping previous instance")
|
|
12
|
+
instance.stop()
|
|
13
|
+
}
|
|
14
|
+
instance = Bun.serve({ port, fetch: app.fetch })
|
|
15
|
+
log.info("server started", { port })
|
|
16
|
+
return instance
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function stop() {
|
|
20
|
+
if (instance) {
|
|
21
|
+
instance.stop()
|
|
22
|
+
instance = null
|
|
23
|
+
log.info("server stopped")
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function running(): boolean {
|
|
28
|
+
return instance !== null
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createCallbackServer(onCallback: (params: URLSearchParams) => Promise<string>): {
|
|
32
|
+
app: Hono
|
|
33
|
+
port: number
|
|
34
|
+
} {
|
|
35
|
+
const port = 19823
|
|
36
|
+
const app = new Hono()
|
|
37
|
+
|
|
38
|
+
app.get("/callback", async (c) => {
|
|
39
|
+
const params = new URL(c.req.url).searchParams
|
|
40
|
+
const html = await onCallback(params)
|
|
41
|
+
return c.html(html)
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
app.get("/health", (c) => c.json({ ok: true }))
|
|
45
|
+
|
|
46
|
+
return { app, port }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { Database } from "./db"
|
|
2
|
+
|
|
3
|
+
export interface ChatMsg {
|
|
4
|
+
role: "user" | "assistant" | "tool"
|
|
5
|
+
content: string
|
|
6
|
+
toolName?: string
|
|
7
|
+
toolStatus?: "running" | "done" | "error"
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function raw() {
|
|
11
|
+
// Access the underlying bun:sqlite instance from Drizzle
|
|
12
|
+
// Tables are already created in db.ts via CREATE TABLE IF NOT EXISTS
|
|
13
|
+
return (Database.Client() as any).$client as import("bun:sqlite").Database
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export namespace ChatHistory {
|
|
17
|
+
export function create(id: string, title?: string) {
|
|
18
|
+
raw().run(
|
|
19
|
+
"INSERT OR REPLACE INTO chat_sessions (id, title, time_created, time_updated) VALUES (?, ?, ?, ?)",
|
|
20
|
+
[id, title || null, Date.now(), Date.now()],
|
|
21
|
+
)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function save(sessionId: string, messages: ChatMsg[]) {
|
|
25
|
+
const d = raw()
|
|
26
|
+
d.run("DELETE FROM chat_messages WHERE session_id = ?", [sessionId])
|
|
27
|
+
const stmt = d.prepare(
|
|
28
|
+
"INSERT INTO chat_messages (session_id, role, content, tool_name, tool_status, time_created) VALUES (?, ?, ?, ?, ?, ?)",
|
|
29
|
+
)
|
|
30
|
+
for (const m of messages) {
|
|
31
|
+
stmt.run(sessionId, m.role, m.content, m.toolName || null, m.toolStatus || null, Date.now())
|
|
32
|
+
}
|
|
33
|
+
// Update session title from first user message
|
|
34
|
+
const first = messages.find((m) => m.role === "user")
|
|
35
|
+
if (first) {
|
|
36
|
+
const title = first.content.slice(0, 80)
|
|
37
|
+
d.run("UPDATE chat_sessions SET title = ?, time_updated = ? WHERE id = ?", [title, Date.now(), sessionId])
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function load(sessionId: string): ChatMsg[] {
|
|
42
|
+
const rows = raw()
|
|
43
|
+
.query("SELECT role, content, tool_name, tool_status FROM chat_messages WHERE session_id = ? ORDER BY id ASC")
|
|
44
|
+
.all(sessionId) as any[]
|
|
45
|
+
return rows.map((r) => ({
|
|
46
|
+
role: r.role,
|
|
47
|
+
content: r.content,
|
|
48
|
+
...(r.tool_name ? { toolName: r.tool_name } : {}),
|
|
49
|
+
...(r.tool_status ? { toolStatus: r.tool_status } : {}),
|
|
50
|
+
}))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function list(limit = 20): Array<{ id: string; title: string | null; time: number; count: number }> {
|
|
54
|
+
const rows = raw()
|
|
55
|
+
.query(
|
|
56
|
+
`SELECT s.id, s.title, s.time_updated as time,
|
|
57
|
+
(SELECT COUNT(*) FROM chat_messages WHERE session_id = s.id) as count
|
|
58
|
+
FROM chat_sessions s
|
|
59
|
+
ORDER BY s.time_updated DESC
|
|
60
|
+
LIMIT ?`,
|
|
61
|
+
)
|
|
62
|
+
.all(limit) as any[]
|
|
63
|
+
return rows.map((r) => ({ id: r.id, title: r.title, time: r.time, count: r.count }))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function remove(sessionId: string) {
|
|
67
|
+
const d = raw()
|
|
68
|
+
d.run("DELETE FROM chat_messages WHERE session_id = ?", [sessionId])
|
|
69
|
+
d.run("DELETE FROM chat_sessions WHERE id = ?", [sessionId])
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { Database as BunDatabase } from "bun:sqlite"
|
|
2
|
+
import { drizzle } from "drizzle-orm/bun-sqlite"
|
|
3
|
+
import { Context } from "../util/context"
|
|
4
|
+
import { lazy } from "../util/lazy"
|
|
5
|
+
import { Global } from "../global"
|
|
6
|
+
import { Log } from "../util/log"
|
|
7
|
+
import path from "path"
|
|
8
|
+
import * as schema from "./schema"
|
|
9
|
+
|
|
10
|
+
const log = Log.create({ service: "db" })
|
|
11
|
+
|
|
12
|
+
export namespace Database {
|
|
13
|
+
type Schema = typeof schema
|
|
14
|
+
|
|
15
|
+
export const Client = lazy(() => {
|
|
16
|
+
const dbpath = path.join(Global.Path.data, "codeblog.db")
|
|
17
|
+
log.info("opening database", { path: dbpath })
|
|
18
|
+
|
|
19
|
+
const sqlite = new BunDatabase(dbpath, { create: true })
|
|
20
|
+
|
|
21
|
+
sqlite.run("PRAGMA journal_mode = WAL")
|
|
22
|
+
sqlite.run("PRAGMA synchronous = NORMAL")
|
|
23
|
+
sqlite.run("PRAGMA busy_timeout = 5000")
|
|
24
|
+
sqlite.run("PRAGMA cache_size = -64000")
|
|
25
|
+
sqlite.run("PRAGMA foreign_keys = ON")
|
|
26
|
+
|
|
27
|
+
// Auto-create tables
|
|
28
|
+
sqlite.run(`CREATE TABLE IF NOT EXISTS published_sessions (
|
|
29
|
+
id TEXT PRIMARY KEY,
|
|
30
|
+
session_id TEXT NOT NULL,
|
|
31
|
+
source TEXT NOT NULL,
|
|
32
|
+
post_id TEXT,
|
|
33
|
+
file_path TEXT NOT NULL,
|
|
34
|
+
time_created INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
|
|
35
|
+
time_updated INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
|
|
36
|
+
)`)
|
|
37
|
+
|
|
38
|
+
sqlite.run(`CREATE TABLE IF NOT EXISTS cached_posts (
|
|
39
|
+
id TEXT PRIMARY KEY,
|
|
40
|
+
title TEXT NOT NULL,
|
|
41
|
+
content TEXT NOT NULL,
|
|
42
|
+
author_name TEXT,
|
|
43
|
+
votes INTEGER DEFAULT 0,
|
|
44
|
+
comments_count INTEGER DEFAULT 0,
|
|
45
|
+
tags TEXT,
|
|
46
|
+
time_created INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
|
|
47
|
+
time_updated INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
|
|
48
|
+
)`)
|
|
49
|
+
|
|
50
|
+
sqlite.run(`CREATE TABLE IF NOT EXISTS chat_sessions (
|
|
51
|
+
id TEXT PRIMARY KEY,
|
|
52
|
+
title TEXT,
|
|
53
|
+
time_created INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
|
|
54
|
+
time_updated INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
|
|
55
|
+
)`)
|
|
56
|
+
|
|
57
|
+
sqlite.run(`CREATE TABLE IF NOT EXISTS chat_messages (
|
|
58
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
59
|
+
session_id TEXT NOT NULL REFERENCES chat_sessions(id) ON DELETE CASCADE,
|
|
60
|
+
role TEXT NOT NULL,
|
|
61
|
+
content TEXT NOT NULL,
|
|
62
|
+
tool_name TEXT,
|
|
63
|
+
tool_status TEXT,
|
|
64
|
+
time_created INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
|
|
65
|
+
)`)
|
|
66
|
+
|
|
67
|
+
sqlite.run(`CREATE TABLE IF NOT EXISTS notifications_cache (
|
|
68
|
+
id TEXT PRIMARY KEY,
|
|
69
|
+
type TEXT NOT NULL,
|
|
70
|
+
message TEXT NOT NULL,
|
|
71
|
+
read INTEGER DEFAULT 0,
|
|
72
|
+
post_id TEXT,
|
|
73
|
+
time_created INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
|
|
74
|
+
time_updated INTEGER NOT NULL DEFAULT (unixepoch() * 1000)
|
|
75
|
+
)`)
|
|
76
|
+
|
|
77
|
+
return drizzle({ client: sqlite, schema })
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
const ctx = Context.create<{ tx: any; effects: (() => void | Promise<void>)[] }>("database")
|
|
81
|
+
|
|
82
|
+
export function use<T>(callback: (db: ReturnType<typeof Client>) => T): T {
|
|
83
|
+
return callback(Client())
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { integer, text, sqliteTable } from "drizzle-orm/sqlite-core"
|
|
2
|
+
|
|
3
|
+
export const Timestamps = {
|
|
4
|
+
time_created: integer()
|
|
5
|
+
.notNull()
|
|
6
|
+
.$default(() => Date.now()),
|
|
7
|
+
time_updated: integer()
|
|
8
|
+
.notNull()
|
|
9
|
+
.$onUpdate(() => Date.now()),
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const published_sessions = sqliteTable("published_sessions", {
|
|
13
|
+
id: text().primaryKey(),
|
|
14
|
+
session_id: text().notNull(),
|
|
15
|
+
source: text().notNull(),
|
|
16
|
+
post_id: text(),
|
|
17
|
+
file_path: text().notNull(),
|
|
18
|
+
...Timestamps,
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
export const cached_posts = sqliteTable("cached_posts", {
|
|
22
|
+
id: text().primaryKey(),
|
|
23
|
+
title: text().notNull(),
|
|
24
|
+
content: text().notNull(),
|
|
25
|
+
author_name: text(),
|
|
26
|
+
votes: integer().default(0),
|
|
27
|
+
comments_count: integer().default(0),
|
|
28
|
+
tags: text(),
|
|
29
|
+
...Timestamps,
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
export const notifications_cache = sqliteTable("notifications_cache", {
|
|
33
|
+
id: text().primaryKey(),
|
|
34
|
+
type: text().notNull(),
|
|
35
|
+
message: text().notNull(),
|
|
36
|
+
read: integer().default(0),
|
|
37
|
+
post_id: text(),
|
|
38
|
+
...Timestamps,
|
|
39
|
+
})
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { published_sessions, cached_posts, notifications_cache } from "./schema.sql"
|
package/src/tui/app.tsx
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { render, useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/solid"
|
|
2
|
+
import { Switch, Match, onMount, createSignal, Show } from "solid-js"
|
|
3
|
+
import { RouteProvider, useRoute } from "./context/route"
|
|
4
|
+
import { ExitProvider, useExit } from "./context/exit"
|
|
5
|
+
import { ThemeProvider, useTheme } from "./context/theme"
|
|
6
|
+
import { Home } from "./routes/home"
|
|
7
|
+
import { ThemePicker } from "./routes/setup"
|
|
8
|
+
import { ModelPicker } from "./routes/model"
|
|
9
|
+
import { Post } from "./routes/post"
|
|
10
|
+
import { Search } from "./routes/search"
|
|
11
|
+
import { Trending } from "./routes/trending"
|
|
12
|
+
import { Notifications } from "./routes/notifications"
|
|
13
|
+
|
|
14
|
+
import pkg from "../../package.json"
|
|
15
|
+
const VERSION = pkg.version
|
|
16
|
+
|
|
17
|
+
export function tui(input: { onExit?: () => Promise<void> }) {
|
|
18
|
+
return new Promise<void>(async (resolve) => {
|
|
19
|
+
render(
|
|
20
|
+
() => (
|
|
21
|
+
<ExitProvider onExit={async () => { await input.onExit?.(); resolve() }}>
|
|
22
|
+
<ThemeProvider>
|
|
23
|
+
<RouteProvider>
|
|
24
|
+
<App />
|
|
25
|
+
</RouteProvider>
|
|
26
|
+
</ThemeProvider>
|
|
27
|
+
</ExitProvider>
|
|
28
|
+
),
|
|
29
|
+
{
|
|
30
|
+
targetFps: 30,
|
|
31
|
+
exitOnCtrlC: false,
|
|
32
|
+
autoFocus: false,
|
|
33
|
+
openConsoleOnError: false,
|
|
34
|
+
},
|
|
35
|
+
)
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function App() {
|
|
40
|
+
const route = useRoute()
|
|
41
|
+
const exit = useExit()
|
|
42
|
+
const theme = useTheme()
|
|
43
|
+
const dimensions = useTerminalDimensions()
|
|
44
|
+
const renderer = useRenderer()
|
|
45
|
+
const [loggedIn, setLoggedIn] = createSignal(false)
|
|
46
|
+
const [username, setUsername] = createSignal("")
|
|
47
|
+
const [hasAI, setHasAI] = createSignal(false)
|
|
48
|
+
const [aiProvider, setAiProvider] = createSignal("")
|
|
49
|
+
const [modelName, setModelName] = createSignal("")
|
|
50
|
+
|
|
51
|
+
async function refreshAI() {
|
|
52
|
+
try {
|
|
53
|
+
const { AIProvider } = await import("../ai/provider")
|
|
54
|
+
const has = await AIProvider.hasAnyKey()
|
|
55
|
+
setHasAI(has)
|
|
56
|
+
if (has) {
|
|
57
|
+
const { Config } = await import("../config")
|
|
58
|
+
const cfg = await Config.load()
|
|
59
|
+
const model = cfg.model || AIProvider.DEFAULT_MODEL
|
|
60
|
+
setModelName(model)
|
|
61
|
+
const info = AIProvider.BUILTIN_MODELS[model]
|
|
62
|
+
setAiProvider(info?.providerID || model.split("/")[0] || "ai")
|
|
63
|
+
}
|
|
64
|
+
} catch {}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
onMount(async () => {
|
|
68
|
+
renderer.setTerminalTitle("CodeBlog")
|
|
69
|
+
|
|
70
|
+
// Check auth status
|
|
71
|
+
try {
|
|
72
|
+
const { Auth } = await import("../auth")
|
|
73
|
+
const authenticated = await Auth.authenticated()
|
|
74
|
+
setLoggedIn(authenticated)
|
|
75
|
+
if (authenticated) {
|
|
76
|
+
const token = await Auth.get()
|
|
77
|
+
if (token?.username) setUsername(token.username)
|
|
78
|
+
}
|
|
79
|
+
} catch {}
|
|
80
|
+
|
|
81
|
+
await refreshAI()
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
useKeyboard((evt) => {
|
|
85
|
+
if (evt.ctrl && evt.name === "c") {
|
|
86
|
+
exit()
|
|
87
|
+
evt.preventDefault()
|
|
88
|
+
return
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Back navigation from sub-pages
|
|
92
|
+
if (evt.name === "escape" && route.data.type !== "home") {
|
|
93
|
+
route.navigate({ type: "home" })
|
|
94
|
+
evt.preventDefault()
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
return (
|
|
100
|
+
<box flexDirection="column" width={dimensions().width} height={dimensions().height}>
|
|
101
|
+
<Switch>
|
|
102
|
+
<Match when={route.data.type === "home"}>
|
|
103
|
+
<Home
|
|
104
|
+
loggedIn={loggedIn()}
|
|
105
|
+
username={username()}
|
|
106
|
+
hasAI={hasAI()}
|
|
107
|
+
aiProvider={aiProvider()}
|
|
108
|
+
modelName={modelName()}
|
|
109
|
+
onLogin={async () => {
|
|
110
|
+
try {
|
|
111
|
+
const { OAuth } = await import("../auth/oauth")
|
|
112
|
+
await OAuth.login()
|
|
113
|
+
const { Auth } = await import("../auth")
|
|
114
|
+
setLoggedIn(true)
|
|
115
|
+
const token = await Auth.get()
|
|
116
|
+
if (token?.username) setUsername(token.username)
|
|
117
|
+
} catch {}
|
|
118
|
+
}}
|
|
119
|
+
onLogout={() => { setLoggedIn(false); setUsername("") }}
|
|
120
|
+
onAIConfigured={refreshAI}
|
|
121
|
+
/>
|
|
122
|
+
</Match>
|
|
123
|
+
<Match when={route.data.type === "theme"}>
|
|
124
|
+
<ThemePicker onDone={() => route.navigate({ type: "home" })} />
|
|
125
|
+
</Match>
|
|
126
|
+
<Match when={route.data.type === "model"}>
|
|
127
|
+
<ModelPicker onDone={async (model) => {
|
|
128
|
+
if (model) setModelName(model)
|
|
129
|
+
await refreshAI()
|
|
130
|
+
route.navigate({ type: "home" })
|
|
131
|
+
}} />
|
|
132
|
+
</Match>
|
|
133
|
+
<Match when={route.data.type === "post"}>
|
|
134
|
+
<Post />
|
|
135
|
+
</Match>
|
|
136
|
+
<Match when={route.data.type === "search"}>
|
|
137
|
+
<Search />
|
|
138
|
+
</Match>
|
|
139
|
+
<Match when={route.data.type === "trending"}>
|
|
140
|
+
<Trending />
|
|
141
|
+
</Match>
|
|
142
|
+
<Match when={route.data.type === "notifications"}>
|
|
143
|
+
<Notifications />
|
|
144
|
+
</Match>
|
|
145
|
+
</Switch>
|
|
146
|
+
|
|
147
|
+
{/* Status bar — like OpenCode */}
|
|
148
|
+
<box paddingLeft={2} paddingRight={2} flexShrink={0} flexDirection="row" gap={2}>
|
|
149
|
+
<text fg={theme.colors.textMuted}>{process.cwd()}</text>
|
|
150
|
+
<box flexGrow={1} />
|
|
151
|
+
<Show when={hasAI()}>
|
|
152
|
+
<text fg={theme.colors.text}>
|
|
153
|
+
<span style={{ fg: theme.colors.success }}>● </span>
|
|
154
|
+
{modelName()}
|
|
155
|
+
</text>
|
|
156
|
+
</Show>
|
|
157
|
+
<Show when={!hasAI()}>
|
|
158
|
+
<text fg={theme.colors.text}>
|
|
159
|
+
<span style={{ fg: theme.colors.error }}>○ </span>
|
|
160
|
+
no AI <span style={{ fg: theme.colors.textMuted }}>/ai</span>
|
|
161
|
+
</text>
|
|
162
|
+
</Show>
|
|
163
|
+
<Show when={loggedIn()}>
|
|
164
|
+
<text fg={theme.colors.text}>
|
|
165
|
+
<span style={{ fg: theme.colors.success }}>● </span>
|
|
166
|
+
{username() || "logged in"}
|
|
167
|
+
</text>
|
|
168
|
+
</Show>
|
|
169
|
+
<Show when={!loggedIn()}>
|
|
170
|
+
<text fg={theme.colors.text}>
|
|
171
|
+
<span style={{ fg: theme.colors.error }}>○ </span>
|
|
172
|
+
<span style={{ fg: theme.colors.textMuted }}>/login</span>
|
|
173
|
+
</text>
|
|
174
|
+
</Show>
|
|
175
|
+
<text fg={theme.colors.textMuted}>v{VERSION}</text>
|
|
176
|
+
</box>
|
|
177
|
+
</box>
|
|
178
|
+
)
|
|
179
|
+
}
|