mirror of
https://github.com/cline/cline.git
synced 2026-09-04 20:02:30 +08:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 166b2e9fd4 |
@@ -1,17 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## [3.86.2]
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix `@` file mentions and workspace file search on VS Code 1.122+ by resolving the new bundled `@vscode/ripgrep-universal` per-platform binary layout before falling back to legacy ripgrep paths.
|
||||
|
||||
## [3.86.1]
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix `@` file mentions failing to find files in some environments (notably VS Code Remote SSH, and after certain VS Code updates) by keeping the file-search fallback alive when the workspace index or bundled ripgrep binary is unavailable.
|
||||
|
||||
## [3.86.0]
|
||||
|
||||
### Added
|
||||
|
||||
@@ -19,7 +19,7 @@ English | <a href="https://github.com/cline/cline/blob/main/locales/es/README.md
|
||||
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank"><strong>Feature Requests</strong></a>
|
||||
</td>
|
||||
<td align="center">
|
||||
<a href="https://docs.cline.bot/getting-started/installing-cline" target="_blank"><strong>Getting Started</strong></a>
|
||||
<a href="https://docs.cline.bot/getting-started/for-new-coders" target="_blank"><strong>Getting Started</strong></a>
|
||||
</td>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "claude-dev",
|
||||
"version": "3.86.2",
|
||||
"version": "3.86.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "claude-dev",
|
||||
"version": "3.86.2",
|
||||
"version": "3.86.0",
|
||||
"license": "Apache-2.0",
|
||||
"workspaces": [
|
||||
"."
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "claude-dev",
|
||||
"displayName": "Cline",
|
||||
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
|
||||
"version": "3.86.2",
|
||||
"version": "3.86.0",
|
||||
"icon": "assets/icons/icon.png",
|
||||
"workspaces": [
|
||||
"."
|
||||
|
||||
@@ -673,13 +673,7 @@ async function getBinaryLocation(name: string): Promise<string> {
|
||||
return (await fileExistsAtPath(fullPath)) ? fullPath : undefined
|
||||
}
|
||||
|
||||
// VS Code 1.122.0 (microsoft/vscode#317978 et al.) migrated from @vscode/ripgrep
|
||||
// to @vscode/ripgrep-universal, which ships per-platform/arch subdirectories.
|
||||
// Probe the new layout first; fall back to the legacy paths for ≤1.121.x.
|
||||
const platformArch = `${process.platform}-${process.arch}`
|
||||
const binPath =
|
||||
(await checkPath(`node_modules/@vscode/ripgrep-universal/bin/${platformArch}/`)) ||
|
||||
(await checkPath(`node_modules.asar.unpacked/@vscode/ripgrep-universal/bin/${platformArch}/`)) ||
|
||||
(await checkPath("node_modules/@vscode/ripgrep/bin/")) ||
|
||||
(await checkPath("node_modules/vscode-ripgrep/bin")) ||
|
||||
(await checkPath("node_modules.asar.unpacked/vscode-ripgrep/bin/")) ||
|
||||
|
||||
@@ -38,7 +38,7 @@ export async function executeRipgrepForFiles(
|
||||
workspacePath: string,
|
||||
limit = 5000,
|
||||
): Promise<{ path: string; type: "file" | "folder"; label?: string }[]> {
|
||||
const rgPath = await resolveRipgrepPath()
|
||||
const rgPath = await getBinaryLocation("rg")
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// Arguments for ripgrep to list files, follow symlinks, include hidden, and exclude common directories
|
||||
@@ -142,45 +142,11 @@ export async function executeRipgrepForFiles(
|
||||
})
|
||||
}
|
||||
|
||||
async function resolveRipgrepPath(): Promise<string> {
|
||||
try {
|
||||
return await getBinaryLocation("rg")
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
const fallback = await findSystemRipgrep()
|
||||
Logger.warn(`[file-search] bundled ripgrep unavailable, trying ${fallback}: ${message}`)
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
async function findSystemRipgrep(): Promise<string> {
|
||||
const fallback = process.platform === "win32" ? "rg.exe" : "rg"
|
||||
const candidates =
|
||||
process.platform === "win32" ? [] : ["/usr/bin/rg", "/opt/homebrew/bin/rg", "/usr/local/bin/rg"]
|
||||
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
await fs.promises.access(candidate, fs.constants.X_OK)
|
||||
return candidate
|
||||
} catch {
|
||||
// Keep looking; the bare command is the final PATH-based fallback.
|
||||
}
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
|
||||
// Get currently active/open files from VSCode tabs using hostbridge
|
||||
async function getActiveFiles(): Promise<Set<string>> {
|
||||
try {
|
||||
const request = GetOpenTabsRequest.create({})
|
||||
const response = await HostProvider.window.getOpenTabs(request)
|
||||
return new Set(response.paths)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
Logger.warn(`[file-search] failed to read open tabs, continuing without active-file boost: ${message}`)
|
||||
return new Set()
|
||||
}
|
||||
const request = GetOpenTabsRequest.create({})
|
||||
const response = await HostProvider.window.getOpenTabs(request)
|
||||
return new Set(response.paths)
|
||||
}
|
||||
|
||||
// Maximum number of candidates to ask the host for. The result is filtered &
|
||||
|
||||
@@ -28,8 +28,6 @@ describe("File Search", () => {
|
||||
const accessStub = sandbox.stub(fs.promises, "access")
|
||||
accessStub.withArgs("/mock/path/rg").resolves()
|
||||
accessStub.withArgs("/mock/path/rg.exe").resolves()
|
||||
accessStub.withArgs("/mock/path/to/binary/rg").resolves()
|
||||
accessStub.withArgs("/mock/path/to/binary/rg.exe").resolves()
|
||||
|
||||
setVscodeHostProviderMock()
|
||||
})
|
||||
@@ -165,46 +163,6 @@ describe("File Search", () => {
|
||||
should(err).have.property("name", "RipgrepError")
|
||||
should(err.stderr).match(/No such file or directory/)
|
||||
})
|
||||
|
||||
it("falls back to a system ripgrep when the bundled binary path is missing", async () => {
|
||||
setVscodeHostProviderMock({
|
||||
getBinaryLocation: async () => "/missing/rg",
|
||||
})
|
||||
|
||||
const accessStub = fs.promises.access as sinon.SinonStub
|
||||
accessStub.withArgs("/missing/rg").rejects(new Error("missing"))
|
||||
accessStub.withArgs("/usr/bin/rg", fs.constants.X_OK).resolves()
|
||||
|
||||
const mockStdout = new Readable({
|
||||
read() {
|
||||
this.push("/workspace/src/main.ts\n")
|
||||
this.push(null)
|
||||
},
|
||||
})
|
||||
const mockStderr = new Readable({
|
||||
read() {
|
||||
this.push(null)
|
||||
},
|
||||
})
|
||||
|
||||
spawnStub.returns({
|
||||
stdout: mockStdout,
|
||||
stderr: mockStderr,
|
||||
on: function (event: string, callback: Function) {
|
||||
if (event === "exit") {
|
||||
setImmediate(() => callback(0))
|
||||
}
|
||||
return this
|
||||
},
|
||||
kill: () => {},
|
||||
} as unknown as childProcess.ChildProcess)
|
||||
|
||||
const result = await fileSearch.executeRipgrepForFiles("/workspace", 5000)
|
||||
const expectedPath = process.platform === "win32" ? "src\\main.ts" : "src/main.ts"
|
||||
|
||||
should(spawnStub.firstCall.args[0]).equal(process.platform === "win32" ? "rg.exe" : "/usr/bin/rg")
|
||||
should(result).containDeep([{ path: expectedPath, type: "file", label: "main.ts" }])
|
||||
})
|
||||
})
|
||||
|
||||
describe("searchWorkspaceFiles", () => {
|
||||
@@ -252,41 +210,6 @@ describe("File Search", () => {
|
||||
should(srcEntries[0]).have.properties({ path: "src", type: "folder" })
|
||||
})
|
||||
|
||||
it("continues search when the host cannot return open tabs", async () => {
|
||||
sandbox.stub(HostProvider.window, "getOpenTabs").rejects(new Error("getOpenTabs unavailable"))
|
||||
sandbox.stub(HostProvider.workspace, "searchWorkspaceItems").rejects({ code: 12, message: "not implemented" })
|
||||
|
||||
const mockStdout = new Readable({
|
||||
read() {
|
||||
this.push("/workspace/src/main.ts\n")
|
||||
this.push(null)
|
||||
},
|
||||
})
|
||||
const mockStderr = new Readable({
|
||||
read() {
|
||||
this.push(null)
|
||||
},
|
||||
})
|
||||
|
||||
spawnStub.returns({
|
||||
stdout: mockStdout,
|
||||
stderr: mockStderr,
|
||||
on: function (event: string, callback: Function) {
|
||||
if (event === "exit") {
|
||||
setImmediate(() => callback(0))
|
||||
}
|
||||
return this
|
||||
},
|
||||
kill: () => {},
|
||||
} as unknown as childProcess.ChildProcess)
|
||||
|
||||
const result = await fileSearch.searchWorkspaceFiles("", "/workspace", 20)
|
||||
const expectedPath = process.platform === "win32" ? "src\\main.ts" : "src/main.ts"
|
||||
|
||||
should(result.source).equal("ripgrep")
|
||||
should(result.items).containDeep([{ path: expectedPath, type: "file", label: "main.ts" }])
|
||||
})
|
||||
|
||||
it("should apply fuzzy matching for non-empty query", async () => {
|
||||
const mockItems: { path: string; type: "file" | "folder"; label?: string }[] = [
|
||||
{ path: "file1.txt", type: "file", label: "file1.txt" },
|
||||
|
||||
@@ -26,7 +26,7 @@ Cline recognizes rules from multiple sources, so you can use existing rule files
|
||||
| Cline Rules | `.clinerules/` | Primary rule format |
|
||||
| Cursor Rules | `.cursorrules` | Automatically detected |
|
||||
| Windsurf Rules | `.windsurfrules` | Automatically detected |
|
||||
| AGENTS.md | `AGENTS.md`, `~/.agents/AGENTS.md` | [Standard format](https://agents.md/) for cross-tool compatibility |
|
||||
| AGENTS.md | `AGENTS.md` | [Standard format](https://agents.md/) for cross-tool compatibility |
|
||||
|
||||
All detected rule types appear in the Rules panel, where you can toggle them individually.
|
||||
|
||||
@@ -37,7 +37,7 @@ Rules can be stored in two locations: your project workspace or globally on your
|
||||
|
||||
**Workspace rules** go in `.clinerules/` at your project root. Use these for team standards, project-specific constraints, and anything you want to share with collaborators via version control.
|
||||
|
||||
**Global rules** go in your system's Cline Rules directory. Use these for personal preferences that apply across all projects. Cline also reads cross-tool global AGENTS instructions from `~/.agents/AGENTS.md`.
|
||||
**Global rules** go in your system's Cline Rules directory. Use these for personal preferences that apply across all projects.
|
||||
|
||||
```text
|
||||
your-project/
|
||||
|
||||
@@ -370,10 +370,6 @@
|
||||
"source": "/getting-started/installing-cline-jetbrains",
|
||||
"destination": "/getting-started/installing-cline"
|
||||
},
|
||||
{
|
||||
"source": "/getting-started/for-new-coders",
|
||||
"destination": "/getting-started/installing-cline"
|
||||
},
|
||||
{
|
||||
"source": "/getting-started/overview",
|
||||
"destination": "/cline-overview"
|
||||
|
||||
+52
-60
@@ -1,72 +1,64 @@
|
||||
# dependencies (bun install)
|
||||
node_modules
|
||||
|
||||
# output
|
||||
out
|
||||
dist
|
||||
dist-standalone
|
||||
node_modules
|
||||
tmp
|
||||
.vscode-test/
|
||||
*.vsix
|
||||
*.tgz
|
||||
target
|
||||
.next
|
||||
.map
|
||||
|
||||
.DS_Store
|
||||
# code coverage
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# logs
|
||||
logs
|
||||
_.log
|
||||
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env*.local
|
||||
|
||||
# caches
|
||||
.eslintcache
|
||||
.cache
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
# IntelliJ based IDEs
|
||||
.idea
|
||||
.husky/_/
|
||||
|
||||
# Finder (MacOS) folder config
|
||||
.DS_Store
|
||||
|
||||
# Package lock files created by other package managers
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
pnpm-lock.yaml
|
||||
|
||||
.clineignore
|
||||
.venv
|
||||
.actrc
|
||||
CLAUDE.local.md
|
||||
|
||||
apps/vscode/webview-ui/src/**/*.js
|
||||
apps/vscode/webview-ui/src/**/*.js.map
|
||||
|
||||
# Ignore coverage directories and files
|
||||
coverage
|
||||
coverage-unit
|
||||
.nyc_output
|
||||
# But don't ignore the coverage scripts in .github/scripts/
|
||||
!.github/scripts/coverage/
|
||||
|
||||
*evals.env
|
||||
.env
|
||||
.secrets
|
||||
.github/act/.secrets
|
||||
|
||||
.worktrees
|
||||
|
||||
## Generated files ##
|
||||
apps/vscode/src/generated/
|
||||
apps/vscode/src/shared/proto/
|
||||
apps/vscode/webview-ui/src/services/grpc-client.ts
|
||||
*.tsbuildinfo
|
||||
|
||||
# E2E Tests
|
||||
test-results
|
||||
|
||||
/.github/act
|
||||
/pkg
|
||||
.secrets
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
# Smoke test results (generated)
|
||||
evals/smoke-tests/results/
|
||||
|
||||
.tui-test
|
||||
secrets.json
|
||||
tui-traces
|
||||
tests/**/cache
|
||||
|
||||
# Backup created by scripts/marketplace-readme.mjs while publishing.
|
||||
# Should never be committed: only exists if a publish aborts mid-swap.
|
||||
.README.github.bak
|
||||
|
||||
|
||||
# SDK Session files / User data
|
||||
# Session files / User data
|
||||
.cline/data
|
||||
.cline/tmp
|
||||
.cline/**/managed.json
|
||||
.cline/**/bundle.json
|
||||
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
.cline/**/managed.json
|
||||
.cline/**/bundle.json
|
||||
|
||||
# Protobuf generated code
|
||||
packages/rpc/src/proto/generated
|
||||
|
||||
# Tauri generated code
|
||||
apps/*/src-tauri/gen
|
||||
apps/*/src-tauri/bin
|
||||
apps/examples/*/src-tauri/gen
|
||||
apps/examples/*/src-tauri/bin
|
||||
# Tauri UI test snapshots
|
||||
apps/*/src/tests/.tui-test
|
||||
apps/*/src/tests/tui-traces
|
||||
|
||||
.cli-release-staging
|
||||
|
||||
@@ -1,21 +1,5 @@
|
||||
# Cline CLI Changelog
|
||||
|
||||
## 3.0.15
|
||||
|
||||
- Add Cline Hub, a web app for monitoring connected clients, viewing and driving sessions, streaming assistant output, and restarting the local hub, with local, LAN, and tunnel usage gated by a room secret.
|
||||
- Support global AGENTS rules so agent rules can be applied across all sessions, not just per-project.
|
||||
- Let plugins contribute static or dynamic rule content when installed in the sandbox.
|
||||
- Bind Discord sessions to individual message authors so different Discord users no longer share chat state in a thread.
|
||||
- Support participant mute targets in Discord: resolve `/mute` and `/unmute` from user mentions or raw user IDs to mute a specific participant in a thread.
|
||||
- Make OAuth URLs clickable in the TUI.
|
||||
- Refresh the bundled model catalog, adding Claude Opus 4.8, Moonshot Kimi K2.6, and Qwen3.7 Max (with cache support).
|
||||
- Discover SDK skill directories that are symlinked, including handling circular symlinks.
|
||||
- Steer active connector sessions across turn keys by matching on session ID, so replies continue the existing session instead of starting a duplicate.
|
||||
- Stop the Discord connector after repeated identical errors (per thread, within a time window) to prevent error messages from flooding a channel.
|
||||
- Fix Discord connector registration and reply fallback handling.
|
||||
- Fix SAP AI Core to use the AI SDK community provider.
|
||||
- Log ACP output as diagnostics instead of errors so normal output no longer appears as errors.
|
||||
|
||||
## 3.0.14
|
||||
|
||||
- Fix OTEL telemetry variable bundling so telemetry is correctly enabled in compiled CLI builds: guard against environments where `process.env` is undefined and remove optional chaining so bundlers can inline the values at build time.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@cline/cli",
|
||||
"displayName": "cline",
|
||||
"version": "3.0.15",
|
||||
"version": "3.0.14",
|
||||
"description": "Autonomous coding agent CLI - capable of creating/editing files, running commands, using the browser, and more",
|
||||
"type": "module",
|
||||
"publishConfig": {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync, readFileSync, rmSync } from "node:fs";
|
||||
import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import {
|
||||
clearHubDiscovery,
|
||||
@@ -14,10 +14,6 @@ import { formatUptime } from "@cline/shared";
|
||||
import { Command } from "commander";
|
||||
import open from "open";
|
||||
import { isProcessRunning } from "../connectors/common";
|
||||
import {
|
||||
type ActiveConnectorRecord,
|
||||
listActiveConnectors,
|
||||
} from "../connectors/status";
|
||||
import { getCliBuildInfo } from "../utils/common";
|
||||
import { c, writeln } from "../utils/output";
|
||||
import { stopAllConnectors } from "./connect";
|
||||
@@ -38,6 +34,19 @@ type StartupArtifact = {
|
||||
stale: boolean;
|
||||
};
|
||||
|
||||
type ActiveConnectorRecord = {
|
||||
type: string;
|
||||
pid: number;
|
||||
hubUrl: string;
|
||||
startedAt?: string;
|
||||
applicationId?: string;
|
||||
botUsername?: string;
|
||||
userName?: string;
|
||||
phoneNumberId?: string;
|
||||
port?: number;
|
||||
baseUrl?: string;
|
||||
};
|
||||
|
||||
type SpawnedProcessRecord = {
|
||||
timestamp?: string;
|
||||
pid?: number;
|
||||
@@ -278,6 +287,142 @@ async function clearHubStartupArtifacts(
|
||||
};
|
||||
}
|
||||
|
||||
function listConnectorStatePaths(
|
||||
type: ActiveConnectorRecord["type"],
|
||||
): string[] {
|
||||
const dir = join(resolveClineDataDir(), "connectors", type);
|
||||
if (!existsSync(dir)) {
|
||||
return [];
|
||||
}
|
||||
return readdirSync(dir)
|
||||
.filter((name) => name.endsWith(".json") && !name.endsWith(".threads.json"))
|
||||
.map((name) => join(dir, name));
|
||||
}
|
||||
|
||||
function readJsonRecord(path: string): Record<string, unknown> | undefined {
|
||||
if (!existsSync(path)) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const raw = readFileSync(path, "utf8");
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
||||
return parsed as Record<string, unknown>;
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed connector state.
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
type ConnectorFieldKey = keyof Omit<
|
||||
ActiveConnectorRecord,
|
||||
"type" | "pid" | "hubUrl"
|
||||
>;
|
||||
|
||||
const connectorFieldExtractors: Record<
|
||||
ConnectorFieldKey,
|
||||
(p: Record<string, unknown>) => string | number | undefined
|
||||
> = {
|
||||
startedAt: (p) => (typeof p.startedAt === "string" ? p.startedAt : undefined),
|
||||
port: (p) => (typeof p.port === "number" ? p.port : undefined),
|
||||
baseUrl: (p) => (typeof p.baseUrl === "string" ? p.baseUrl : undefined),
|
||||
userName: (p) => (typeof p.userName === "string" ? p.userName : undefined),
|
||||
botUsername: (p) =>
|
||||
typeof p.botUsername === "string" ? p.botUsername : undefined,
|
||||
applicationId: (p) =>
|
||||
typeof p.applicationId === "string" ? p.applicationId : undefined,
|
||||
phoneNumberId: (p) =>
|
||||
typeof p.phoneNumberId === "string" ? p.phoneNumberId : undefined,
|
||||
};
|
||||
|
||||
const connectorConfigs: Record<
|
||||
string,
|
||||
{ required: ConnectorFieldKey[]; optional: ConnectorFieldKey[] }
|
||||
> = {
|
||||
discord: {
|
||||
required: ["userName", "applicationId"],
|
||||
optional: ["startedAt", "port", "baseUrl"],
|
||||
},
|
||||
telegram: { required: ["botUsername"], optional: ["startedAt"] },
|
||||
gchat: { required: ["userName"], optional: ["startedAt", "port", "baseUrl"] },
|
||||
linear: {
|
||||
required: ["userName"],
|
||||
optional: ["startedAt", "port", "baseUrl"],
|
||||
},
|
||||
whatsapp: {
|
||||
required: ["userName"],
|
||||
optional: ["startedAt", "phoneNumberId", "port", "baseUrl"],
|
||||
},
|
||||
};
|
||||
|
||||
function readActiveConnectorRecord(
|
||||
type: ActiveConnectorRecord["type"],
|
||||
statePath: string,
|
||||
): ActiveConnectorRecord | undefined {
|
||||
const parsed = readJsonRecord(statePath);
|
||||
if (!parsed) {
|
||||
return undefined;
|
||||
}
|
||||
const pid = typeof parsed.pid === "number" ? parsed.pid : undefined;
|
||||
const hubUrl =
|
||||
typeof parsed.hubUrl === "string"
|
||||
? parsed.hubUrl
|
||||
: typeof parsed.rpcAddress === "string"
|
||||
? parsed.rpcAddress
|
||||
: undefined;
|
||||
if (!pid || !hubUrl || !isProcessRunning(pid)) {
|
||||
return undefined;
|
||||
}
|
||||
const config = connectorConfigs[type];
|
||||
if (!config) {
|
||||
return undefined;
|
||||
}
|
||||
const fields: Partial<
|
||||
Omit<ActiveConnectorRecord, "type" | "pid" | "hubUrl">
|
||||
> = {};
|
||||
for (const key of config.required) {
|
||||
const value = connectorFieldExtractors[key](parsed);
|
||||
if (!value || (typeof value === "string" && !value.trim())) {
|
||||
return undefined;
|
||||
}
|
||||
(fields as Record<string, unknown>)[key] = value;
|
||||
}
|
||||
for (const key of config.optional) {
|
||||
const value = connectorFieldExtractors[key](parsed);
|
||||
if (value !== undefined) {
|
||||
(fields as Record<string, unknown>)[key] = value;
|
||||
}
|
||||
}
|
||||
return { type, pid, hubUrl, ...fields } as ActiveConnectorRecord;
|
||||
}
|
||||
|
||||
function listActiveConnectors(): ActiveConnectorRecord[] {
|
||||
const connectorTypes: ActiveConnectorRecord["type"][] = [
|
||||
"telegram",
|
||||
"gchat",
|
||||
"linear",
|
||||
"whatsapp",
|
||||
];
|
||||
const records: ActiveConnectorRecord[] = [];
|
||||
for (const type of connectorTypes) {
|
||||
for (const statePath of listConnectorStatePaths(type)) {
|
||||
const record = readActiveConnectorRecord(type, statePath);
|
||||
if (record) {
|
||||
records.push(record);
|
||||
}
|
||||
}
|
||||
}
|
||||
return records.sort((left, right) => {
|
||||
if (left.type !== right.type) {
|
||||
return left.type.localeCompare(right.type);
|
||||
}
|
||||
const leftName = left.botUsername ?? left.userName ?? "";
|
||||
const rightName = right.botUsername ?? right.userName ?? "";
|
||||
return leftName.localeCompare(rightName);
|
||||
});
|
||||
}
|
||||
|
||||
function formatHubUptimeFromStartedAt(
|
||||
startedAt: string | undefined,
|
||||
): string | undefined {
|
||||
|
||||
@@ -258,7 +258,6 @@ describe("plugin install command", () => {
|
||||
},
|
||||
peerDependencies: {
|
||||
"@cline/shared": "*",
|
||||
bun: ">=1.0.0",
|
||||
},
|
||||
peerDependenciesMeta: {
|
||||
"@cline/shared": {
|
||||
@@ -305,12 +304,12 @@ describe("plugin install command", () => {
|
||||
peerDependenciesMeta?: Record<string, unknown>;
|
||||
};
|
||||
expect(packageManifest.dependencies).toEqual({ yaml: "^2.8.1" });
|
||||
expect(packageManifest.peerDependencies).toEqual({ bun: ">=1.0.0" });
|
||||
expect(packageManifest.peerDependencies).toBeUndefined();
|
||||
expect(packageManifest.peerDependenciesMeta).toBeUndefined();
|
||||
const npmLog = readFileSync(npmLogPath, "utf8");
|
||||
expect(npmLog).toContain(`${join(".tmp")}/`);
|
||||
expect(npmLog).toContain(
|
||||
"package install --omit=dev --omit=peer --legacy-peer-deps --no-audit --no-fund --package-lock=false",
|
||||
"package install --omit=dev --no-audit --no-fund --package-lock=false",
|
||||
);
|
||||
expect(existsSync(join(result.installPath, "package", ".git"))).toBe(false);
|
||||
expect(
|
||||
@@ -357,7 +356,6 @@ describe("plugin install command", () => {
|
||||
const npmLog = readFileSync(npmLogPath, "utf8");
|
||||
expect(npmLog).toContain("install published-plugin@1.0.0");
|
||||
expect(npmLog).toContain("--omit=peer");
|
||||
expect(npmLog).toContain("--legacy-peer-deps");
|
||||
expect(
|
||||
existsSync(
|
||||
join(result.installPath, "package", "node_modules", "@cline", "core"),
|
||||
|
||||
@@ -671,7 +671,6 @@ async function installNpmPackage(
|
||||
packageRoot,
|
||||
"--omit=dev",
|
||||
"--omit=peer",
|
||||
"--legacy-peer-deps",
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
"--package-lock=false",
|
||||
@@ -693,8 +692,6 @@ async function installPackageDependencies(
|
||||
[
|
||||
"install",
|
||||
"--omit=dev",
|
||||
"--omit=peer",
|
||||
"--legacy-peer-deps",
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
"--package-lock=false",
|
||||
|
||||
@@ -345,32 +345,6 @@ describe("discordConnector", () => {
|
||||
it("instructs Discord agents to use /idle for unrelated subscribed thread messages", () => {
|
||||
expect(__test__.DISCORD_SYSTEM_RULES).toContain("reply exactly /idle");
|
||||
expect(__test__.DISCORD_SYSTEM_RULES).toContain("isDirectMention is false");
|
||||
expect(__test__.DISCORD_SYSTEM_RULES).toContain("send /mute@BotName");
|
||||
expect(__test__.DISCORD_SYSTEM_RULES).toContain("send /unmute@BotName");
|
||||
expect(__test__.DISCORD_SYSTEM_RULES).toContain(
|
||||
"/mute@BotName @user-or-bot",
|
||||
);
|
||||
expect(__test__.DISCORD_SYSTEM_RULES).toContain(
|
||||
"/unmute@BotName @user-or-bot",
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves Discord mute targets from user mentions and ids", () => {
|
||||
expect(__test__.resolveDiscordMuteTarget("<@123456789012345678>")).toEqual({
|
||||
participantKey: "discord:user:123456789012345678",
|
||||
participantLabel: "<@123456789012345678>",
|
||||
});
|
||||
expect(__test__.resolveDiscordMuteTarget("<@!123456789012345678>")).toEqual(
|
||||
{
|
||||
participantKey: "discord:user:123456789012345678",
|
||||
participantLabel: "<@123456789012345678>",
|
||||
},
|
||||
);
|
||||
expect(__test__.resolveDiscordMuteTarget("@123456789012345678")).toEqual({
|
||||
participantKey: "discord:user:123456789012345678",
|
||||
participantLabel: "<@123456789012345678>",
|
||||
});
|
||||
expect(__test__.resolveDiscordMuteTarget("@not-a-user-id")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves outbound Discord mention names to user mention ids", async () => {
|
||||
|
||||
@@ -47,7 +47,6 @@ import { InMemoryStateAdapter } from "../stores/memory-state";
|
||||
import { startConnectorTaskUpdateRelay } from "../task-updates";
|
||||
import {
|
||||
type ConnectorBindingStore,
|
||||
type ConnectorMuteTarget,
|
||||
type ConnectorThreadState,
|
||||
clearBindingSessionIds,
|
||||
findBindingForParticipantKey,
|
||||
@@ -74,8 +73,6 @@ const DISCORD_SYSTEM_RULES = getConnectorSystemRules(
|
||||
"You can respond in Discord threads, channels, and DMs, and you can use tools according to the user's requests and your capabilities.",
|
||||
"When asked to mention a Discord user or bot by name, write the mention as @display-name or @username. The connector resolves unique guild names to Discord mention IDs before sending. Do not ask the user for a Discord ID unless the name cannot be resolved.",
|
||||
"Discord subscribed thread messages may arrive even when they are not addressed to you. Check <discord_message_context>: when isDirectMention is false and the message is part of another user or bot conversation that does not require your action, reply exactly /idle and nothing else. The connector treats /idle as a private no-op and will not post it to Discord.",
|
||||
"If this Discord thread is caught in a bot loop or the user wants the connector to stop processing this thread, tell them to send /mute@BotName in shared channels or /mute in DMs. Tell them to send /unmute@BotName in shared channels or /unmute in DMs when they want this connector to resume processing the thread.",
|
||||
"If the user wants to mute only one Discord user or bot in the current thread, tell them to send /mute@BotName @user-or-bot in shared channels or /mute @user-or-bot in DMs. Tell them to send /unmute@BotName @user-or-bot in shared channels or /unmute @user-or-bot in DMs to resume processing that participant.",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
@@ -278,22 +275,6 @@ function formatDiscordRuntimeText(
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function resolveDiscordMuteTarget(
|
||||
rawTarget: string,
|
||||
): ConnectorMuteTarget | undefined {
|
||||
const trimmed = rawTarget.trim();
|
||||
const userId =
|
||||
trimmed.match(/^<@!?(\d{15,25})>$/)?.[1] ??
|
||||
trimmed.match(/^@?(\d{15,25})$/)?.[1];
|
||||
if (!userId) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
participantKey: `discord:user:${userId}`,
|
||||
participantLabel: `<@${userId}>`,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeDiscordThreadId(threadId: string): DiscordThreadIdParts {
|
||||
const parts = threadId.split(":");
|
||||
if (parts.length < 3 || parts[0] !== "discord") {
|
||||
@@ -994,14 +975,11 @@ class DiscordConnector extends ConnectorBase<
|
||||
|
||||
const statePath = this.resolveConnectorStatePath(options.applicationId);
|
||||
const bindingsPath = this.resolveBindingsPath(options.applicationId);
|
||||
const staleState = this.removeStaleState(
|
||||
this.removeStaleState(
|
||||
statePath,
|
||||
(path) => this.readConnectorState(path),
|
||||
(state) => state.pid,
|
||||
);
|
||||
if (staleState) {
|
||||
clearBindingSessionIds<DiscordThreadState>(bindingsPath);
|
||||
}
|
||||
if (
|
||||
await this.maybeRunInBackground({
|
||||
rawArgs,
|
||||
@@ -1115,12 +1093,6 @@ class DiscordConnector extends ConnectorBase<
|
||||
resolveStop?.();
|
||||
};
|
||||
|
||||
|
||||
type ErrorTrackerEntry = { count: number; firstSeen: number; lastSeen: number };
|
||||
const errorTracker = new Map<string, ErrorTrackerEntry>();
|
||||
const MAX_REPEATED_ERRORS = 3;
|
||||
const ERROR_WINDOW_MS = 60_000; // 1 minute
|
||||
|
||||
const handleTurn = async (
|
||||
thread: Thread<DiscordThreadState>,
|
||||
text: string,
|
||||
@@ -1153,9 +1125,6 @@ class DiscordConnector extends ConnectorBase<
|
||||
logger: loggerAdapter,
|
||||
transport: "discord",
|
||||
botUserName: options.userName,
|
||||
ownerParticipantKeys: options.ownerUserId
|
||||
? [`discord:user:${options.ownerUserId}`]
|
||||
: undefined,
|
||||
requestStop,
|
||||
bindingsPath,
|
||||
hookCommand: options.hookCommand,
|
||||
@@ -1166,7 +1135,6 @@ class DiscordConnector extends ConnectorBase<
|
||||
chatCommandHost,
|
||||
activeTurns,
|
||||
turnKey: queueKey,
|
||||
resolveMuteTarget: ({ target }) => resolveDiscordMuteTarget(target),
|
||||
createEmptyRuntimeReplyResolver:
|
||||
createDiscordEmptyRuntimeReplyResolver,
|
||||
getSessionMetadata: (currentThread, _clientId, currentState) => ({
|
||||
@@ -1250,46 +1218,7 @@ class DiscordConnector extends ConnectorBase<
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
|
||||
// Track repeated errors per-thread with fixed time window
|
||||
const now = Date.now();
|
||||
const errorKey = `${thread.id}:${message.slice(0, 200)}`; // Per-thread error tracking
|
||||
const tracked = errorTracker.get(errorKey);
|
||||
|
||||
if (!tracked) {
|
||||
// First occurrence, start tracking
|
||||
errorTracker.set(errorKey, { count: 1, firstSeen: now, lastSeen: now });
|
||||
await thread.post(`Discord bridge error: ${message}`);
|
||||
} else if (now - tracked.firstSeen > ERROR_WINDOW_MS) {
|
||||
// Outside fixed window, reset counter
|
||||
errorTracker.set(errorKey, { count: 1, firstSeen: now, lastSeen: now });
|
||||
await thread.post(`Discord bridge error: ${message}`);
|
||||
} else {
|
||||
// Within fixed window, increment counter
|
||||
tracked.count++;
|
||||
tracked.lastSeen = now;
|
||||
|
||||
if (tracked.count >= MAX_REPEATED_ERRORS) {
|
||||
// Too many repeated errors in this thread, kill the connector
|
||||
loggerAdapter.core.error?.(
|
||||
"Discord connector stopping due to repeated errors",
|
||||
{
|
||||
transport: "discord",
|
||||
threadId: thread.id,
|
||||
errorMessage: message,
|
||||
count: tracked.count,
|
||||
windowMs: now - tracked.firstSeen,
|
||||
},
|
||||
);
|
||||
await thread.post(
|
||||
`Discord bridge error (repeated ${tracked.count} times in ${Math.round((now - tracked.firstSeen) / 1000)}s): ${message}\n\nConnector shutting down due to repeated errors.`,
|
||||
);
|
||||
requestStop("repeated_discord_errors");
|
||||
} else {
|
||||
// Still within threshold, post error
|
||||
await thread.post(`Discord bridge error: ${message}`);
|
||||
}
|
||||
}
|
||||
await thread.post(`Discord bridge error: ${message}`);
|
||||
}
|
||||
};
|
||||
if (activeTurns.has(queueKey)) {
|
||||
@@ -1554,7 +1483,6 @@ class DiscordConnector extends ConnectorBase<
|
||||
}
|
||||
|
||||
await stopPromise;
|
||||
clearBindingSessionIds<DiscordThreadState>(bindingsPath);
|
||||
gatewayAbortController.abort();
|
||||
stopTaskUpdateStream();
|
||||
stopEventStream();
|
||||
@@ -1574,7 +1502,6 @@ export const __test__ = {
|
||||
DISCORD_SYSTEM_RULES,
|
||||
createDiscordEmptyRuntimeReplyResolver,
|
||||
formatDiscordRuntimeText,
|
||||
resolveDiscordMuteTarget,
|
||||
findBindingForThread: (
|
||||
bindings: ConnectorBindingStore<DiscordThreadState>,
|
||||
thread: Pick<Thread<DiscordThreadState>, "id" | "channelId" | "isDM"> & {
|
||||
|
||||
@@ -416,14 +416,11 @@ class GoogleChatConnector extends ConnectorBase<
|
||||
): Promise<number> {
|
||||
const statePath = this.resolveConnectorStatePath(options.userName);
|
||||
const bindingsPath = this.resolveBindingsPath(options.userName);
|
||||
const staleState = this.removeStaleState(
|
||||
this.removeStaleState(
|
||||
statePath,
|
||||
(path) => this.readConnectorState(path),
|
||||
(state) => state.pid,
|
||||
);
|
||||
if (staleState) {
|
||||
clearBindingSessionIds<GoogleChatThreadState>(bindingsPath);
|
||||
}
|
||||
if (
|
||||
await this.maybeRunInBackground({
|
||||
rawArgs,
|
||||
@@ -819,7 +816,6 @@ class GoogleChatConnector extends ConnectorBase<
|
||||
io.writeln(`[gchat] configure Google Chat App URL: ${endpointUrl}`);
|
||||
|
||||
await stopPromise;
|
||||
clearBindingSessionIds<GoogleChatThreadState>(bindingsPath);
|
||||
stopTaskUpdateStream();
|
||||
stopEventStream();
|
||||
await server.close();
|
||||
|
||||
@@ -484,14 +484,11 @@ class LinearConnector extends ConnectorBase<
|
||||
): Promise<number> {
|
||||
const statePath = this.resolveConnectorStatePath(options.userName);
|
||||
const bindingsPath = this.resolveBindingsPath(options.userName);
|
||||
const staleState = this.removeStaleState(
|
||||
this.removeStaleState(
|
||||
statePath,
|
||||
(path) => this.readConnectorState(path),
|
||||
(state) => state.pid,
|
||||
);
|
||||
if (staleState) {
|
||||
clearBindingSessionIds<LinearThreadState>(bindingsPath);
|
||||
}
|
||||
if (
|
||||
await this.maybeRunInBackground({
|
||||
rawArgs,
|
||||
@@ -856,7 +853,6 @@ class LinearConnector extends ConnectorBase<
|
||||
io.writeln(`[linear] configure Linear webhook URL: ${webhookUrl}`);
|
||||
|
||||
await stopPromise;
|
||||
clearBindingSessionIds<LinearThreadState>(bindingsPath);
|
||||
stopTaskUpdateStream();
|
||||
stopEventStream();
|
||||
await server.close();
|
||||
|
||||
@@ -581,14 +581,11 @@ class SlackConnector extends ConnectorBase<
|
||||
const statePath = this.resolveConnectorStatePath(options.userName);
|
||||
const bindingsPath = this.resolveBindingsPath(options.userName);
|
||||
const stateStorePath = this.resolveStateStorePath(options.userName);
|
||||
const staleState = this.removeStaleState(
|
||||
this.removeStaleState(
|
||||
statePath,
|
||||
(path) => this.readConnectorState(path),
|
||||
(state) => state.pid,
|
||||
);
|
||||
if (staleState) {
|
||||
clearBindingSessionIds<SlackThreadState>(bindingsPath);
|
||||
}
|
||||
if (
|
||||
await this.maybeRunInBackground({
|
||||
rawArgs,
|
||||
@@ -1059,7 +1056,6 @@ class SlackConnector extends ConnectorBase<
|
||||
);
|
||||
|
||||
await stopPromise;
|
||||
clearBindingSessionIds<SlackThreadState>(bindingsPath);
|
||||
stopTaskUpdateStream();
|
||||
stopEventStream();
|
||||
await server.close();
|
||||
|
||||
@@ -609,14 +609,11 @@ class TelegramConnector extends ConnectorBase<
|
||||
: [...rawArgs, "--bot-username", resolvedBotUsername];
|
||||
const statePath = this.resolveConnectorStatePath(options.botUsername);
|
||||
const bindingsPath = this.resolveBindingsPath(options.botUsername);
|
||||
const staleState = this.removeStaleState(
|
||||
this.removeStaleState(
|
||||
statePath,
|
||||
(path) => this.readConnectorState(path),
|
||||
(state) => state.pid,
|
||||
);
|
||||
if (staleState) {
|
||||
clearBindingSessionIds<TelegramThreadState>(bindingsPath);
|
||||
}
|
||||
if (
|
||||
await this.maybeRunInBackground({
|
||||
rawArgs: backgroundArgs,
|
||||
@@ -1061,7 +1058,6 @@ class TelegramConnector extends ConnectorBase<
|
||||
process.on("SIGTERM", shutdown);
|
||||
|
||||
await stopPromise;
|
||||
clearBindingSessionIds<TelegramThreadState>(bindingsPath);
|
||||
|
||||
stopTaskUpdateStream();
|
||||
stopEventStream();
|
||||
|
||||
@@ -455,14 +455,11 @@ class WhatsAppConnector extends ConnectorBase<
|
||||
});
|
||||
const statePath = this.resolveConnectorStatePath(instanceKey);
|
||||
const bindingsPath = this.resolveBindingsPath(instanceKey);
|
||||
const staleState = this.removeStaleState(
|
||||
this.removeStaleState(
|
||||
statePath,
|
||||
(path) => this.readConnectorState(path),
|
||||
(state) => state.pid,
|
||||
);
|
||||
if (staleState) {
|
||||
clearBindingSessionIds<WhatsAppThreadState>(bindingsPath);
|
||||
}
|
||||
if (
|
||||
await this.maybeRunInBackground({
|
||||
rawArgs,
|
||||
@@ -845,7 +842,6 @@ class WhatsAppConnector extends ConnectorBase<
|
||||
io.writeln(`[whatsapp] configure WhatsApp webhook URL: ${endpointUrl}`);
|
||||
|
||||
await stopPromise;
|
||||
clearBindingSessionIds<WhatsAppThreadState>(bindingsPath);
|
||||
stopTaskUpdateStream();
|
||||
stopEventStream();
|
||||
await server.close();
|
||||
|
||||
@@ -124,13 +124,11 @@ export abstract class ConnectorBase<Options, State>
|
||||
statePath: string,
|
||||
readState: (path: string) => State | undefined,
|
||||
getPid: (state: State) => number,
|
||||
): State | undefined {
|
||||
): void {
|
||||
const state = readState(statePath);
|
||||
if (state && !isProcessRunning(getPid(state))) {
|
||||
this.removeStateFile(statePath);
|
||||
return state;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
protected async maybeRunInBackground(input: {
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
export type ConnectorCatalogEntry = {
|
||||
name: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
export const CONNECTOR_CATALOG: ConnectorCatalogEntry[] = [
|
||||
{
|
||||
name: "discord",
|
||||
description:
|
||||
"Discord interactions and gateway bridge backed by RPC runtime sessions",
|
||||
},
|
||||
{
|
||||
name: "gchat",
|
||||
description: "Google Chat webhook bridge backed by RPC runtime sessions",
|
||||
},
|
||||
{
|
||||
name: "linear",
|
||||
description: "Linear webhook bridge backed by RPC runtime sessions",
|
||||
},
|
||||
{
|
||||
name: "slack",
|
||||
description: "Slack webhook bridge backed by RPC runtime sessions",
|
||||
},
|
||||
{
|
||||
name: "telegram",
|
||||
description: "Bridge Telegram bot messages into RPC chat sessions",
|
||||
},
|
||||
{
|
||||
name: "whatsapp",
|
||||
description: "Bridge WhatsApp webhook messages into RPC chat sessions",
|
||||
},
|
||||
];
|
||||
|
||||
export function listConnectorCatalog(): ConnectorCatalogEntry[] {
|
||||
return CONNECTOR_CATALOG.map((entry) => ({ ...entry }));
|
||||
}
|
||||
@@ -28,14 +28,14 @@ type TestState = {
|
||||
welcomeSentAt?: string;
|
||||
};
|
||||
|
||||
function createThread(initialState: TestState = {}, isDM = true) {
|
||||
function createThread(initialState: TestState = {}) {
|
||||
let state = { ...initialState };
|
||||
const posts: unknown[] = [];
|
||||
return {
|
||||
thread: {
|
||||
id: "thread-1",
|
||||
channelId: "channel-1",
|
||||
isDM,
|
||||
isDM: true,
|
||||
get state() {
|
||||
return Promise.resolve(state);
|
||||
},
|
||||
@@ -58,7 +58,7 @@ function createThread(initialState: TestState = {}, isDM = true) {
|
||||
return {
|
||||
id: "thread-1",
|
||||
channelId: "channel-1",
|
||||
isDM,
|
||||
isDM: true,
|
||||
state,
|
||||
};
|
||||
},
|
||||
@@ -92,8 +92,6 @@ function createRuntimeClient(
|
||||
) {
|
||||
const startRuntimeSession = vi.fn(async () => ({ sessionId: "session-1" }));
|
||||
const updateSession = vi.fn(async () => undefined);
|
||||
const abortRuntimeSession = vi.fn(async () => undefined);
|
||||
const deleteSession = vi.fn(async () => undefined);
|
||||
const sendRuntimeSession = vi.fn(async () => ({
|
||||
result: {
|
||||
text: responseText,
|
||||
@@ -106,9 +104,6 @@ function createRuntimeClient(
|
||||
client: {
|
||||
startRuntimeSession,
|
||||
updateSession,
|
||||
abortRuntimeSession,
|
||||
stopRuntimeSession: abortRuntimeSession,
|
||||
deleteSession,
|
||||
sendRuntimeSession,
|
||||
readMessages,
|
||||
streamEvents: vi.fn(() => () => undefined),
|
||||
@@ -255,194 +250,6 @@ describe("handleConnectorUserTurn", () => {
|
||||
expect(getState().welcomeSentAt).toBeUndefined();
|
||||
});
|
||||
|
||||
it("ignores bare connector slash commands in shared threads", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "connector-host-test-"));
|
||||
tempDirs.push(dir);
|
||||
const bindingsPath = join(dir, "threads.json");
|
||||
const { thread, posts, getState } = createThread(
|
||||
{
|
||||
sessionId: "session-1",
|
||||
enableTools: false,
|
||||
autoApproveTools: false,
|
||||
cwd: "/tmp/work",
|
||||
workspaceRoot: "/tmp/work",
|
||||
participantKey: "discord:user:owner",
|
||||
participantLabel: "owner",
|
||||
},
|
||||
false,
|
||||
);
|
||||
const runtime = createRuntimeClient("unused");
|
||||
|
||||
await handleConnectorUserTurn({
|
||||
thread: thread as never,
|
||||
text: "/new",
|
||||
client: runtime.client as never,
|
||||
pendingApprovals: new Map(),
|
||||
baseStartRequest: baseStartRequest() as never,
|
||||
explicitSystemPrompt: undefined,
|
||||
clientId: "client-1",
|
||||
logger: {
|
||||
core: { debug: vi.fn(), log: vi.fn(), error: vi.fn() },
|
||||
} as never,
|
||||
transport: "discord",
|
||||
botUserName: "ClineAdapterBot",
|
||||
ownerParticipantKeys: ["discord:user:owner"],
|
||||
requestStop: vi.fn(),
|
||||
bindingsPath,
|
||||
systemRules: "rules",
|
||||
errorLabel: "Discord",
|
||||
getSessionMetadata: () => ({}),
|
||||
reusedLogMessage: "reused",
|
||||
});
|
||||
|
||||
expect(posts).toEqual([]);
|
||||
expect(getState().sessionId).toBe("session-1");
|
||||
expect(runtime.client.abortRuntimeSession).not.toHaveBeenCalled();
|
||||
expect(runtime.sendRuntimeSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows owner-addressed connector slash commands in shared threads", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "connector-host-test-"));
|
||||
tempDirs.push(dir);
|
||||
const bindingsPath = join(dir, "threads.json");
|
||||
const { thread, posts, getState } = createThread(
|
||||
{
|
||||
sessionId: "session-1",
|
||||
enableTools: false,
|
||||
autoApproveTools: false,
|
||||
cwd: "/tmp/work",
|
||||
workspaceRoot: "/tmp/work",
|
||||
participantKey: "discord:user:owner",
|
||||
participantLabel: "owner",
|
||||
},
|
||||
false,
|
||||
);
|
||||
const runtime = createRuntimeClient("unused");
|
||||
|
||||
await handleConnectorUserTurn({
|
||||
thread: thread as never,
|
||||
text: "/new@ClineAdapterBot",
|
||||
client: runtime.client as never,
|
||||
pendingApprovals: new Map(),
|
||||
baseStartRequest: baseStartRequest() as never,
|
||||
explicitSystemPrompt: undefined,
|
||||
clientId: "client-1",
|
||||
logger: {
|
||||
core: { debug: vi.fn(), log: vi.fn(), error: vi.fn() },
|
||||
} as never,
|
||||
transport: "discord",
|
||||
botUserName: "ClineAdapterBot",
|
||||
ownerParticipantKeys: ["discord:user:owner"],
|
||||
requestStop: vi.fn(),
|
||||
bindingsPath,
|
||||
hookCommand: "echo noop",
|
||||
systemRules: "rules",
|
||||
errorLabel: "Discord",
|
||||
getSessionMetadata: () => ({}),
|
||||
reusedLogMessage: "reused",
|
||||
});
|
||||
|
||||
expect(posts).toEqual(["Started a fresh session."]);
|
||||
expect(getState().sessionId).toBeUndefined();
|
||||
expect(runtime.client.abortRuntimeSession).toHaveBeenCalledWith(
|
||||
"session-1",
|
||||
);
|
||||
expect(dispatchConnectorHookMock).toHaveBeenCalledWith(
|
||||
"echo noop",
|
||||
expect.objectContaining({ event: "session.reset" }),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("denies non-owner connector slash commands", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "connector-host-test-"));
|
||||
tempDirs.push(dir);
|
||||
const bindingsPath = join(dir, "threads.json");
|
||||
const { thread, posts, getState } = createThread(
|
||||
{
|
||||
sessionId: "session-1",
|
||||
enableTools: false,
|
||||
autoApproveTools: false,
|
||||
cwd: "/tmp/work",
|
||||
workspaceRoot: "/tmp/work",
|
||||
participantKey: "discord:user:not-owner",
|
||||
participantLabel: "not-owner",
|
||||
},
|
||||
false,
|
||||
);
|
||||
const runtime = createRuntimeClient("unused");
|
||||
|
||||
await handleConnectorUserTurn({
|
||||
thread: thread as never,
|
||||
text: "/new@ClineAdapterBot",
|
||||
client: runtime.client as never,
|
||||
pendingApprovals: new Map(),
|
||||
baseStartRequest: baseStartRequest() as never,
|
||||
explicitSystemPrompt: undefined,
|
||||
clientId: "client-1",
|
||||
logger: {
|
||||
core: { debug: vi.fn(), log: vi.fn(), error: vi.fn() },
|
||||
} as never,
|
||||
transport: "discord",
|
||||
botUserName: "ClineAdapterBot",
|
||||
ownerParticipantKeys: ["discord:user:owner"],
|
||||
requestStop: vi.fn(),
|
||||
bindingsPath,
|
||||
systemRules: "rules",
|
||||
errorLabel: "Discord",
|
||||
getSessionMetadata: () => ({}),
|
||||
reusedLogMessage: "reused",
|
||||
});
|
||||
|
||||
expect(posts).toEqual(["Only the connector owner can use slash commands."]);
|
||||
expect(getState().sessionId).toBe("session-1");
|
||||
expect(runtime.client.abortRuntimeSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps bare connector slash commands available in DMs", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "connector-host-test-"));
|
||||
tempDirs.push(dir);
|
||||
const bindingsPath = join(dir, "threads.json");
|
||||
const { thread, posts, getState } = createThread({
|
||||
sessionId: "session-1",
|
||||
enableTools: false,
|
||||
autoApproveTools: false,
|
||||
cwd: "/tmp/work",
|
||||
workspaceRoot: "/tmp/work",
|
||||
participantKey: "discord:user:owner",
|
||||
participantLabel: "owner",
|
||||
});
|
||||
const runtime = createRuntimeClient("unused");
|
||||
|
||||
await handleConnectorUserTurn({
|
||||
thread: thread as never,
|
||||
text: "/new",
|
||||
client: runtime.client as never,
|
||||
pendingApprovals: new Map(),
|
||||
baseStartRequest: baseStartRequest() as never,
|
||||
explicitSystemPrompt: undefined,
|
||||
clientId: "client-1",
|
||||
logger: {
|
||||
core: { debug: vi.fn(), log: vi.fn(), error: vi.fn() },
|
||||
} as never,
|
||||
transport: "discord",
|
||||
botUserName: "ClineAdapterBot",
|
||||
ownerParticipantKeys: ["discord:user:owner"],
|
||||
requestStop: vi.fn(),
|
||||
bindingsPath,
|
||||
systemRules: "rules",
|
||||
errorLabel: "Discord",
|
||||
getSessionMetadata: () => ({}),
|
||||
reusedLogMessage: "reused",
|
||||
});
|
||||
|
||||
expect(posts).toEqual(["Started a fresh session."]);
|
||||
expect(getState().sessionId).toBeUndefined();
|
||||
expect(runtime.client.abortRuntimeSession).toHaveBeenCalledWith(
|
||||
"session-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps tools disabled when connector startup forced no-tools", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "connector-host-test-"));
|
||||
tempDirs.push(dir);
|
||||
@@ -864,371 +671,6 @@ describe("handleConnectorUserTurn", () => {
|
||||
expect(posts).toEqual([]);
|
||||
});
|
||||
|
||||
it("mutes a connector thread until /unmute", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "connector-host-test-"));
|
||||
tempDirs.push(dir);
|
||||
const bindingsPath = join(dir, "threads.json");
|
||||
const { thread, posts } = createThread({
|
||||
enableTools: true,
|
||||
autoApproveTools: true,
|
||||
cwd: "/tmp/work",
|
||||
workspaceRoot: "/tmp/work",
|
||||
welcomeSentAt: new Date().toISOString(),
|
||||
});
|
||||
const runtime = createRuntimeClient("runtime reply");
|
||||
const commonInput = {
|
||||
thread: thread as never,
|
||||
client: runtime.client as never,
|
||||
pendingApprovals: new Map(),
|
||||
baseStartRequest: baseStartRequest() as never,
|
||||
explicitSystemPrompt: undefined,
|
||||
clientId: "client-1",
|
||||
logger: {
|
||||
core: { debug: vi.fn(), log: vi.fn(), error: vi.fn() },
|
||||
} as never,
|
||||
transport: "discord",
|
||||
botUserName: "ClineAdapterBot",
|
||||
requestStop: vi.fn(),
|
||||
bindingsPath,
|
||||
systemRules: "rules",
|
||||
errorLabel: "Discord",
|
||||
getSessionMetadata: () => ({}),
|
||||
reusedLogMessage: "reused",
|
||||
startedLogMessage: "started",
|
||||
postFinalReply: async ({ text }: { text: string }) => {
|
||||
posts.push(text);
|
||||
},
|
||||
};
|
||||
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
text: "/mute",
|
||||
});
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
text: "a bot keeps talking",
|
||||
});
|
||||
|
||||
expect(posts).toEqual([
|
||||
"Thread muted. I will ignore messages here until /unmute.",
|
||||
]);
|
||||
expect(runtime.startRuntimeSession).not.toHaveBeenCalled();
|
||||
expect(runtime.sendRuntimeSession).not.toHaveBeenCalled();
|
||||
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
text: "/unmute",
|
||||
});
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
text: "hello again",
|
||||
});
|
||||
|
||||
expect(posts.at(-2)).toBe("Thread unmuted.");
|
||||
expect(posts.at(-1)).toBe("runtime reply");
|
||||
expect(runtime.sendRuntimeSession).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("aborts active turns when muting a connector thread", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "connector-host-test-"));
|
||||
tempDirs.push(dir);
|
||||
const bindingsPath = join(dir, "threads.json");
|
||||
const { thread, posts } = createThread({
|
||||
enableTools: true,
|
||||
autoApproveTools: true,
|
||||
cwd: "/tmp/work",
|
||||
workspaceRoot: "/tmp/work",
|
||||
welcomeSentAt: new Date().toISOString(),
|
||||
});
|
||||
const runtime = createRuntimeClient("unused");
|
||||
const activeTurns = new Map([
|
||||
["other-participant", { sessionId: "session-1", threadId: "thread-1" }],
|
||||
]);
|
||||
|
||||
await handleConnectorUserTurn({
|
||||
thread: thread as never,
|
||||
text: "/mute",
|
||||
client: runtime.client as never,
|
||||
pendingApprovals: new Map(),
|
||||
baseStartRequest: baseStartRequest() as never,
|
||||
explicitSystemPrompt: undefined,
|
||||
clientId: "client-1",
|
||||
logger: {
|
||||
core: { debug: vi.fn(), log: vi.fn(), error: vi.fn() },
|
||||
} as never,
|
||||
transport: "discord",
|
||||
botUserName: "ClineAdapterBot",
|
||||
requestStop: vi.fn(),
|
||||
bindingsPath,
|
||||
systemRules: "rules",
|
||||
errorLabel: "Discord",
|
||||
getSessionMetadata: () => ({}),
|
||||
reusedLogMessage: "reused",
|
||||
startedLogMessage: "started",
|
||||
activeTurns,
|
||||
turnKey: "current-participant",
|
||||
});
|
||||
|
||||
expect(runtime.client.abortRuntimeSession).toHaveBeenCalledWith(
|
||||
"session-1",
|
||||
);
|
||||
expect(posts).toEqual([
|
||||
"Thread muted. I will ignore messages here until /unmute.",
|
||||
]);
|
||||
});
|
||||
|
||||
it("mutes a specific participant in the current connector thread", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "connector-host-test-"));
|
||||
tempDirs.push(dir);
|
||||
const bindingsPath = join(dir, "threads.json");
|
||||
const alice = createThread(
|
||||
{
|
||||
enableTools: true,
|
||||
autoApproveTools: true,
|
||||
cwd: "/tmp/work",
|
||||
workspaceRoot: "/tmp/work",
|
||||
participantKey: "discord:user:alice",
|
||||
participantLabel: "Alice",
|
||||
welcomeSentAt: new Date().toISOString(),
|
||||
},
|
||||
false,
|
||||
);
|
||||
const bob = createThread(
|
||||
{
|
||||
enableTools: true,
|
||||
autoApproveTools: true,
|
||||
cwd: "/tmp/work",
|
||||
workspaceRoot: "/tmp/work",
|
||||
participantKey: "discord:user:bob",
|
||||
participantLabel: "Bob",
|
||||
welcomeSentAt: new Date().toISOString(),
|
||||
},
|
||||
false,
|
||||
);
|
||||
const runtime = createRuntimeClient("runtime reply");
|
||||
const commonInput = {
|
||||
client: runtime.client as never,
|
||||
pendingApprovals: new Map(),
|
||||
baseStartRequest: baseStartRequest() as never,
|
||||
explicitSystemPrompt: undefined,
|
||||
clientId: "client-1",
|
||||
logger: {
|
||||
core: { debug: vi.fn(), log: vi.fn(), error: vi.fn() },
|
||||
} as never,
|
||||
transport: "discord",
|
||||
botUserName: "ClineAdapterBot",
|
||||
requestStop: vi.fn(),
|
||||
bindingsPath,
|
||||
systemRules: "rules",
|
||||
errorLabel: "Discord",
|
||||
getSessionMetadata: () => ({}),
|
||||
reusedLogMessage: "reused",
|
||||
startedLogMessage: "started",
|
||||
resolveMuteTarget: ({ target }: { target: string }) =>
|
||||
target === "<@bob>"
|
||||
? {
|
||||
participantKey: "discord:user:bob",
|
||||
participantLabel: "<@bob>",
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
thread: alice.thread as never,
|
||||
text: "/mute@ClineAdapterBot <@bob>",
|
||||
});
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
thread: bob.thread as never,
|
||||
text: "bob keeps talking",
|
||||
});
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
thread: alice.thread as never,
|
||||
text: "alice is still allowed",
|
||||
postFinalReply: async ({ text }: { text: string }) => {
|
||||
alice.posts.push(text);
|
||||
},
|
||||
});
|
||||
|
||||
expect(alice.posts[0]).toBe(
|
||||
"Muted <@bob> in this thread. I will ignore their messages until /unmute <@bob>.",
|
||||
);
|
||||
expect(bob.posts).toEqual([]);
|
||||
expect(alice.posts.at(-1)).toBe("runtime reply");
|
||||
expect(runtime.sendRuntimeSession).toHaveBeenCalledTimes(1);
|
||||
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
thread: alice.thread as never,
|
||||
text: "/unmute@ClineAdapterBot <@bob>",
|
||||
});
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
thread: bob.thread as never,
|
||||
text: "bob is back",
|
||||
postFinalReply: async ({ text }: { text: string }) => {
|
||||
bob.posts.push(text);
|
||||
},
|
||||
});
|
||||
|
||||
expect(alice.posts.at(-1)).toBe("Unmuted <@bob> in this thread.");
|
||||
expect(bob.posts.at(-1)).toBe("runtime reply");
|
||||
expect(runtime.sendRuntimeSession).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not report thread unmuted when only participant-specific mutes are active", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "connector-host-test-"));
|
||||
tempDirs.push(dir);
|
||||
const bindingsPath = join(dir, "threads.json");
|
||||
const alice = createThread(
|
||||
{
|
||||
enableTools: true,
|
||||
autoApproveTools: true,
|
||||
cwd: "/tmp/work",
|
||||
workspaceRoot: "/tmp/work",
|
||||
participantKey: "discord:user:alice",
|
||||
participantLabel: "Alice",
|
||||
welcomeSentAt: new Date().toISOString(),
|
||||
},
|
||||
false,
|
||||
);
|
||||
const bob = createThread(
|
||||
{
|
||||
enableTools: true,
|
||||
autoApproveTools: true,
|
||||
cwd: "/tmp/work",
|
||||
workspaceRoot: "/tmp/work",
|
||||
participantKey: "discord:user:bob",
|
||||
participantLabel: "Bob",
|
||||
welcomeSentAt: new Date().toISOString(),
|
||||
},
|
||||
false,
|
||||
);
|
||||
const runtime = createRuntimeClient("runtime reply");
|
||||
const commonInput = {
|
||||
client: runtime.client as never,
|
||||
pendingApprovals: new Map(),
|
||||
baseStartRequest: baseStartRequest() as never,
|
||||
explicitSystemPrompt: undefined,
|
||||
clientId: "client-1",
|
||||
logger: {
|
||||
core: { debug: vi.fn(), log: vi.fn(), error: vi.fn() },
|
||||
} as never,
|
||||
transport: "discord",
|
||||
botUserName: "ClineAdapterBot",
|
||||
requestStop: vi.fn(),
|
||||
bindingsPath,
|
||||
systemRules: "rules",
|
||||
errorLabel: "Discord",
|
||||
getSessionMetadata: () => ({}),
|
||||
reusedLogMessage: "reused",
|
||||
startedLogMessage: "started",
|
||||
resolveMuteTarget: ({ target }: { target: string }) =>
|
||||
target === "<@bob>"
|
||||
? {
|
||||
participantKey: "discord:user:bob",
|
||||
participantLabel: "<@bob>",
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
thread: alice.thread as never,
|
||||
text: "/mute@ClineAdapterBot <@bob>",
|
||||
});
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
thread: alice.thread as never,
|
||||
text: "/unmute@ClineAdapterBot",
|
||||
});
|
||||
await handleConnectorUserTurn({
|
||||
...commonInput,
|
||||
thread: bob.thread as never,
|
||||
text: "bob is still muted",
|
||||
postFinalReply: async ({ text }: { text: string }) => {
|
||||
bob.posts.push(text);
|
||||
},
|
||||
});
|
||||
|
||||
expect(alice.posts).toEqual([
|
||||
"Muted <@bob> in this thread. I will ignore their messages until /unmute <@bob>.",
|
||||
"No thread-level mute is active. Participant-specific mutes are still active for <@bob>. Use /unmute <target> to clear one.",
|
||||
]);
|
||||
expect(bob.posts).toEqual([]);
|
||||
expect(runtime.sendRuntimeSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("aborts active turns for a participant-specific mute", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "connector-host-test-"));
|
||||
tempDirs.push(dir);
|
||||
const bindingsPath = join(dir, "threads.json");
|
||||
const { thread, posts } = createThread({
|
||||
enableTools: true,
|
||||
autoApproveTools: true,
|
||||
cwd: "/tmp/work",
|
||||
workspaceRoot: "/tmp/work",
|
||||
participantKey: "discord:user:alice",
|
||||
welcomeSentAt: new Date().toISOString(),
|
||||
});
|
||||
const runtime = createRuntimeClient("unused");
|
||||
const activeTurns = new Map([
|
||||
[
|
||||
"discord:user:bob",
|
||||
{
|
||||
sessionId: "session-bob",
|
||||
threadId: "thread-1",
|
||||
participantKey: "discord:user:bob",
|
||||
},
|
||||
],
|
||||
[
|
||||
"discord:user:alice",
|
||||
{
|
||||
sessionId: "session-alice",
|
||||
threadId: "thread-1",
|
||||
participantKey: "discord:user:alice",
|
||||
},
|
||||
],
|
||||
]);
|
||||
|
||||
await handleConnectorUserTurn({
|
||||
thread: thread as never,
|
||||
text: "/mute <@bob>",
|
||||
client: runtime.client as never,
|
||||
pendingApprovals: new Map(),
|
||||
baseStartRequest: baseStartRequest() as never,
|
||||
explicitSystemPrompt: undefined,
|
||||
clientId: "client-1",
|
||||
logger: {
|
||||
core: { debug: vi.fn(), log: vi.fn(), error: vi.fn() },
|
||||
} as never,
|
||||
transport: "discord",
|
||||
botUserName: "ClineAdapterBot",
|
||||
requestStop: vi.fn(),
|
||||
bindingsPath,
|
||||
systemRules: "rules",
|
||||
errorLabel: "Discord",
|
||||
getSessionMetadata: () => ({}),
|
||||
reusedLogMessage: "reused",
|
||||
startedLogMessage: "started",
|
||||
activeTurns,
|
||||
resolveMuteTarget: () => ({
|
||||
participantKey: "discord:user:bob",
|
||||
participantLabel: "<@bob>",
|
||||
}),
|
||||
});
|
||||
|
||||
expect(runtime.client.abortRuntimeSession).toHaveBeenCalledTimes(1);
|
||||
expect(runtime.client.abortRuntimeSession).toHaveBeenCalledWith(
|
||||
"session-bob",
|
||||
);
|
||||
expect(posts).toEqual([
|
||||
"Muted <@bob> in this thread. I will ignore their messages until /unmute <@bob>.",
|
||||
]);
|
||||
});
|
||||
|
||||
it("posts adapter fallback replies when the runtime stream is empty", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "connector-host-test-"));
|
||||
tempDirs.push(dir);
|
||||
|
||||
@@ -12,8 +12,6 @@ import { buildUserInputMessage, resolveSystemPrompt } from "../runtime/prompt";
|
||||
import {
|
||||
type ChatCommandHost,
|
||||
type ChatCommandState,
|
||||
isCommandAddressedToBot,
|
||||
type MuteCommandInput,
|
||||
maybeHandleChatCommand,
|
||||
normalizeCommandName,
|
||||
} from "../utils/chat-commands";
|
||||
@@ -31,24 +29,15 @@ import {
|
||||
getOrCreateSessionId,
|
||||
} from "./session-runtime";
|
||||
import {
|
||||
type ConnectorMuteTarget,
|
||||
type ConnectorThreadState,
|
||||
findMutedParticipantsForThread,
|
||||
isParticipantMutedInBindings,
|
||||
isThreadMutedInBindings,
|
||||
loadThreadState,
|
||||
persistMergedThreadState,
|
||||
persistThreadBinding,
|
||||
readBindings,
|
||||
resolveThreadBindingKey,
|
||||
setParticipantMuted,
|
||||
setThreadMuted,
|
||||
} from "./thread-bindings";
|
||||
|
||||
export type ActiveConnectorTurn = {
|
||||
sessionId: string;
|
||||
threadId?: string;
|
||||
participantKey?: string;
|
||||
};
|
||||
|
||||
type EmptyRuntimeReplyResolver = () => Promise<string | undefined>;
|
||||
@@ -153,53 +142,6 @@ export function isConnectorIdleReply(text: string): boolean {
|
||||
return text.trim().toLowerCase() === "/idle";
|
||||
}
|
||||
|
||||
function resolveConnectorCommandName(
|
||||
text: string,
|
||||
botUserName: string | undefined,
|
||||
): string | undefined {
|
||||
const [commandToken = ""] = text.trim().split(/\s+/);
|
||||
if (!commandToken.startsWith("/")) {
|
||||
return undefined;
|
||||
}
|
||||
return normalizeCommandName(commandToken.toLowerCase(), botUserName);
|
||||
}
|
||||
|
||||
function getConnectorCommandToken(text: string): string | undefined {
|
||||
const [commandToken = ""] = text.trim().split(/\s+/);
|
||||
return commandToken.startsWith("/") ? commandToken : undefined;
|
||||
}
|
||||
|
||||
function isConnectorCommandAddressedToThisBot(
|
||||
text: string,
|
||||
botUserName: string | undefined,
|
||||
): boolean {
|
||||
const commandToken = getConnectorCommandToken(text);
|
||||
return commandToken
|
||||
? isCommandAddressedToBot(commandToken, botUserName)
|
||||
: false;
|
||||
}
|
||||
|
||||
function participantMatchesOwner(
|
||||
participantKey: string | undefined,
|
||||
ownerParticipantKeys: readonly string[] | undefined,
|
||||
): boolean {
|
||||
const normalizedParticipantKey = participantKey?.trim().toLowerCase();
|
||||
if (!normalizedParticipantKey) {
|
||||
return false;
|
||||
}
|
||||
return (ownerParticipantKeys ?? []).some(
|
||||
(key) => key.trim().toLowerCase() === normalizedParticipantKey,
|
||||
);
|
||||
}
|
||||
|
||||
function formatMuteTargetLabel(target: ConnectorMuteTarget): string {
|
||||
return target.participantLabel?.trim() || target.participantKey;
|
||||
}
|
||||
|
||||
function formatMuteTargetList(targets: ConnectorMuteTarget[]): string {
|
||||
return targets.map(formatMuteTargetLabel).join(", ");
|
||||
}
|
||||
|
||||
export async function handleConnectorUserTurn<
|
||||
TState extends ConnectorThreadState,
|
||||
>(input: {
|
||||
@@ -214,7 +156,6 @@ export async function handleConnectorUserTurn<
|
||||
logger: CliLoggerAdapter;
|
||||
transport: string;
|
||||
botUserName?: string;
|
||||
ownerParticipantKeys?: string[];
|
||||
requestStop: (reason: string) => void;
|
||||
bindingsPath: string;
|
||||
hookCommand?: string;
|
||||
@@ -233,14 +174,6 @@ export async function handleConnectorUserTurn<
|
||||
userInstructionService?: UserInstructionConfigService;
|
||||
activeTurns?: Map<string, ActiveConnectorTurn>;
|
||||
turnKey?: string;
|
||||
resolveMuteTarget?: (input: {
|
||||
target: string;
|
||||
thread: Thread<TState>;
|
||||
currentState: TState;
|
||||
}) =>
|
||||
| Promise<ConnectorMuteTarget | undefined>
|
||||
| ConnectorMuteTarget
|
||||
| undefined;
|
||||
forceDisableTools?: boolean;
|
||||
reusedLogMessage: string;
|
||||
startedLogMessage?: string;
|
||||
@@ -358,70 +291,6 @@ export async function handleConnectorUserTurn<
|
||||
);
|
||||
return;
|
||||
}
|
||||
const commandName = resolveConnectorCommandName(
|
||||
resolvedInput,
|
||||
input.botUserName,
|
||||
);
|
||||
const isConnectorCommand = commandName !== undefined;
|
||||
if (
|
||||
isConnectorCommand &&
|
||||
!input.thread.isDM &&
|
||||
!isConnectorCommandAddressedToThisBot(resolvedInput, input.botUserName)
|
||||
) {
|
||||
input.logger.core.log("Unaddressed connector chat command ignored", {
|
||||
transport: input.transport,
|
||||
threadId: input.thread.id,
|
||||
channelId: input.thread.channelId,
|
||||
participantKey: initialState.participantKey,
|
||||
textPreview: truncateConnectorText(resolvedInput),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (
|
||||
isConnectorCommand &&
|
||||
input.ownerParticipantKeys?.length &&
|
||||
!participantMatchesOwner(
|
||||
initialState.participantKey,
|
||||
input.ownerParticipantKeys,
|
||||
)
|
||||
) {
|
||||
await postConnectorText(
|
||||
input.thread,
|
||||
input.transport,
|
||||
"Only the connector owner can use slash commands.",
|
||||
);
|
||||
input.logger.core.log("Non-owner connector chat command denied", {
|
||||
transport: input.transport,
|
||||
threadId: input.thread.id,
|
||||
channelId: input.thread.channelId,
|
||||
participantKey: initialState.participantKey,
|
||||
ownerParticipantKeys: input.ownerParticipantKeys,
|
||||
textPreview: truncateConnectorText(resolvedInput),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const turnBindings = readBindings<TState>(input.bindingsPath);
|
||||
const threadMuted = isThreadMutedInBindings(turnBindings, input.thread);
|
||||
const participantMuted = isParticipantMutedInBindings(
|
||||
turnBindings,
|
||||
input.thread,
|
||||
initialState.participantKey,
|
||||
);
|
||||
if (
|
||||
(threadMuted || participantMuted) &&
|
||||
commandName !== "/unmute" &&
|
||||
commandName !== "/mute"
|
||||
) {
|
||||
input.logger.core.log("Muted connector thread message ignored", {
|
||||
transport: input.transport,
|
||||
threadId: input.thread.id,
|
||||
channelId: input.thread.channelId,
|
||||
participantKey: initialState.participantKey,
|
||||
muteScope: threadMuted ? "thread" : "participant",
|
||||
textPreview: truncateConnectorText(resolvedInput),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const turnKey =
|
||||
input.turnKey ||
|
||||
resolveThreadBindingKey(
|
||||
@@ -479,7 +348,11 @@ export async function handleConnectorUserTurn<
|
||||
}
|
||||
await input.onMessageReceived?.(receivedDetails);
|
||||
|
||||
const toolLockCommand = commandName?.match(/^\/(tools|yolo)$/i);
|
||||
const [commandToken = ""] = resolvedInput.trim().split(/\s+/);
|
||||
const toolLockCommand = normalizeCommandName(
|
||||
commandToken.toLowerCase(),
|
||||
input.botUserName,
|
||||
).match(/^\/(tools|yolo)$/i);
|
||||
if (input.forceDisableTools && toolLockCommand) {
|
||||
const settingName = toolLockCommand[1]?.toLowerCase();
|
||||
await postConnectorText(
|
||||
@@ -494,7 +367,6 @@ export async function handleConnectorUserTurn<
|
||||
await maybeHandleChatCommand(resolvedInput, {
|
||||
enabled: true,
|
||||
botUserName: input.botUserName,
|
||||
requireBotMention: !input.thread.isDM,
|
||||
host: input.chatCommandHost,
|
||||
getState: async () => {
|
||||
const current = await loadThreadState(
|
||||
@@ -520,7 +392,6 @@ export async function handleConnectorUserTurn<
|
||||
effectiveCurrent.workspaceRoot ||
|
||||
input.baseStartRequest.workspaceRoot,
|
||||
toolsLocked: input.forceDisableTools,
|
||||
threadMuted: isThreadMutedInBindings(turnBindings, input.thread),
|
||||
};
|
||||
},
|
||||
setState: async (next: ChatCommandState) => {
|
||||
@@ -626,90 +497,6 @@ export async function handleConnectorUserTurn<
|
||||
"Aborting current task.",
|
||||
);
|
||||
},
|
||||
mute: async (commandInput: MuteCommandInput) => {
|
||||
const target = commandInput.target?.trim()
|
||||
? await input.resolveMuteTarget?.({
|
||||
target: commandInput.target,
|
||||
thread: input.thread,
|
||||
currentState: initialState,
|
||||
})
|
||||
: undefined;
|
||||
if (commandInput.target?.trim() && !target) {
|
||||
return `Could not resolve mute target: ${commandInput.target.trim()}`;
|
||||
}
|
||||
const activeTurns = input.activeTurns
|
||||
? Array.from(input.activeTurns.entries()).filter(([key, turn]) =>
|
||||
target
|
||||
? key === target.participantKey ||
|
||||
turn.participantKey === target.participantKey
|
||||
: key === turnKey ||
|
||||
turn.threadId === input.thread.id ||
|
||||
(initialState.sessionId?.trim() &&
|
||||
turn.sessionId === initialState.sessionId.trim()),
|
||||
)
|
||||
: [];
|
||||
await Promise.allSettled(
|
||||
activeTurns.map(([, turn]) =>
|
||||
input.client.abortRuntimeSession(turn.sessionId),
|
||||
),
|
||||
);
|
||||
if (target) {
|
||||
setParticipantMuted(
|
||||
input.bindingsPath,
|
||||
input.thread,
|
||||
target,
|
||||
true,
|
||||
input.errorLabel,
|
||||
);
|
||||
return `Muted ${formatMuteTargetLabel(target)} in this thread. I will ignore their messages until /unmute ${formatMuteTargetLabel(target)}.`;
|
||||
}
|
||||
setThreadMuted(
|
||||
input.bindingsPath,
|
||||
input.thread,
|
||||
true,
|
||||
input.errorLabel,
|
||||
);
|
||||
return undefined;
|
||||
},
|
||||
unmute: async (commandInput: MuteCommandInput) => {
|
||||
const target = commandInput.target?.trim()
|
||||
? await input.resolveMuteTarget?.({
|
||||
target: commandInput.target,
|
||||
thread: input.thread,
|
||||
currentState: initialState,
|
||||
})
|
||||
: undefined;
|
||||
if (commandInput.target?.trim() && !target) {
|
||||
return `Could not resolve unmute target: ${commandInput.target.trim()}`;
|
||||
}
|
||||
if (target) {
|
||||
setParticipantMuted(
|
||||
input.bindingsPath,
|
||||
input.thread,
|
||||
target,
|
||||
false,
|
||||
input.errorLabel,
|
||||
);
|
||||
return `Unmuted ${formatMuteTargetLabel(target)} in this thread.`;
|
||||
}
|
||||
if (!threadMuted) {
|
||||
const mutedParticipants = findMutedParticipantsForThread(
|
||||
turnBindings,
|
||||
input.thread,
|
||||
);
|
||||
if (mutedParticipants.length > 0) {
|
||||
return `No thread-level mute is active. Participant-specific mutes are still active for ${formatMuteTargetList(mutedParticipants)}. Use /unmute <target> to clear one.`;
|
||||
}
|
||||
return "Thread is not muted.";
|
||||
}
|
||||
setThreadMuted(
|
||||
input.bindingsPath,
|
||||
input.thread,
|
||||
false,
|
||||
input.errorLabel,
|
||||
);
|
||||
return undefined;
|
||||
},
|
||||
stop: async () => {
|
||||
await clearSession({
|
||||
thread: input.thread,
|
||||
@@ -765,7 +552,6 @@ export async function handleConnectorUserTurn<
|
||||
`isDM=${input.thread.isDM ? "true" : "false"}`,
|
||||
`tools=${effectiveCurrent.enableTools ? "on" : "off"}`,
|
||||
`yolo=${effectiveCurrent.autoApproveTools ? "on" : "off"}`,
|
||||
`muted=${threadMuted ? "true" : "false"}`,
|
||||
`cwd=${effectiveCurrent.cwd || input.baseStartRequest.cwd}`,
|
||||
`workspaceRoot=${effectiveCurrent.workspaceRoot || input.baseStartRequest.workspaceRoot}`,
|
||||
].join("\n");
|
||||
@@ -971,11 +757,7 @@ export async function handleConnectorUserTurn<
|
||||
sessionId,
|
||||
});
|
||||
|
||||
input.activeTurns?.set(turnKey, {
|
||||
sessionId,
|
||||
threadId: input.thread.id,
|
||||
participantKey: currentState.participantKey,
|
||||
});
|
||||
input.activeTurns?.set(turnKey, { sessionId });
|
||||
await input.thread.startTyping();
|
||||
let toolStatusMessage: SentMessage | undefined;
|
||||
const postFinalReply = input.postFinalReply
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { CONNECTOR_CATALOG, listConnectorCatalog } from "./catalog";
|
||||
import type { ConnectCommandDefinition } from "./types";
|
||||
|
||||
type ConnectorRegistryEntry = {
|
||||
@@ -7,10 +6,6 @@ type ConnectorRegistryEntry = {
|
||||
load: () => Promise<ConnectCommandDefinition>;
|
||||
};
|
||||
|
||||
const connectorDescriptions = new Map(
|
||||
CONNECTOR_CATALOG.map((entry) => [entry.name, entry.description]),
|
||||
);
|
||||
|
||||
const registry = new Map<string, ConnectorRegistryEntry>([
|
||||
[
|
||||
"discord",
|
||||
@@ -25,7 +20,7 @@ const registry = new Map<string, ConnectorRegistryEntry>([
|
||||
"gchat",
|
||||
{
|
||||
name: "gchat",
|
||||
description: connectorDescriptions.get("gchat") ?? "Google Chat",
|
||||
description: "Google Chat webhook bridge backed by RPC runtime sessions",
|
||||
load: async () => (await import("./adapters/gchat")).gchatConnector,
|
||||
},
|
||||
],
|
||||
@@ -33,7 +28,7 @@ const registry = new Map<string, ConnectorRegistryEntry>([
|
||||
"linear",
|
||||
{
|
||||
name: "linear",
|
||||
description: connectorDescriptions.get("linear") ?? "Linear",
|
||||
description: "Linear webhook bridge backed by RPC runtime sessions",
|
||||
load: async () => (await import("./adapters/linear")).linearConnector,
|
||||
},
|
||||
],
|
||||
@@ -41,7 +36,7 @@ const registry = new Map<string, ConnectorRegistryEntry>([
|
||||
"slack",
|
||||
{
|
||||
name: "slack",
|
||||
description: connectorDescriptions.get("slack") ?? "Slack",
|
||||
description: "Slack webhook bridge backed by RPC runtime sessions",
|
||||
load: async () => (await import("./adapters/slack")).slackConnector,
|
||||
},
|
||||
],
|
||||
@@ -49,7 +44,7 @@ const registry = new Map<string, ConnectorRegistryEntry>([
|
||||
"telegram",
|
||||
{
|
||||
name: "telegram",
|
||||
description: connectorDescriptions.get("telegram") ?? "Telegram",
|
||||
description: "Bridge Telegram bot messages into RPC chat sessions",
|
||||
load: async () => (await import("./adapters/telegram")).telegramConnector,
|
||||
},
|
||||
],
|
||||
@@ -57,7 +52,7 @@ const registry = new Map<string, ConnectorRegistryEntry>([
|
||||
"whatsapp",
|
||||
{
|
||||
name: "whatsapp",
|
||||
description: connectorDescriptions.get("whatsapp") ?? "WhatsApp",
|
||||
description: "Bridge WhatsApp webhook messages into RPC chat sessions",
|
||||
load: async () => (await import("./adapters/whatsapp")).whatsappConnector,
|
||||
},
|
||||
],
|
||||
@@ -66,7 +61,10 @@ const registry = new Map<string, ConnectorRegistryEntry>([
|
||||
export function listConnectors(): Array<
|
||||
Pick<ConnectorRegistryEntry, "name" | "description">
|
||||
> {
|
||||
return listConnectorCatalog();
|
||||
return [...registry.values()].map(({ name, description }) => ({
|
||||
name,
|
||||
description,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getConnector(
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { resolveClineDataDir } from "@cline/core";
|
||||
|
||||
function isProcessRunning(pid: number): boolean {
|
||||
if (!Number.isInteger(pid) || pid <= 0) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export type ActiveConnectorRecord = {
|
||||
id: string;
|
||||
type: string;
|
||||
pid: number;
|
||||
hubUrl: string;
|
||||
startedAt?: string;
|
||||
applicationId?: string;
|
||||
botUsername?: string;
|
||||
userName?: string;
|
||||
phoneNumberId?: string;
|
||||
port?: number;
|
||||
baseUrl?: string;
|
||||
};
|
||||
|
||||
function listConnectorStatePaths(
|
||||
type: ActiveConnectorRecord["type"],
|
||||
): string[] {
|
||||
const dir = join(resolveClineDataDir(), "connectors", type);
|
||||
if (!existsSync(dir)) {
|
||||
return [];
|
||||
}
|
||||
return readdirSync(dir)
|
||||
.filter((name) => name.endsWith(".json") && !name.endsWith(".threads.json"))
|
||||
.map((name) => join(dir, name));
|
||||
}
|
||||
|
||||
function readJsonRecord(path: string): Record<string, unknown> | undefined {
|
||||
if (!existsSync(path)) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const raw = readFileSync(path, "utf8");
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
||||
return parsed as Record<string, unknown>;
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed connector state.
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
type ConnectorFieldKey = keyof Omit<
|
||||
ActiveConnectorRecord,
|
||||
"id" | "type" | "pid" | "hubUrl"
|
||||
>;
|
||||
|
||||
const connectorFieldExtractors: Record<
|
||||
ConnectorFieldKey,
|
||||
(p: Record<string, unknown>) => string | number | undefined
|
||||
> = {
|
||||
startedAt: (p) => (typeof p.startedAt === "string" ? p.startedAt : undefined),
|
||||
port: (p) => (typeof p.port === "number" ? p.port : undefined),
|
||||
baseUrl: (p) => (typeof p.baseUrl === "string" ? p.baseUrl : undefined),
|
||||
userName: (p) => (typeof p.userName === "string" ? p.userName : undefined),
|
||||
botUsername: (p) =>
|
||||
typeof p.botUsername === "string" ? p.botUsername : undefined,
|
||||
applicationId: (p) =>
|
||||
typeof p.applicationId === "string" ? p.applicationId : undefined,
|
||||
phoneNumberId: (p) =>
|
||||
typeof p.phoneNumberId === "string" ? p.phoneNumberId : undefined,
|
||||
};
|
||||
|
||||
const connectorConfigs: Record<
|
||||
string,
|
||||
{ required: ConnectorFieldKey[]; optional: ConnectorFieldKey[] }
|
||||
> = {
|
||||
discord: {
|
||||
required: ["userName", "applicationId"],
|
||||
optional: ["startedAt", "port", "baseUrl"],
|
||||
},
|
||||
telegram: { required: ["botUsername"], optional: ["startedAt"] },
|
||||
gchat: { required: ["userName"], optional: ["startedAt", "port", "baseUrl"] },
|
||||
linear: {
|
||||
required: ["userName"],
|
||||
optional: ["startedAt", "port", "baseUrl"],
|
||||
},
|
||||
slack: { required: ["userName"], optional: ["startedAt", "port", "baseUrl"] },
|
||||
whatsapp: {
|
||||
required: ["userName"],
|
||||
optional: ["startedAt", "phoneNumberId", "port", "baseUrl"],
|
||||
},
|
||||
};
|
||||
|
||||
function connectorRecordId(
|
||||
type: ActiveConnectorRecord["type"],
|
||||
fields: Partial<
|
||||
Omit<ActiveConnectorRecord, "id" | "type" | "pid" | "hubUrl">
|
||||
>,
|
||||
pid: number,
|
||||
): string {
|
||||
const identity =
|
||||
fields.botUsername ??
|
||||
fields.userName ??
|
||||
fields.applicationId ??
|
||||
fields.phoneNumberId ??
|
||||
String(pid);
|
||||
return `${type}:${identity}`;
|
||||
}
|
||||
|
||||
function readActiveConnectorRecord(
|
||||
type: ActiveConnectorRecord["type"],
|
||||
statePath: string,
|
||||
): ActiveConnectorRecord | undefined {
|
||||
const parsed = readJsonRecord(statePath);
|
||||
if (!parsed) {
|
||||
return undefined;
|
||||
}
|
||||
const pid = typeof parsed.pid === "number" ? parsed.pid : undefined;
|
||||
const hubUrl =
|
||||
typeof parsed.hubUrl === "string"
|
||||
? parsed.hubUrl
|
||||
: typeof parsed.rpcAddress === "string"
|
||||
? parsed.rpcAddress
|
||||
: undefined;
|
||||
if (!pid || !hubUrl || !isProcessRunning(pid)) {
|
||||
return undefined;
|
||||
}
|
||||
const config = connectorConfigs[type];
|
||||
if (!config) {
|
||||
return undefined;
|
||||
}
|
||||
const fields: Partial<
|
||||
Omit<ActiveConnectorRecord, "id" | "type" | "pid" | "hubUrl">
|
||||
> = {};
|
||||
for (const key of config.required) {
|
||||
const value = connectorFieldExtractors[key](parsed);
|
||||
if (!value || (typeof value === "string" && !value.trim())) {
|
||||
return undefined;
|
||||
}
|
||||
(fields as Record<string, unknown>)[key] = value;
|
||||
}
|
||||
for (const key of config.optional) {
|
||||
const value = connectorFieldExtractors[key](parsed);
|
||||
if (value !== undefined) {
|
||||
(fields as Record<string, unknown>)[key] = value;
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: connectorRecordId(type, fields, pid),
|
||||
type,
|
||||
pid,
|
||||
hubUrl,
|
||||
...fields,
|
||||
} as ActiveConnectorRecord;
|
||||
}
|
||||
|
||||
export function listActiveConnectors(): ActiveConnectorRecord[] {
|
||||
const connectorTypes: ActiveConnectorRecord["type"][] = [
|
||||
"discord",
|
||||
"telegram",
|
||||
"gchat",
|
||||
"linear",
|
||||
"slack",
|
||||
"whatsapp",
|
||||
];
|
||||
const records: ActiveConnectorRecord[] = [];
|
||||
for (const type of connectorTypes) {
|
||||
for (const statePath of listConnectorStatePaths(type)) {
|
||||
const record = readActiveConnectorRecord(type, statePath);
|
||||
if (record) {
|
||||
records.push(record);
|
||||
}
|
||||
}
|
||||
}
|
||||
return records.sort((left, right) => {
|
||||
if (left.type !== right.type) {
|
||||
return left.type.localeCompare(right.type);
|
||||
}
|
||||
const leftName = left.botUsername ?? left.userName ?? "";
|
||||
const rightName = right.botUsername ?? right.userName ?? "";
|
||||
return leftName.localeCompare(rightName);
|
||||
});
|
||||
}
|
||||
@@ -4,14 +4,9 @@ import { join } from "node:path";
|
||||
import type { Thread } from "chat";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
clearBindingSessionIds,
|
||||
type ConnectorThreadState,
|
||||
isParticipantMuted,
|
||||
isThreadMuted,
|
||||
readBindingForThread,
|
||||
readBindings,
|
||||
setParticipantMuted,
|
||||
setThreadMuted,
|
||||
writeBindings,
|
||||
} from "./thread-bindings";
|
||||
|
||||
@@ -124,129 +119,4 @@ describe("thread binding refresh", () => {
|
||||
readBindings<TestState>(path)[participantKey]?.serializedThread,
|
||||
).toContain("new_thread_id");
|
||||
});
|
||||
|
||||
it("stores mute state at thread scope instead of participant scope", () => {
|
||||
const path = createBindingsPath();
|
||||
const thread = createThread({
|
||||
id: "thread-1",
|
||||
channelId: "discord:guild:channel",
|
||||
isDM: false,
|
||||
participantKey: "discord:user:alice",
|
||||
});
|
||||
|
||||
setThreadMuted(path, thread, true, "Discord");
|
||||
|
||||
expect(
|
||||
isThreadMuted(
|
||||
path,
|
||||
createThread({
|
||||
id: "thread-1",
|
||||
channelId: "discord:guild:channel",
|
||||
isDM: false,
|
||||
participantKey: "discord:user:bob",
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
const binding = readBindingForThread<TestState>(
|
||||
path,
|
||||
thread,
|
||||
"Discord",
|
||||
"discord:user:alice",
|
||||
);
|
||||
expect(binding).toBeUndefined();
|
||||
|
||||
setThreadMuted(path, thread, false, "Discord");
|
||||
|
||||
expect(isThreadMuted(path, thread)).toBe(false);
|
||||
});
|
||||
|
||||
it("stores participant mute state scoped to the current thread", () => {
|
||||
const path = createBindingsPath();
|
||||
const thread = createThread({
|
||||
id: "thread-1",
|
||||
channelId: "discord:guild:channel",
|
||||
isDM: false,
|
||||
});
|
||||
const otherThread = createThread({
|
||||
id: "thread-2",
|
||||
channelId: "discord:guild:channel",
|
||||
isDM: false,
|
||||
});
|
||||
|
||||
setParticipantMuted(
|
||||
path,
|
||||
thread,
|
||||
{
|
||||
participantKey: "discord:user:bob",
|
||||
participantLabel: "Bob",
|
||||
},
|
||||
true,
|
||||
"Discord",
|
||||
);
|
||||
|
||||
expect(isParticipantMuted(path, thread, "discord:user:bob")).toBe(true);
|
||||
expect(isParticipantMuted(path, thread, "discord:user:alice")).toBe(false);
|
||||
expect(isParticipantMuted(path, otherThread, "discord:user:bob")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
readBindingForThread<TestState>(
|
||||
path,
|
||||
thread,
|
||||
"Discord",
|
||||
"discord:user:bob",
|
||||
),
|
||||
).toBeUndefined();
|
||||
|
||||
setParticipantMuted(
|
||||
path,
|
||||
thread,
|
||||
{ participantKey: "discord:user:bob" },
|
||||
false,
|
||||
"Discord",
|
||||
);
|
||||
|
||||
expect(isParticipantMuted(path, thread, "discord:user:bob")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearBindingSessionIds", () => {
|
||||
it("clears session ids from bindings and serialized thread state", () => {
|
||||
const path = createBindingsPath();
|
||||
writeBindings<TestState>(path, {
|
||||
thread_1: {
|
||||
channelId: "discord:C123",
|
||||
isDM: false,
|
||||
serializedThread: JSON.stringify({
|
||||
id: "thread_1",
|
||||
channelId: "discord:C123",
|
||||
isDM: false,
|
||||
sessionId: "legacy-root-session",
|
||||
state: {
|
||||
sessionId: "sess-1",
|
||||
cwd: "/tmp/work",
|
||||
teamId: "T123",
|
||||
},
|
||||
}),
|
||||
sessionId: "sess-1",
|
||||
state: { sessionId: "sess-1", cwd: "/tmp/work", teamId: "T123" },
|
||||
updatedAt: "2026-03-17T00:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
clearBindingSessionIds<TestState>(path);
|
||||
|
||||
const binding = readBindings<TestState>(path).thread_1;
|
||||
expect(binding?.sessionId).toBeUndefined();
|
||||
expect(binding?.state?.sessionId).toBeUndefined();
|
||||
expect(binding?.state?.cwd).toBe("/tmp/work");
|
||||
const serializedThread = JSON.parse(binding?.serializedThread ?? "{}") as {
|
||||
sessionId?: string;
|
||||
state?: TestState;
|
||||
};
|
||||
expect(serializedThread.sessionId).toBeUndefined();
|
||||
expect(serializedThread.state?.sessionId).toBeUndefined();
|
||||
expect(serializedThread.state?.cwd).toBe("/tmp/work");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,15 +14,10 @@ export type ConnectorThreadState = {
|
||||
};
|
||||
|
||||
export type ConnectorThreadBinding<TState extends ConnectorThreadState> = {
|
||||
kind?: "participant" | "thread" | "thread-participant-mute";
|
||||
channelId: string;
|
||||
isDM: boolean;
|
||||
participantKey?: string;
|
||||
participantLabel?: string;
|
||||
threadMutedAt?: string;
|
||||
mutedParticipantKey?: string;
|
||||
mutedParticipantLabel?: string;
|
||||
participantMutedAt?: string;
|
||||
serializedThread: string;
|
||||
sessionId?: string;
|
||||
state?: TState;
|
||||
@@ -46,11 +41,6 @@ export type ConnectorBindingThreadIdentity = Pick<
|
||||
participantKey?: string;
|
||||
};
|
||||
|
||||
export type ConnectorMuteTarget = {
|
||||
participantKey: string;
|
||||
participantLabel?: string;
|
||||
};
|
||||
|
||||
function normalizeParticipantKey(
|
||||
value: string | undefined,
|
||||
): string | undefined {
|
||||
@@ -74,63 +64,6 @@ function readSerializedThreadIdentity(
|
||||
}
|
||||
}
|
||||
|
||||
function resolveThreadControlKey(
|
||||
thread: ConnectorBindingThreadIdentity,
|
||||
): string {
|
||||
return `thread:${thread.id}`;
|
||||
}
|
||||
|
||||
function resolveParticipantMuteControlKey(
|
||||
thread: ConnectorBindingThreadIdentity,
|
||||
participantKey: string | undefined,
|
||||
): string | undefined {
|
||||
const normalized = normalizeParticipantKey(participantKey);
|
||||
return normalized
|
||||
? `thread:${thread.id}:participant:${normalized}`
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function isControlBinding(
|
||||
binding: ConnectorThreadBinding<ConnectorThreadState> | undefined,
|
||||
): boolean {
|
||||
return (
|
||||
binding?.kind === "thread" || binding?.kind === "thread-participant-mute"
|
||||
);
|
||||
}
|
||||
|
||||
function clearSerializedThreadSessionId(
|
||||
serializedThread: string | undefined,
|
||||
): { serializedThread: string | undefined; updated: boolean } {
|
||||
if (!serializedThread?.trim()) {
|
||||
return { serializedThread, updated: false };
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(serializedThread) as unknown;
|
||||
if (!parsed || typeof parsed !== "object") {
|
||||
return { serializedThread, updated: false };
|
||||
}
|
||||
const record = parsed as Record<string, unknown>;
|
||||
let updated = false;
|
||||
if ("sessionId" in record) {
|
||||
delete record.sessionId;
|
||||
updated = true;
|
||||
}
|
||||
if (record.state && typeof record.state === "object") {
|
||||
const state = record.state as Record<string, unknown>;
|
||||
if ("sessionId" in state) {
|
||||
delete state.sessionId;
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
return {
|
||||
serializedThread: updated ? JSON.stringify(parsed) : serializedThread,
|
||||
updated,
|
||||
};
|
||||
} catch {
|
||||
return { serializedThread, updated: false };
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveThreadBindingKey(
|
||||
thread: ConnectorBindingThreadIdentity,
|
||||
state?: ConnectorThreadState | null,
|
||||
@@ -165,21 +98,14 @@ export function findBindingForThread<TState extends ConnectorThreadState>(
|
||||
const exactThreadParticipantKey = normalizeParticipantKey(
|
||||
exactThread?.participantKey ?? exactThread?.state?.participantKey,
|
||||
);
|
||||
if (
|
||||
exactThread &&
|
||||
!isControlBinding(exactThread) &&
|
||||
exactThreadParticipantKey === participantKey
|
||||
) {
|
||||
if (exactThread && exactThreadParticipantKey === participantKey) {
|
||||
return { key: thread.id, binding: exactThread };
|
||||
}
|
||||
const exactParticipant = bindings[participantKey];
|
||||
if (exactParticipant && !isControlBinding(exactParticipant)) {
|
||||
if (exactParticipant) {
|
||||
return { key: participantKey, binding: exactParticipant };
|
||||
}
|
||||
for (const [key, binding] of Object.entries(bindings)) {
|
||||
if (isControlBinding(binding)) {
|
||||
continue;
|
||||
}
|
||||
const bindingParticipantKey = normalizeParticipantKey(
|
||||
binding.participantKey ?? binding.state?.participantKey,
|
||||
);
|
||||
@@ -190,13 +116,10 @@ export function findBindingForThread<TState extends ConnectorThreadState>(
|
||||
return undefined;
|
||||
}
|
||||
const exact = bindings[thread.id];
|
||||
if (exact && !isControlBinding(exact)) {
|
||||
if (exact) {
|
||||
return { key: thread.id, binding: exact };
|
||||
}
|
||||
for (const [key, binding] of Object.entries(bindings)) {
|
||||
if (isControlBinding(binding)) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
binding.channelId === thread.channelId &&
|
||||
binding.isDM === thread.isDM
|
||||
@@ -282,9 +205,6 @@ export function persistThreadBinding<TState extends ConnectorThreadState>(
|
||||
state,
|
||||
);
|
||||
for (const [key, binding] of Object.entries(bindings)) {
|
||||
if (isControlBinding(binding)) {
|
||||
continue;
|
||||
}
|
||||
const bindingParticipantKey = normalizeParticipantKey(
|
||||
binding.participantKey ?? binding.state?.participantKey,
|
||||
);
|
||||
@@ -303,7 +223,6 @@ export function persistThreadBinding<TState extends ConnectorThreadState>(
|
||||
}
|
||||
}
|
||||
bindings[bindingKey] = {
|
||||
kind: "participant",
|
||||
channelId: thread.channelId,
|
||||
isDM: thread.isDM,
|
||||
participantKey,
|
||||
@@ -316,139 +235,6 @@ export function persistThreadBinding<TState extends ConnectorThreadState>(
|
||||
writeBindings(path, bindings);
|
||||
}
|
||||
|
||||
export function isThreadMuted<TState extends ConnectorThreadState>(
|
||||
path: string,
|
||||
thread: ConnectorBindingThreadIdentity,
|
||||
): boolean {
|
||||
const bindings = readBindings<TState>(path);
|
||||
return isThreadMutedInBindings(bindings, thread);
|
||||
}
|
||||
|
||||
export function isThreadMutedInBindings<TState extends ConnectorThreadState>(
|
||||
bindings: ConnectorBindingStore<TState>,
|
||||
thread: ConnectorBindingThreadIdentity,
|
||||
): boolean {
|
||||
const binding = bindings[resolveThreadControlKey(thread)];
|
||||
return Boolean(binding?.threadMutedAt);
|
||||
}
|
||||
|
||||
export function isParticipantMuted<TState extends ConnectorThreadState>(
|
||||
path: string,
|
||||
thread: ConnectorBindingThreadIdentity,
|
||||
participantKey: string | undefined,
|
||||
): boolean {
|
||||
const key = resolveParticipantMuteControlKey(thread, participantKey);
|
||||
if (!key) {
|
||||
return false;
|
||||
}
|
||||
const bindings = readBindings<TState>(path);
|
||||
return isParticipantMutedInBindings(bindings, thread, participantKey);
|
||||
}
|
||||
|
||||
export function isParticipantMutedInBindings<
|
||||
TState extends ConnectorThreadState,
|
||||
>(
|
||||
bindings: ConnectorBindingStore<TState>,
|
||||
thread: ConnectorBindingThreadIdentity,
|
||||
participantKey: string | undefined,
|
||||
): boolean {
|
||||
const key = resolveParticipantMuteControlKey(thread, participantKey);
|
||||
if (!key) {
|
||||
return false;
|
||||
}
|
||||
const binding = bindings[key];
|
||||
return Boolean(binding?.participantMutedAt);
|
||||
}
|
||||
|
||||
export function findMutedParticipantsForThread<
|
||||
TState extends ConnectorThreadState,
|
||||
>(
|
||||
bindings: ConnectorBindingStore<TState>,
|
||||
thread: ConnectorBindingThreadIdentity,
|
||||
): ConnectorMuteTarget[] {
|
||||
const prefix = `thread:${thread.id}:participant:`;
|
||||
return Object.entries(bindings)
|
||||
.filter(
|
||||
([key, binding]) =>
|
||||
key.startsWith(prefix) &&
|
||||
binding.kind === "thread-participant-mute" &&
|
||||
Boolean(binding.participantMutedAt) &&
|
||||
Boolean(normalizeParticipantKey(binding.mutedParticipantKey)),
|
||||
)
|
||||
.map(([, binding]) => ({
|
||||
participantKey:
|
||||
normalizeParticipantKey(binding.mutedParticipantKey) ?? "",
|
||||
participantLabel: binding.mutedParticipantLabel,
|
||||
}))
|
||||
.filter((target) => target.participantKey.length > 0);
|
||||
}
|
||||
|
||||
export function setThreadMuted<TState extends ConnectorThreadState>(
|
||||
path: string,
|
||||
thread: Thread<TState>,
|
||||
muted: boolean,
|
||||
errorLabel: string,
|
||||
): string | undefined {
|
||||
const bindings = readBindings<TState>(path);
|
||||
const key = resolveThreadControlKey(thread as ConnectorBindingThreadIdentity);
|
||||
if (!muted) {
|
||||
if (bindings[key]) {
|
||||
delete bindings[key];
|
||||
writeBindings(path, bindings);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
const mutedAt = new Date().toISOString();
|
||||
bindings[key] = {
|
||||
kind: "thread",
|
||||
channelId: thread.channelId,
|
||||
isDM: thread.isDM,
|
||||
threadMutedAt: mutedAt,
|
||||
serializedThread: serializeThread(thread, errorLabel),
|
||||
updatedAt: mutedAt,
|
||||
};
|
||||
writeBindings(path, bindings);
|
||||
return mutedAt;
|
||||
}
|
||||
|
||||
export function setParticipantMuted<TState extends ConnectorThreadState>(
|
||||
path: string,
|
||||
thread: Thread<TState>,
|
||||
target: ConnectorMuteTarget,
|
||||
muted: boolean,
|
||||
errorLabel: string,
|
||||
): string | undefined {
|
||||
const normalized = normalizeParticipantKey(target.participantKey);
|
||||
const key = resolveParticipantMuteControlKey(
|
||||
thread as ConnectorBindingThreadIdentity,
|
||||
normalized,
|
||||
);
|
||||
if (!normalized || !key) {
|
||||
return undefined;
|
||||
}
|
||||
const bindings = readBindings<TState>(path);
|
||||
if (!muted) {
|
||||
if (bindings[key]) {
|
||||
delete bindings[key];
|
||||
writeBindings(path, bindings);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
const mutedAt = new Date().toISOString();
|
||||
bindings[key] = {
|
||||
kind: "thread-participant-mute",
|
||||
channelId: thread.channelId,
|
||||
isDM: thread.isDM,
|
||||
mutedParticipantKey: normalized,
|
||||
mutedParticipantLabel: target.participantLabel?.trim() || undefined,
|
||||
participantMutedAt: mutedAt,
|
||||
serializedThread: serializeThread(thread, errorLabel),
|
||||
updatedAt: mutedAt,
|
||||
};
|
||||
writeBindings(path, bindings);
|
||||
return mutedAt;
|
||||
}
|
||||
|
||||
export function mergeThreadState<TState extends ConnectorThreadState>(
|
||||
threadState: TState | null | undefined,
|
||||
bindingState: TState | undefined,
|
||||
@@ -548,17 +334,11 @@ export function clearBindingSessionIds<TState extends ConnectorThreadState>(
|
||||
const bindings = readBindings<TState>(path);
|
||||
let updated = false;
|
||||
for (const binding of Object.values(bindings)) {
|
||||
if ("sessionId" in binding) {
|
||||
delete binding.sessionId;
|
||||
updated = true;
|
||||
}
|
||||
if (binding.state && "sessionId" in binding.state) {
|
||||
delete binding.state.sessionId;
|
||||
updated = true;
|
||||
}
|
||||
const serialized = clearSerializedThreadSessionId(binding.serializedThread);
|
||||
if (serialized.updated) {
|
||||
binding.serializedThread = serialized.serializedThread ?? "";
|
||||
if (binding.sessionId || binding.state?.sessionId) {
|
||||
binding.sessionId = undefined;
|
||||
if (binding.state) {
|
||||
binding.state.sessionId = undefined;
|
||||
}
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { DialogActions, DialogId } from "@opentui-ui/dialog/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DialogActions, DialogId } from "@opentui-ui/dialog/react";
|
||||
import { withShownDialog } from "./loading-dialog-lifecycle";
|
||||
|
||||
type LoadingDialogCall =
|
||||
|
||||
@@ -769,7 +769,7 @@ export function OAuthLoginContent(
|
||||
</text>
|
||||
<text fg="gray">Visit this URL and enter the code above:</text>
|
||||
<text fg="cyan" selectable>
|
||||
<a href={deviceVerifyUrl}>{deviceVerifyUrl}</a>
|
||||
{deviceVerifyUrl}
|
||||
</text>
|
||||
</box>
|
||||
)}
|
||||
@@ -793,7 +793,7 @@ export function OAuthLoginContent(
|
||||
|
||||
{authUrl && (
|
||||
<text fg="gray" selectable>
|
||||
<a href={authUrl}>{authUrl}</a>
|
||||
{authUrl}
|
||||
</text>
|
||||
)}
|
||||
|
||||
|
||||
@@ -158,48 +158,42 @@ async function runProviderChange(
|
||||
}
|
||||
if (!saved) return false;
|
||||
}
|
||||
await withLoadingDialog(
|
||||
dialog,
|
||||
`Loading ${displayName} models...`,
|
||||
async () => {
|
||||
await refreshProviderModelsFromSource(manager, newProviderId).catch(
|
||||
() => {},
|
||||
);
|
||||
const newSettings = manager.getProviderSettings(newProviderId);
|
||||
const newApiKey =
|
||||
getPersistedProviderApiKey(newProviderId, newSettings) ?? "";
|
||||
await withLoadingDialog(dialog, `Loading ${displayName} models...`, async () => {
|
||||
await refreshProviderModelsFromSource(manager, newProviderId).catch(() => {});
|
||||
const newSettings = manager.getProviderSettings(newProviderId);
|
||||
const newApiKey =
|
||||
getPersistedProviderApiKey(newProviderId, newSettings) ?? "";
|
||||
|
||||
manager.saveProviderSettings(
|
||||
{
|
||||
...(newSettings ?? {}),
|
||||
provider: newProviderId,
|
||||
},
|
||||
{ setLastUsed: true },
|
||||
);
|
||||
manager.saveProviderSettings(
|
||||
{
|
||||
...(newSettings ?? {}),
|
||||
provider: newProviderId,
|
||||
},
|
||||
{ setLastUsed: true },
|
||||
);
|
||||
|
||||
config.providerId = newProviderId;
|
||||
config.apiKey = newApiKey;
|
||||
config.providerId = newProviderId;
|
||||
config.apiKey = newApiKey;
|
||||
|
||||
const resolved = await resolveProviderConfig(
|
||||
newProviderId,
|
||||
{
|
||||
loadLatestOnInit: true,
|
||||
loadPrivateOnAuth: true,
|
||||
failOnError: false,
|
||||
},
|
||||
manager.getProviderConfig(newProviderId, { includeKnownModels: false }),
|
||||
);
|
||||
config.knownModels = resolved?.knownModels;
|
||||
const modelIds = Object.keys(resolved?.knownModels ?? {});
|
||||
if (newSettings?.model) {
|
||||
config.modelId = newSettings.model;
|
||||
} else if (modelIds[0]) {
|
||||
config.modelId = modelIds[0];
|
||||
}
|
||||
const resolved = await resolveProviderConfig(
|
||||
newProviderId,
|
||||
{
|
||||
loadLatestOnInit: true,
|
||||
loadPrivateOnAuth: true,
|
||||
failOnError: false,
|
||||
},
|
||||
manager.getProviderConfig(newProviderId, { includeKnownModels: false }),
|
||||
);
|
||||
config.knownModels = resolved?.knownModels;
|
||||
const modelIds = Object.keys(resolved?.knownModels ?? {});
|
||||
if (newSettings?.model) {
|
||||
config.modelId = newSettings.model;
|
||||
} else if (modelIds[0]) {
|
||||
config.modelId = modelIds[0];
|
||||
}
|
||||
|
||||
await onModelChange();
|
||||
},
|
||||
);
|
||||
await onModelChange();
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ import {
|
||||
ChatMessageList,
|
||||
type TranscriptScrollHandle,
|
||||
} from "../components/chat-message-list";
|
||||
import { InlineToolResponse } from "../components/inline-tool-response";
|
||||
import { InputBar, type TextareaHandle } from "../components/input-bar";
|
||||
import { InlineToolResponse } from "../components/inline-tool-response";
|
||||
import { QueuedPrompts } from "../components/queued-prompts";
|
||||
import {
|
||||
resolveModelDisplayName,
|
||||
|
||||
@@ -127,7 +127,7 @@ export function OnboardingOAuthPendingScreen(props: {
|
||||
>
|
||||
<text fg="gray">If the browser didn't open:</text>
|
||||
<text fg={palette.act} marginTop={1} selectable>
|
||||
<a href={props.authUrl}>{props.authUrl}</a>
|
||||
{props.authUrl}
|
||||
</text>
|
||||
</box>
|
||||
)}
|
||||
@@ -194,7 +194,7 @@ export function OnboardingDeviceCodeScreen(props: {
|
||||
Visit this URL and enter the code above:
|
||||
</text>
|
||||
<text fg={palette.act} selectable>
|
||||
<a href={props.deviceVerifyUrl}>{props.deviceVerifyUrl}</a>
|
||||
{props.deviceVerifyUrl}
|
||||
</text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
createChatCommandHost,
|
||||
isCommandAddressedToBot,
|
||||
maybeHandleChatCommand,
|
||||
normalizeCommandName,
|
||||
} from "./chat-commands";
|
||||
import { createChatCommandHost, maybeHandleChatCommand } from "./chat-commands";
|
||||
|
||||
describe("chat commands", () => {
|
||||
it("shows connector help for /help and /start", async () => {
|
||||
@@ -69,46 +64,6 @@ describe("chat commands", () => {
|
||||
expect(reply).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires a bot suffix when requested", async () => {
|
||||
const reply = vi.fn(async () => undefined);
|
||||
const context = {
|
||||
enabled: true,
|
||||
botUserName: "clinebot",
|
||||
requireBotMention: true,
|
||||
getState: async () => ({
|
||||
enableTools: true,
|
||||
autoApproveTools: false,
|
||||
cwd: "/tmp",
|
||||
workspaceRoot: "/tmp",
|
||||
}),
|
||||
setState: async () => undefined,
|
||||
reply,
|
||||
};
|
||||
|
||||
expect(await maybeHandleChatCommand("/help", context)).toBe(false);
|
||||
expect(reply).not.toHaveBeenCalled();
|
||||
|
||||
expect(await maybeHandleChatCommand("/help@clinebot", context)).toBe(true);
|
||||
expect(reply).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Cline connector commands:"),
|
||||
);
|
||||
});
|
||||
|
||||
it("detects commands addressed to the configured bot", () => {
|
||||
expect(isCommandAddressedToBot("/new@clinebot", "clinebot")).toBe(true);
|
||||
expect(isCommandAddressedToBot("/new@cline_bot", "@cline_bot")).toBe(true);
|
||||
expect(isCommandAddressedToBot("/new@cline.bot", "cline.bot")).toBe(true);
|
||||
expect(isCommandAddressedToBot("/new@cline-bot", "cline-bot")).toBe(true);
|
||||
expect(isCommandAddressedToBot("/new", "clinebot")).toBe(false);
|
||||
expect(isCommandAddressedToBot("/new@otherbot", "clinebot")).toBe(false);
|
||||
expect(isCommandAddressedToBot("/new@clinebot", undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it("normalizes commands addressed to dotted and hyphenated bot names", () => {
|
||||
expect(normalizeCommandName("/new@cline.bot", "cline.bot")).toBe("/new");
|
||||
expect(normalizeCommandName("/new@cline-bot", "cline-bot")).toBe("/new");
|
||||
});
|
||||
|
||||
it("leaves bot-suffixed commands unmatched without a known bot username", async () => {
|
||||
const reply = vi.fn(async () => undefined);
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ export type ChatCommandState = {
|
||||
cwd: string;
|
||||
workspaceRoot: string;
|
||||
toolsLocked?: boolean;
|
||||
threadMuted?: boolean;
|
||||
};
|
||||
|
||||
export type ForkSessionResult = {
|
||||
@@ -16,14 +15,9 @@ export type ForkSessionResult = {
|
||||
newSessionId: string;
|
||||
};
|
||||
|
||||
export type MuteCommandInput = {
|
||||
target?: string;
|
||||
};
|
||||
|
||||
export type ChatCommandContext = {
|
||||
enabled: boolean;
|
||||
botUserName?: string;
|
||||
requireBotMention?: boolean;
|
||||
host?: ChatCommandHost;
|
||||
getState: () => Promise<ChatCommandState> | ChatCommandState;
|
||||
setState: (next: ChatCommandState) => Promise<void> | void;
|
||||
@@ -31,12 +25,6 @@ export type ChatCommandContext = {
|
||||
reset?: () => Promise<void> | void;
|
||||
abort?: () => Promise<void> | void;
|
||||
stop?: () => Promise<void> | void;
|
||||
mute?: (
|
||||
input: MuteCommandInput,
|
||||
) => Promise<string | undefined> | string | undefined;
|
||||
unmute?: (
|
||||
input: MuteCommandInput,
|
||||
) => Promise<string | undefined> | string | undefined;
|
||||
describe?: () => Promise<string> | string;
|
||||
fork?: () =>
|
||||
| Promise<ForkSessionResult | undefined>
|
||||
@@ -105,12 +93,6 @@ export class ChatCommandHost {
|
||||
}
|
||||
|
||||
const [commandRaw, ...args] = trimmed.split(/\s+/);
|
||||
if (
|
||||
context.requireBotMention &&
|
||||
!isCommandAddressedToBot(commandRaw, context.botUserName)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const command = normalizeCommandName(
|
||||
commandRaw.toLowerCase(),
|
||||
context.botUserName,
|
||||
@@ -140,7 +122,7 @@ export function normalizeCommandName(
|
||||
command: string,
|
||||
botUserName?: string,
|
||||
): string {
|
||||
const botMention = command.match(/^(\/[^@\s]+)@[a-z0-9_.\-]+$/i);
|
||||
const botMention = command.match(/^(\/[^@\s]+)@[a-z0-9_]+$/i);
|
||||
if (!botMention) {
|
||||
return command;
|
||||
}
|
||||
@@ -152,18 +134,6 @@ export function normalizeCommandName(
|
||||
return suffix === expectedBotName ? botMention[1] : command;
|
||||
}
|
||||
|
||||
export function isCommandAddressedToBot(
|
||||
command: string,
|
||||
botUserName?: string,
|
||||
): boolean {
|
||||
const expectedBotName = botUserName?.replace(/^@+/, "").trim().toLowerCase();
|
||||
if (!expectedBotName) {
|
||||
return false;
|
||||
}
|
||||
const match = command.match(/^\/[^@\s]+@([a-z0-9_.\-]+)$/i);
|
||||
return match?.[1]?.toLowerCase() === expectedBotName;
|
||||
}
|
||||
|
||||
function tokenizeArgs(input: string): string[] {
|
||||
const tokens: string[] = [];
|
||||
let current = "";
|
||||
@@ -275,11 +245,9 @@ function formatHelp(state: ChatCommandState): string {
|
||||
"/cwd <path> - change working directory",
|
||||
"/schedule create/list/trigger/delete - manage scheduled workflows",
|
||||
"/abort - stop the current task",
|
||||
"/mute [target] - ignore this thread or target until /unmute",
|
||||
"/unmute [target] - resume processing this thread or target",
|
||||
"/exit - stop this connector",
|
||||
"",
|
||||
`Current state: tools=${state.enableTools ? "on" : "off"}, yolo=${state.autoApproveTools ? "on" : "off"}, muted=${state.threadMuted ? "true" : "false"}`,
|
||||
`Current state: tools=${state.enableTools ? "on" : "off"}, yolo=${state.autoApproveTools ? "on" : "off"}`,
|
||||
state.toolsLocked
|
||||
? "Tool controls are locked because this connector was started with --no-tools."
|
||||
: undefined,
|
||||
@@ -317,26 +285,6 @@ function createDefaultChatCommandHost(): ChatCommandHost {
|
||||
await context.abort?.();
|
||||
},
|
||||
})
|
||||
.register("command", {
|
||||
names: ["/mute"],
|
||||
isAvailable: (context) => typeof context.mute === "function",
|
||||
run: async ({ args }, context) => {
|
||||
const target = args.join(" ").trim() || undefined;
|
||||
const reply = await context.mute?.({ target });
|
||||
await context.reply(
|
||||
reply ?? "Thread muted. I will ignore messages here until /unmute.",
|
||||
);
|
||||
},
|
||||
})
|
||||
.register("command", {
|
||||
names: ["/unmute"],
|
||||
isAvailable: (context) => typeof context.unmute === "function",
|
||||
run: async ({ args }, context) => {
|
||||
const target = args.join(" ").trim() || undefined;
|
||||
const reply = await context.unmute?.({ target });
|
||||
await context.reply(reply ?? "Thread unmuted.");
|
||||
},
|
||||
})
|
||||
.register("command", {
|
||||
names: ["/exit"],
|
||||
isAvailable: (context) => typeof context.stop === "function",
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
# Cline Hub
|
||||
|
||||
A browser dashboard for the local Cline hub. Open it to see who's connected, what sessions are running, drive a session from a chat box, and restart the hub when you need a fresh daemon.
|
||||
|
||||
## Capabilities
|
||||
|
||||
- live list of connected hub clients (from `HubUIClient.subscribeUI`)
|
||||
- live list of active sessions with status, model, and titles
|
||||
- click a session to view its message history and stream new assistant output
|
||||
- start a new session from an initial prompt — workspace/provider/model are reused from the most recent session, or `CLINE_PROVIDER` / `CLINE_MODEL` env vars
|
||||
- send messages to the selected session and watch chunks stream back
|
||||
- **Restart Hub** button: gracefully stops the local detached hub and respawns a fresh one
|
||||
- optional LAN/tunnel exposure gated by a shared `ROOM_SECRET`
|
||||
|
||||
The dashboard registers two clients with the hub: a `cline-hub-server` (via `ClineCore`) for driving sessions and a `cline-hub-server` (via `HubUIClient`) for the admin view.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
cd apps/cline-hub
|
||||
bun run start
|
||||
```
|
||||
|
||||
Open <http://127.0.0.1:8787> and click **Connect**. The server will discover or spawn a local detached hub on startup; the hub endpoint is printed in the console and shown in the sidebar.
|
||||
|
||||
For webview development with Vite hot reload:
|
||||
|
||||
```bash
|
||||
cd apps/cline-hub
|
||||
bun run dev
|
||||
```
|
||||
|
||||
This starts the Vite webview server on <http://127.0.0.1:5173> and the hub dashboard on <http://127.0.0.1:8787>. Open the dashboard URL; the served page loads webview modules from Vite, so changes under `src/webview/src` hot reload without rebuilding. Use `CLINE_HUB_WEBVIEW_DEV_PORT` or `CLINE_HUB_WEBVIEW_DEV_HOST` to change the Vite bind address.
|
||||
|
||||
To start a brand-new session, the dashboard needs to know which provider and model to use. It picks them up automatically from the most recent session on the hub. If there are no recent sessions, set `CLINE_PROVIDER` and `CLINE_MODEL` in the environment before running.
|
||||
|
||||
## Configuration
|
||||
|
||||
Environment variables:
|
||||
|
||||
| Variable | Default | Description |
|
||||
| --- | --- | --- |
|
||||
| `HOST` | `127.0.0.1` | Bind host for the dashboard. Use the default for same-machine development. Set `HOST=0.0.0.0` only when intentionally exposing the dashboard on a LAN/tunnel. |
|
||||
| `CLINE_HUB_DASHBOARD_PORT` | `8787` | Dashboard HTTP/WebSocket port. |
|
||||
| `PUBLIC_URL` | `http://<HOST>:<PORT>` (`127.0.0.1` when binding `0.0.0.0`) | URL printed for humans to open/copy. Set this to your LAN URL or tunnel URL. |
|
||||
| `ROOM_SECRET` | unset | Shared invite secret required for browser WebSocket connections when `HOST` is non-local. |
|
||||
| `WORKSPACE_ROOT` | current directory | Workspace passed to the hub on startup. |
|
||||
| `CLINE_PROVIDER` | unset | Fallback provider id when no recent session is available to copy from. |
|
||||
| `CLINE_MODEL` | unset | Fallback model id when no recent session is available to copy from. |
|
||||
|
||||
The server prints both the bind URL and the public/invite URL at startup. When `ROOM_SECRET` is set, the printed invite URL includes `?roomSecret=...`; the browser UI also lets you paste the secret manually.
|
||||
|
||||
Validate option parsing without starting a server:
|
||||
|
||||
```bash
|
||||
bun run smoke:options
|
||||
```
|
||||
|
||||
## LAN usage
|
||||
|
||||
Choose a strong room secret and bind explicitly to all interfaces:
|
||||
|
||||
```bash
|
||||
cd apps/cline-hub
|
||||
HOST=0.0.0.0 \
|
||||
CLINE_HUB_DASHBOARD_PORT=8787 \
|
||||
PUBLIC_URL=http://YOUR_LAN_IP:8787 \
|
||||
ROOM_SECRET='use-a-long-random-secret' \
|
||||
bun run start
|
||||
```
|
||||
|
||||
Share the printed invite URL with another machine on the same LAN.
|
||||
|
||||
`ROOM_SECRET` is required for `HOST=0.0.0.0`; without it the dashboard exits before listening.
|
||||
|
||||
## Tunnel usage
|
||||
|
||||
Start the dashboard locally with an explicit secret:
|
||||
|
||||
```bash
|
||||
cd apps/cline-hub
|
||||
ROOM_SECRET='use-a-long-random-secret' bun run start
|
||||
```
|
||||
|
||||
In another terminal, expose the local port with your tunnel provider, for example:
|
||||
|
||||
```bash
|
||||
ngrok http 8787
|
||||
```
|
||||
|
||||
Restart the dashboard with the tunnel URL as `PUBLIC_URL` so the printed invite URL is copyable:
|
||||
|
||||
```bash
|
||||
PUBLIC_URL=https://YOUR-TUNNEL.example \
|
||||
ROOM_SECRET='use-a-long-random-secret' \
|
||||
bun run start
|
||||
```
|
||||
|
||||
Share only the printed invite URL with trusted participants.
|
||||
|
||||
## Restarting the hub
|
||||
|
||||
Clicking **Restart Hub** in the sidebar:
|
||||
|
||||
1. Detaches the dashboard's `ClineCore` and `HubUIClient` from the current hub.
|
||||
2. Calls `stopLocalHubServerGracefully()` to shut the local detached hub down.
|
||||
3. Calls `ensureDetachedHubServer(workspaceRoot)` to spawn a fresh hub.
|
||||
4. Reconnects and broadcasts the new hub state to every open browser tab.
|
||||
|
||||
Sessions running on the previous hub are stopped along with the hub. Other clients connected to that hub (CLI, VS Code, menubar) will see their connection drop and reconnect to the new daemon on next request.
|
||||
|
||||
## Security warning
|
||||
|
||||
This is an example dashboard, not a production admin tool. Exposing it on a LAN or tunnel lets anyone with the invite secret list clients/sessions on your hub, drive sessions, and restart the hub. Use a long random `ROOM_SECRET`, only share the URL with trusted participants, and stop the process when you are done. The hub and agent runtime remain owned by the host machine.
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"name": "@cline/cline-hub",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"description": "Browser dashboard for the Cline hub: live clients, sessions, streaming chat, and hub restart.",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build:webview": "bun run --cwd src/webview build",
|
||||
"dev": "bun run src/dev.ts",
|
||||
"start": "bun run src/server.ts",
|
||||
"smoke:options": "bun run src/validate-options.ts",
|
||||
"typecheck": "bun tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@cline/core": "workspace:*",
|
||||
"@cline/llms": "workspace:*",
|
||||
"@cline/shared": "workspace:*"
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
import { join } from "node:path";
|
||||
import process from "node:process";
|
||||
|
||||
const webviewHost =
|
||||
process.env.CLINE_HUB_WEBVIEW_DEV_HOST?.trim() || "127.0.0.1";
|
||||
const webviewPort = process.env.CLINE_HUB_WEBVIEW_DEV_PORT?.trim() || "5173";
|
||||
const webviewDevServerUrl =
|
||||
process.env.VITE_DEV_SERVER_URL?.trim() ||
|
||||
`http://${webviewHost}:${webviewPort}`;
|
||||
|
||||
const cwd = process.cwd();
|
||||
const webviewCwd = join(cwd, "src", "webview");
|
||||
|
||||
const children: Bun.Subprocess[] = [];
|
||||
let shuttingDown = false;
|
||||
|
||||
function spawn(
|
||||
name: string,
|
||||
command: string[],
|
||||
options: {
|
||||
cwd: string;
|
||||
env: NodeJS.ProcessEnv;
|
||||
},
|
||||
): Bun.Subprocess {
|
||||
const child = Bun.spawn(command, {
|
||||
...options,
|
||||
stdout: "inherit",
|
||||
stderr: "inherit",
|
||||
});
|
||||
children.push(child);
|
||||
void child.exited.then((code) => {
|
||||
if (!shuttingDown) {
|
||||
console.error(`[cline-hub:dev] ${name} exited with code ${code}`);
|
||||
shutdown(code === 0 ? 0 : 1);
|
||||
}
|
||||
});
|
||||
return child;
|
||||
}
|
||||
|
||||
function shutdown(exitCode = 0): void {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
for (const child of children) {
|
||||
try {
|
||||
child.kill();
|
||||
} catch {
|
||||
// The process may have already exited.
|
||||
}
|
||||
}
|
||||
process.exitCode = exitCode;
|
||||
}
|
||||
|
||||
process.on("SIGINT", () => shutdown(0));
|
||||
process.on("SIGTERM", () => shutdown(0));
|
||||
|
||||
console.log(`[cline-hub:dev] Vite webview: ${webviewDevServerUrl}`);
|
||||
console.log("[cline-hub:dev] Hub dashboard: http://127.0.0.1:8787/");
|
||||
|
||||
spawn(
|
||||
"webview",
|
||||
[
|
||||
"bun",
|
||||
"run",
|
||||
"dev",
|
||||
"--host",
|
||||
webviewHost,
|
||||
"--port",
|
||||
webviewPort,
|
||||
"--strictPort",
|
||||
],
|
||||
{
|
||||
cwd: webviewCwd,
|
||||
env: process.env,
|
||||
},
|
||||
);
|
||||
|
||||
spawn("server", ["bun", "run", "src/server.ts"], {
|
||||
cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
VITE_DEV_SERVER_URL: webviewDevServerUrl,
|
||||
},
|
||||
});
|
||||
|
||||
await Promise.allSettled(children.map((child) => child.exited));
|
||||
@@ -1,96 +0,0 @@
|
||||
export interface ClineHubServerOptions {
|
||||
host: string;
|
||||
port: number;
|
||||
publicUrl: string;
|
||||
roomSecret?: string;
|
||||
workspaceRoot: string;
|
||||
}
|
||||
|
||||
const DEFAULT_HOST = "127.0.0.1";
|
||||
const DEFAULT_PORT = 8787;
|
||||
const DASHBOARD_PORT_ENV = "CLINE_HUB_DASHBOARD_PORT";
|
||||
|
||||
function parsePort(value: string | undefined): number {
|
||||
if (!value?.trim()) return DEFAULT_PORT;
|
||||
const port = Number.parseInt(value, 10);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error(
|
||||
`${DASHBOARD_PORT_ENV} must be an integer from 1 to 65535, got ${value}`,
|
||||
);
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
function normalizeHost(value: string | undefined): string {
|
||||
return value?.trim() || DEFAULT_HOST;
|
||||
}
|
||||
|
||||
function normalizePublicUrl(
|
||||
value: string | undefined,
|
||||
host: string,
|
||||
port: number,
|
||||
): string {
|
||||
const fallbackHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
|
||||
const raw = value?.trim() || `http://${fallbackHost}:${port}`;
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(raw);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`PUBLIC_URL must be a valid http(s) URL, got ${raw}: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
}
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
||||
throw new Error(
|
||||
`PUBLIC_URL must use http: or https:, got ${parsed.protocol}`,
|
||||
);
|
||||
}
|
||||
parsed.hash = "";
|
||||
return parsed.toString().replace(/\/$/, "");
|
||||
}
|
||||
|
||||
function normalizeRoomSecret(value: string | undefined): string | undefined {
|
||||
const secret = value?.trim();
|
||||
return secret ? secret : undefined;
|
||||
}
|
||||
|
||||
function isLocalBindHost(host: string): boolean {
|
||||
return host === "127.0.0.1" || host === "localhost" || host === "::1";
|
||||
}
|
||||
|
||||
export function isNonLocalBindHost(host: string): boolean {
|
||||
return !isLocalBindHost(host);
|
||||
}
|
||||
|
||||
export function resolveClineHubServerOptions(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): ClineHubServerOptions {
|
||||
const host = normalizeHost(env.HOST);
|
||||
const port = parsePort(env[DASHBOARD_PORT_ENV]);
|
||||
const publicUrl = normalizePublicUrl(env.PUBLIC_URL, host, port);
|
||||
const roomSecret = normalizeRoomSecret(env.ROOM_SECRET);
|
||||
if (isNonLocalBindHost(host) && !roomSecret) {
|
||||
throw new Error(
|
||||
`ROOM_SECRET is required when HOST=${host}. Use HOST=127.0.0.1 for local-only development or set ROOM_SECRET before exposing this example on a LAN/tunnel.`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
host,
|
||||
port,
|
||||
publicUrl,
|
||||
roomSecret,
|
||||
workspaceRoot: env.WORKSPACE_ROOT?.trim() || process.cwd(),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildInviteUrl(
|
||||
publicUrl: string,
|
||||
roomSecret: string | undefined,
|
||||
): string {
|
||||
if (!roomSecret) return publicUrl;
|
||||
const url = new URL(publicUrl);
|
||||
url.searchParams.set("roomSecret", roomSecret);
|
||||
return url.toString();
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
import { CORE_BUILD_VERSION } from "@cline/core";
|
||||
import { isNonLocalBindHost } from "./options";
|
||||
import {
|
||||
handleToolApprovalResponse,
|
||||
rejectOrphanedApprovals,
|
||||
} from "./server/approvals";
|
||||
import {
|
||||
browserConfig,
|
||||
host,
|
||||
inviteUrl,
|
||||
port,
|
||||
publicUrl,
|
||||
roomSecret,
|
||||
webviewDistDir,
|
||||
} from "./server/deps";
|
||||
import { handleDesktopCommand } from "./server/desktop-commands";
|
||||
import { createJsonResponse, WebviewAssets } from "./server/http";
|
||||
import {
|
||||
attachHub,
|
||||
restartHub,
|
||||
syncHubClientsAndSessions,
|
||||
syncHubHealth,
|
||||
} from "./server/hub";
|
||||
import {
|
||||
loadModels,
|
||||
runProviderOAuthLogin,
|
||||
saveProviderSettings,
|
||||
sendProviderCatalog,
|
||||
} from "./server/providers";
|
||||
import {
|
||||
abortPeerTurn,
|
||||
deleteSession,
|
||||
forkPeerSession,
|
||||
initializePeer,
|
||||
resetPeer,
|
||||
restorePeerSession,
|
||||
selectSession,
|
||||
sendMessage,
|
||||
} from "./server/sessions";
|
||||
import { HubContext } from "./server/state";
|
||||
import { broadcastHubState, hubStatusPayload } from "./server/state-payloads";
|
||||
import type { BrowserFrame, BrowserPeer } from "./server/types";
|
||||
|
||||
const ctx = new HubContext();
|
||||
const assets = new WebviewAssets(webviewDistDir);
|
||||
const syncClientsAndSessions = () => syncHubClientsAndSessions(ctx);
|
||||
|
||||
function isAuthorizedBrowserRequest(url: URL): boolean {
|
||||
if (!roomSecret) return true;
|
||||
return url.searchParams.get("roomSecret") === roomSecret;
|
||||
}
|
||||
|
||||
await attachHub(ctx);
|
||||
setInterval(() => {
|
||||
void (async () => {
|
||||
await syncHubHealth(ctx);
|
||||
broadcastHubState(ctx);
|
||||
})();
|
||||
}, 5_000);
|
||||
|
||||
const server = Bun.serve<BrowserPeer>({
|
||||
port,
|
||||
hostname: host,
|
||||
async fetch(req, server) {
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname === "/version") {
|
||||
return createJsonResponse({ coreVersion: CORE_BUILD_VERSION });
|
||||
}
|
||||
if (url.pathname === "/health") {
|
||||
await syncHubHealth(ctx);
|
||||
return createJsonResponse(hubStatusPayload(ctx));
|
||||
}
|
||||
if (url.pathname === "/browser") {
|
||||
if (!isAuthorizedBrowserRequest(url)) {
|
||||
return createJsonResponse({ error: "invalid_room_secret" }, 401);
|
||||
}
|
||||
const displayName = `Browser ${Math.random().toString(36).slice(2, 6)}`;
|
||||
const data = {
|
||||
socket: undefined as never,
|
||||
displayName,
|
||||
sending: false,
|
||||
};
|
||||
if (server.upgrade(req, { data })) return undefined;
|
||||
return new Response("upgrade failed", { status: 400 });
|
||||
}
|
||||
if (url.pathname === "/config.json") {
|
||||
return createJsonResponse(browserConfig);
|
||||
}
|
||||
return assets.serve(url.pathname);
|
||||
},
|
||||
websocket: {
|
||||
async open(socket) {
|
||||
const peer = socket.data;
|
||||
peer.socket = socket;
|
||||
ctx.peers.add(peer);
|
||||
},
|
||||
async message(socket, raw) {
|
||||
const peer = socket.data;
|
||||
try {
|
||||
const frame = JSON.parse(String(raw)) as BrowserFrame;
|
||||
if (frame.type === "desktopCommand") {
|
||||
try {
|
||||
const result = await handleDesktopCommand(
|
||||
ctx,
|
||||
frame.command,
|
||||
frame.args,
|
||||
);
|
||||
ctx.send(peer, {
|
||||
type: "desktopCommandResult",
|
||||
id: frame.id,
|
||||
ok: true,
|
||||
result,
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.send(peer, {
|
||||
type: "desktopCommandResult",
|
||||
id: frame.id,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
} else if (frame.type === "ready") {
|
||||
await initializePeer(ctx, peer, syncClientsAndSessions);
|
||||
} else if (frame.type === "loadModels") {
|
||||
await loadModels(ctx, peer, frame.providerId);
|
||||
} else if (frame.type === "loadProviderCatalog") {
|
||||
await sendProviderCatalog(ctx, peer);
|
||||
} else if (frame.type === "saveProviderSettings") {
|
||||
await saveProviderSettings(ctx, peer, frame);
|
||||
} else if (frame.type === "runProviderOAuthLogin") {
|
||||
await runProviderOAuthLogin(ctx, peer, frame.providerId);
|
||||
} else if (frame.type === "attachSession") {
|
||||
await selectSession(ctx, peer, frame.sessionId);
|
||||
} else if (frame.type === "deleteSession") {
|
||||
await deleteSession(ctx, peer, frame.sessionId);
|
||||
} else if (frame.type === "updateSessionMetadata") {
|
||||
if (!ctx.cline) throw new Error("Hub is not connected.");
|
||||
const session = await ctx.cline.get(frame.sessionId);
|
||||
const metadata =
|
||||
session?.metadata && typeof session.metadata === "object"
|
||||
? (session.metadata as Record<string, unknown>)
|
||||
: {};
|
||||
await ctx.cline.update(frame.sessionId, {
|
||||
metadata: { ...metadata, ...frame.metadata },
|
||||
});
|
||||
await syncHubClientsAndSessions(ctx);
|
||||
broadcastHubState(ctx);
|
||||
} else if (frame.type === "approval_response") {
|
||||
handleToolApprovalResponse(ctx, frame);
|
||||
} else if (frame.type === "abort") {
|
||||
await abortPeerTurn(ctx, peer);
|
||||
} else if (frame.type === "reset") {
|
||||
await resetPeer(ctx, peer);
|
||||
} else if (frame.type === "send") {
|
||||
if (peer.sending) {
|
||||
ctx.send(peer, {
|
||||
type: "status",
|
||||
text: "A turn is already in progress.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
peer.sending = true;
|
||||
try {
|
||||
await sendMessage(
|
||||
ctx,
|
||||
peer,
|
||||
frame.prompt,
|
||||
frame.config,
|
||||
frame.attachments,
|
||||
);
|
||||
} finally {
|
||||
peer.sending = false;
|
||||
}
|
||||
} else if (frame.type === "forkSession") {
|
||||
await forkPeerSession(ctx, peer, syncClientsAndSessions);
|
||||
} else if (frame.type === "restore") {
|
||||
await restorePeerSession(
|
||||
ctx,
|
||||
peer,
|
||||
frame.checkpointRunCount,
|
||||
syncClientsAndSessions,
|
||||
);
|
||||
} else if (frame.type === "restart_hub") {
|
||||
await restartHub(ctx);
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.send(peer, {
|
||||
type: "error",
|
||||
text: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
},
|
||||
close(socket) {
|
||||
const peer = socket.data;
|
||||
peer.unsubscribeEvents?.();
|
||||
ctx.peers.delete(peer);
|
||||
rejectOrphanedApprovals(ctx);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`Cline Hub dashboard listening: ${server.url}`);
|
||||
console.log(`Cline Hub public URL: ${publicUrl}`);
|
||||
console.log(`hub endpoint: ${ctx.hubUrl}`);
|
||||
if (roomSecret) {
|
||||
console.log(`Cline Hub invite URL: ${inviteUrl}`);
|
||||
} else if (isNonLocalBindHost(host)) {
|
||||
console.warn("WARNING: non-local bind without ROOM_SECRET is not allowed.");
|
||||
} else {
|
||||
console.log(
|
||||
"ROOM_SECRET is not set; this local-only instance accepts browser connections without an invite token.",
|
||||
);
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
import type { CoreSessionEvent } from "@cline/core";
|
||||
import type { AgentEvent } from "@cline/shared";
|
||||
import type { WebviewToolEvent } from "../webview-protocol";
|
||||
import { rejectPendingApprovalsForSession } from "./approvals";
|
||||
import type { HubContext } from "./state";
|
||||
import { broadcastHubState } from "./state-payloads";
|
||||
import { asString, chunkText } from "./utils";
|
||||
|
||||
function agentEventText(event: AgentEvent): string {
|
||||
if (
|
||||
event.type === "content_start" &&
|
||||
event.contentType === "text" &&
|
||||
typeof event.text === "string"
|
||||
) {
|
||||
return event.text;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function sendChunkToSelectedPeers(
|
||||
ctx: HubContext,
|
||||
sessionId: string,
|
||||
text: string,
|
||||
): void {
|
||||
if (!text) return;
|
||||
ctx.sendToSelectedPeers(sessionId, { type: "assistant_delta", text });
|
||||
}
|
||||
|
||||
function forwardAgentEvent(
|
||||
ctx: HubContext,
|
||||
sessionId: string,
|
||||
event: AgentEvent,
|
||||
): void {
|
||||
if (event.type === "content_start") {
|
||||
if (event.contentType === "reasoning") {
|
||||
ctx.sendToSelectedPeers(sessionId, {
|
||||
type: "reasoning_delta",
|
||||
text: event.reasoning ?? event.text ?? "",
|
||||
redacted: event.redacted,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.contentType === "tool") {
|
||||
ctx.sendToSelectedPeers(sessionId, {
|
||||
type: "tool_event",
|
||||
text: `Running ${event.toolName ?? "tool"}...`,
|
||||
event: {
|
||||
toolCallId: event.toolCallId,
|
||||
toolName: event.toolName,
|
||||
status: "running",
|
||||
input: event.input,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
const text = agentEventText(event);
|
||||
if (text) sendChunkToSelectedPeers(ctx, sessionId, text);
|
||||
return;
|
||||
}
|
||||
if (event.type === "content_update" && event.contentType === "tool") {
|
||||
const toolEvent: WebviewToolEvent = {
|
||||
toolCallId: event.toolCallId,
|
||||
toolName: event.toolName,
|
||||
status: "running",
|
||||
output: event.update,
|
||||
};
|
||||
ctx.sendToSelectedPeers(sessionId, {
|
||||
type: "tool_event",
|
||||
text: `${event.toolName ?? "tool"} updated`,
|
||||
event: toolEvent,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.type === "content_end") {
|
||||
if (event.contentType === "reasoning") {
|
||||
ctx.sendToSelectedPeers(sessionId, {
|
||||
type: "reasoning_delta",
|
||||
text: event.reasoning ?? event.text ?? "",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.contentType === "tool") {
|
||||
const toolName = event.toolName ?? "tool";
|
||||
ctx.sendToSelectedPeers(sessionId, {
|
||||
type: "tool_event",
|
||||
text: event.error
|
||||
? `${toolName} failed: ${event.error}`
|
||||
: `${toolName} completed`,
|
||||
event: {
|
||||
toolCallId: event.toolCallId,
|
||||
toolName,
|
||||
status: event.error ? "failed" : "completed",
|
||||
output: event.output,
|
||||
error: event.error,
|
||||
},
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.type === "notice") {
|
||||
ctx.sendToSelectedPeers(sessionId, { type: "status", text: event.message });
|
||||
return;
|
||||
}
|
||||
if (event.type === "done") {
|
||||
ctx.sendToSelectedPeers(sessionId, {
|
||||
type: "turn_done",
|
||||
finishReason: event.reason,
|
||||
iterations: event.iterations,
|
||||
usage: event.usage
|
||||
? {
|
||||
inputTokens: event.usage.inputTokens,
|
||||
outputTokens: event.usage.outputTokens,
|
||||
cacheCreationInputTokens: event.usage.cacheWriteTokens,
|
||||
cacheReadInputTokens: event.usage.cacheReadTokens,
|
||||
totalCost: event.usage.totalCost,
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.type === "error") {
|
||||
ctx.sendToSelectedPeers(sessionId, {
|
||||
type: "error",
|
||||
text: event.error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function handleSessionEvent(
|
||||
ctx: HubContext,
|
||||
event: CoreSessionEvent,
|
||||
): void {
|
||||
const payload = event.payload as Record<string, unknown> | undefined;
|
||||
const sessionId = asString(payload?.sessionId);
|
||||
if (!sessionId) return;
|
||||
if (event.type === "chunk") {
|
||||
const text = chunkText((payload as Record<string, unknown>).chunk);
|
||||
sendChunkToSelectedPeers(ctx, sessionId, text);
|
||||
} else if (event.type === "agent_event") {
|
||||
if (event.payload.teamRole === "teammate") return;
|
||||
forwardAgentEvent(ctx, sessionId, event.payload.event);
|
||||
} else if (event.type === "status") {
|
||||
const status = asString((payload as Record<string, unknown>).status);
|
||||
const tracked = ctx.sessions.get(sessionId);
|
||||
if (tracked && status) {
|
||||
tracked.status = status;
|
||||
tracked.updatedAt = Date.now();
|
||||
}
|
||||
for (const peer of ctx.peers) {
|
||||
if (peer.selectedSessionId === sessionId) {
|
||||
ctx.send(peer, {
|
||||
type: "status",
|
||||
text: status ?? "Session status changed.",
|
||||
});
|
||||
}
|
||||
}
|
||||
broadcastHubState(ctx);
|
||||
} else if (event.type === "ended") {
|
||||
rejectPendingApprovalsForSession(
|
||||
ctx,
|
||||
sessionId,
|
||||
"Session ended before approval was resolved.",
|
||||
);
|
||||
const tracked = ctx.sessions.get(sessionId);
|
||||
if (tracked) {
|
||||
tracked.status = "completed";
|
||||
tracked.updatedAt = Date.now();
|
||||
}
|
||||
for (const peer of ctx.peers) {
|
||||
if (peer.selectedSessionId === sessionId) {
|
||||
ctx.send(peer, {
|
||||
type: "turn_done",
|
||||
finishReason: event.payload.reason,
|
||||
iterations: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
broadcastHubState(ctx);
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
import type { ToolApprovalRequest, ToolApprovalResult } from "@cline/shared";
|
||||
import type { WebviewInboundMessage } from "../webview-protocol";
|
||||
import type { HubContext } from "./state";
|
||||
import { broadcastHubState } from "./state-payloads";
|
||||
|
||||
function createApprovalId(): string {
|
||||
return `approval-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
|
||||
export function resolveToolApproval(
|
||||
ctx: HubContext,
|
||||
approvalId: string,
|
||||
result: ToolApprovalResult,
|
||||
): boolean {
|
||||
const pending = ctx.pendingToolApprovals.get(approvalId);
|
||||
if (!pending) return false;
|
||||
clearTimeout(pending.timeout);
|
||||
ctx.pendingToolApprovals.delete(approvalId);
|
||||
ctx.sendToSelectedPeers(pending.sessionId, {
|
||||
type: "approval_resolved",
|
||||
approvalId,
|
||||
approved: result.approved,
|
||||
reason: result.reason,
|
||||
});
|
||||
pending.resolve(result);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function rejectPendingApprovalsForSession(
|
||||
ctx: HubContext,
|
||||
sessionId: string,
|
||||
reason: string,
|
||||
): void {
|
||||
for (const [approvalId, pending] of [...ctx.pendingToolApprovals.entries()]) {
|
||||
if (pending.sessionId === sessionId) {
|
||||
resolveToolApproval(ctx, approvalId, { approved: false, reason });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function rejectAllPendingApprovals(
|
||||
ctx: HubContext,
|
||||
reason: string,
|
||||
): void {
|
||||
for (const approvalId of [...ctx.pendingToolApprovals.keys()]) {
|
||||
resolveToolApproval(ctx, approvalId, { approved: false, reason });
|
||||
}
|
||||
}
|
||||
|
||||
export function rejectOrphanedApprovals(ctx: HubContext): void {
|
||||
for (const [approvalId, pending] of [...ctx.pendingToolApprovals.entries()]) {
|
||||
if (!ctx.hasSelectedPeer(pending.sessionId)) {
|
||||
resolveToolApproval(ctx, approvalId, {
|
||||
approved: false,
|
||||
reason: "Cline Hub webview disconnected before approval was resolved.",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function requestToolApprovalFromWebview(
|
||||
ctx: HubContext,
|
||||
request: ToolApprovalRequest,
|
||||
): Promise<ToolApprovalResult> {
|
||||
if (!ctx.hasSelectedPeer(request.sessionId)) {
|
||||
return Promise.resolve({
|
||||
approved: false,
|
||||
reason: "No Cline Hub webview is attached to this session.",
|
||||
});
|
||||
}
|
||||
|
||||
const approvalId = createApprovalId();
|
||||
ctx.pushEvent(
|
||||
"Tool approval requested",
|
||||
`${request.toolName} is waiting for approval`,
|
||||
"warn",
|
||||
);
|
||||
broadcastHubState(ctx);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const timeout = setTimeout(() => {
|
||||
resolveToolApproval(ctx, approvalId, {
|
||||
approved: false,
|
||||
reason: "Tool approval request timed out.",
|
||||
});
|
||||
}, 10 * 60_000);
|
||||
ctx.pendingToolApprovals.set(approvalId, {
|
||||
sessionId: request.sessionId,
|
||||
resolve,
|
||||
timeout,
|
||||
});
|
||||
ctx.sendToSelectedPeers(request.sessionId, {
|
||||
type: "approval_request",
|
||||
approvalId,
|
||||
sessionId: request.sessionId,
|
||||
agentId: request.agentId,
|
||||
conversationId: request.conversationId,
|
||||
iteration: request.iteration,
|
||||
toolCallId: request.toolCallId,
|
||||
toolName: request.toolName,
|
||||
input: request.input,
|
||||
policy: request.policy as Record<string, unknown> | undefined,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function handleToolApprovalResponse(
|
||||
ctx: HubContext,
|
||||
frame: Extract<WebviewInboundMessage, { type: "approval_response" }>,
|
||||
): void {
|
||||
const approvalId = frame.approvalId.trim();
|
||||
if (!approvalId) return;
|
||||
const resolved = resolveToolApproval(ctx, approvalId, {
|
||||
approved: frame.approved,
|
||||
reason:
|
||||
frame.reason ??
|
||||
(frame.approved ? "Approved in Cline Hub." : "Rejected in Cline Hub."),
|
||||
});
|
||||
if (!resolved) {
|
||||
console.warn(`Ignoring unknown tool approval response: ${approvalId}`);
|
||||
}
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import process from "node:process";
|
||||
import { listConnectorCatalog } from "../../../cli/src/connectors/catalog";
|
||||
import { listActiveConnectors } from "../../../cli/src/connectors/status";
|
||||
import { PLATFORMS } from "../../../cli/src/wizards/connect/platforms";
|
||||
import type {
|
||||
WebviewConnectorChannel,
|
||||
WebviewConnectorChannelsResponse,
|
||||
} from "../webview-protocol";
|
||||
import { cliIndexPath, workspaceRoot } from "./deps";
|
||||
import { asRecord, asString } from "./utils";
|
||||
|
||||
export function connectorChannelsPayload(): WebviewConnectorChannelsResponse {
|
||||
const supported = new Set(
|
||||
listConnectorCatalog().map((connector) => connector.name),
|
||||
);
|
||||
const available: WebviewConnectorChannel[] = PLATFORMS.filter((platform) =>
|
||||
supported.has(platform.id),
|
||||
).map((platform) => ({
|
||||
id: platform.id,
|
||||
name: platform.name,
|
||||
type: platform.type,
|
||||
hint: platform.hint,
|
||||
fields: platform.fields.map((field) => ({
|
||||
flag: field.flag,
|
||||
label: field.label,
|
||||
placeholder: field.placeholder,
|
||||
required: field.required,
|
||||
help: field.help,
|
||||
})),
|
||||
security: platform.security
|
||||
? {
|
||||
prompt: platform.security.prompt,
|
||||
fields: platform.security.fields.map((field) => ({
|
||||
key: field.key,
|
||||
label: field.label,
|
||||
placeholder: field.placeholder,
|
||||
help: field.help,
|
||||
requiredMessage: field.requiredMessage,
|
||||
})),
|
||||
}
|
||||
: undefined,
|
||||
}));
|
||||
return { available, active: listActiveConnectors() };
|
||||
}
|
||||
|
||||
async function runCliConnectCommand(args: string[]): Promise<{
|
||||
code: number;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}> {
|
||||
const launcher = (process.versions as Record<string, string | undefined>).bun
|
||||
? process.execPath
|
||||
: "bun";
|
||||
const child = spawn(
|
||||
launcher,
|
||||
["--conditions=development", cliIndexPath, "connect", ...args],
|
||||
{
|
||||
cwd: workspaceRoot,
|
||||
env: {
|
||||
...process.env,
|
||||
CLINE_BUILD_ENV: process.env.CLINE_BUILD_ENV ?? "development",
|
||||
},
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout?.setEncoding("utf8");
|
||||
child.stderr?.setEncoding("utf8");
|
||||
child.stdout?.on("data", (chunk) => {
|
||||
stdout += String(chunk);
|
||||
});
|
||||
child.stderr?.on("data", (chunk) => {
|
||||
stderr += String(chunk);
|
||||
});
|
||||
const code = await new Promise<number>((resolve, reject) => {
|
||||
child.on("error", reject);
|
||||
child.on("close", (exitCode) => resolve(exitCode ?? 0));
|
||||
});
|
||||
return { code, stdout, stderr };
|
||||
}
|
||||
|
||||
async function waitForConnectorState(
|
||||
predicate: () => boolean,
|
||||
timeoutMs = 5_000,
|
||||
): Promise<void> {
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
if (predicate()) return;
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
}
|
||||
}
|
||||
|
||||
function buildConnectorStartArgs(args?: Record<string, unknown>): string[] {
|
||||
const channel = asString(args?.channel);
|
||||
if (!channel) throw new Error("channel is required");
|
||||
const platform = PLATFORMS.find((entry) => entry.id === channel);
|
||||
if (!platform) throw new Error(`unknown connector channel: ${channel}`);
|
||||
const supported = new Set(
|
||||
listConnectorCatalog().map((connector) => connector.name),
|
||||
);
|
||||
if (!supported.has(platform.id)) {
|
||||
throw new Error(`connector channel is not available: ${channel}`);
|
||||
}
|
||||
const values = asRecord(args?.values) ?? {};
|
||||
const cliArgs = [channel];
|
||||
for (const field of platform.fields) {
|
||||
const value = asString(values[field.flag]);
|
||||
if (!value) {
|
||||
if (field.required) throw new Error(`${field.label} is required`);
|
||||
continue;
|
||||
}
|
||||
cliArgs.push(field.flag, value);
|
||||
}
|
||||
const security = asRecord(args?.security);
|
||||
if (security?.enabled === true && platform.security) {
|
||||
const securityValues = asRecord(security.values) ?? {};
|
||||
const hookValues: Record<string, string> = {};
|
||||
for (const field of platform.security.fields) {
|
||||
const value = asString(securityValues[field.key]);
|
||||
if (!value) throw new Error(field.requiredMessage);
|
||||
const validationError = field.validate?.(value);
|
||||
if (validationError) throw new Error(validationError);
|
||||
hookValues[field.key] = value;
|
||||
}
|
||||
cliArgs.push(
|
||||
"--hook-command",
|
||||
platform.security.buildHookCommand(hookValues),
|
||||
);
|
||||
}
|
||||
return cliArgs;
|
||||
}
|
||||
|
||||
export async function startConnectorChannel(
|
||||
args?: Record<string, unknown>,
|
||||
): Promise<WebviewConnectorChannelsResponse> {
|
||||
const cliArgs = buildConnectorStartArgs(args);
|
||||
const channel = cliArgs[0] ?? "";
|
||||
const result = await runCliConnectCommand(cliArgs);
|
||||
if (result.code !== 0) {
|
||||
throw new Error(
|
||||
(result.stderr.trim() || result.stdout.trim() || "connector start failed")
|
||||
.trim()
|
||||
.slice(0, 2_000),
|
||||
);
|
||||
}
|
||||
await waitForConnectorState(() =>
|
||||
listActiveConnectors().some((connector) => connector.type === channel),
|
||||
);
|
||||
return connectorChannelsPayload();
|
||||
}
|
||||
|
||||
export async function stopConnectorChannel(
|
||||
args?: Record<string, unknown>,
|
||||
): Promise<WebviewConnectorChannelsResponse> {
|
||||
const channel = asString(args?.channel);
|
||||
if (!channel) throw new Error("channel is required");
|
||||
const supported = new Set(
|
||||
listConnectorCatalog().map((connector) => connector.name),
|
||||
);
|
||||
if (!supported.has(channel)) {
|
||||
throw new Error(`unknown connector channel: ${channel}`);
|
||||
}
|
||||
const result = await runCliConnectCommand([channel, "--stop"]);
|
||||
if (result.code !== 0) {
|
||||
throw new Error(
|
||||
(result.stderr.trim() || result.stdout.trim() || "connector stop failed")
|
||||
.trim()
|
||||
.slice(0, 2_000),
|
||||
);
|
||||
}
|
||||
await waitForConnectorState(
|
||||
() =>
|
||||
!listActiveConnectors().some((connector) => connector.type === channel),
|
||||
);
|
||||
return connectorChannelsPayload();
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { dirname, join, normalize } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ProviderSettingsManager } from "@cline/core";
|
||||
import { buildInviteUrl, resolveClineHubServerOptions } from "../options";
|
||||
import type { BrowserConfig } from "./types";
|
||||
|
||||
export const options = resolveClineHubServerOptions();
|
||||
export const { host, port, publicUrl, roomSecret, workspaceRoot } = options;
|
||||
export const inviteUrl = buildInviteUrl(publicUrl, roomSecret);
|
||||
|
||||
const serverDir = dirname(fileURLToPath(import.meta.url));
|
||||
/** server.ts lives one level up from this module, so resolve relative to it. */
|
||||
export const appSrcDir = join(serverDir, "..");
|
||||
export const webviewDistDir = join(appSrcDir, "../dist/webview");
|
||||
export const cliIndexPath = normalize(
|
||||
join(appSrcDir, "../../cli/src/index.ts"),
|
||||
);
|
||||
|
||||
export const providerSettingsManager = new ProviderSettingsManager();
|
||||
|
||||
export const browserConfig: BrowserConfig = {
|
||||
inviteRequired: Boolean(roomSecret),
|
||||
publicUrl,
|
||||
};
|
||||
@@ -1,238 +0,0 @@
|
||||
import {
|
||||
addLocalProvider,
|
||||
type ClineAccountActionRequest,
|
||||
ClineAccountService,
|
||||
ensureCustomProvidersLoaded,
|
||||
executeClineAccountAction,
|
||||
getLocalProviderModels,
|
||||
listLocalProviders,
|
||||
loginLocalProvider,
|
||||
normalizeOAuthProvider,
|
||||
type ProviderCapability,
|
||||
type ProviderClient,
|
||||
type ProviderProtocol,
|
||||
readGlobalSettings,
|
||||
resolveLocalClineAuthToken,
|
||||
saveLocalProviderOAuthCredentials,
|
||||
saveLocalProviderSettings,
|
||||
setDisabledPlugin,
|
||||
setDisabledTools,
|
||||
setTelemetryOptOutGlobally,
|
||||
toggleDisabledTool,
|
||||
} from "@cline/core";
|
||||
import { getClineEnvironmentConfig } from "@cline/shared";
|
||||
import {
|
||||
connectorChannelsPayload,
|
||||
startConnectorChannel,
|
||||
stopConnectorChannel,
|
||||
} from "./connectors";
|
||||
import { providerSettingsManager, workspaceRoot } from "./deps";
|
||||
import {
|
||||
deleteMcpServer,
|
||||
ensureMcpSettingsFile,
|
||||
readMcpServersResponse,
|
||||
setMcpServerDisabled,
|
||||
upsertMcpServer,
|
||||
} from "./mcp";
|
||||
import { handleRoutineScheduleCommand } from "./schedules";
|
||||
import { toWebviewSessionSummary } from "./session-mapping";
|
||||
import type { HubContext } from "./state";
|
||||
import { broadcastHubState } from "./state-payloads";
|
||||
import type { JsonRecord } from "./types";
|
||||
import { listUserInstructionConfigs } from "./user-instructions";
|
||||
import { openExternalUrl, readProviderSettingsUpdate } from "./utils";
|
||||
|
||||
const ROUTINE_SCHEDULE_COMMANDS = new Set([
|
||||
"list_routine_schedules",
|
||||
"create_routine_schedule",
|
||||
"update_routine_schedule",
|
||||
"pause_routine_schedule",
|
||||
"resume_routine_schedule",
|
||||
"trigger_routine_schedule",
|
||||
"delete_routine_schedule",
|
||||
]);
|
||||
|
||||
export async function handleDesktopCommand(
|
||||
ctx: HubContext,
|
||||
command: string,
|
||||
args?: Record<string, unknown>,
|
||||
): Promise<unknown> {
|
||||
if (command === "list_provider_catalog") {
|
||||
await ensureCustomProvidersLoaded(providerSettingsManager);
|
||||
return await listLocalProviders(providerSettingsManager);
|
||||
}
|
||||
if (command === "list_provider_models") {
|
||||
const provider = String(args?.provider ?? "").trim();
|
||||
return await getLocalProviderModels(
|
||||
provider,
|
||||
providerSettingsManager.getProviderConfig(provider),
|
||||
);
|
||||
}
|
||||
if (command === "save_provider_settings") {
|
||||
return saveLocalProviderSettings(providerSettingsManager, {
|
||||
...readProviderSettingsUpdate(args),
|
||||
providerId: String(args?.provider ?? ""),
|
||||
enabled: typeof args?.enabled === "boolean" ? args.enabled : undefined,
|
||||
apiKey: typeof args?.api_key === "string" ? args.api_key : undefined,
|
||||
baseUrl: typeof args?.base_url === "string" ? args.base_url : undefined,
|
||||
});
|
||||
}
|
||||
if (command === "add_provider") {
|
||||
await ensureCustomProvidersLoaded(providerSettingsManager);
|
||||
return await addLocalProvider(providerSettingsManager, {
|
||||
providerId: String(args?.provider_id ?? ""),
|
||||
name: String(args?.name ?? ""),
|
||||
baseUrl: String(args?.base_url ?? ""),
|
||||
apiKey: typeof args?.api_key === "string" ? args.api_key : undefined,
|
||||
headers:
|
||||
args?.headers && typeof args.headers === "object"
|
||||
? (args.headers as Record<string, string>)
|
||||
: undefined,
|
||||
timeoutMs:
|
||||
typeof args?.timeout_ms === "number" ? args.timeout_ms : undefined,
|
||||
models: Array.isArray(args?.models)
|
||||
? (args.models as string[])
|
||||
: undefined,
|
||||
defaultModelId:
|
||||
typeof args?.default_model_id === "string"
|
||||
? args.default_model_id
|
||||
: undefined,
|
||||
modelsSourceUrl:
|
||||
typeof args?.models_source_url === "string"
|
||||
? args.models_source_url
|
||||
: undefined,
|
||||
protocol:
|
||||
typeof args?.protocol === "string"
|
||||
? (args.protocol as ProviderProtocol)
|
||||
: undefined,
|
||||
client:
|
||||
typeof args?.client === "string"
|
||||
? (args.client as ProviderClient)
|
||||
: undefined,
|
||||
capabilities: Array.isArray(args?.capabilities)
|
||||
? (args.capabilities as ProviderCapability[])
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
if (command === "run_provider_oauth_login") {
|
||||
const providerId = normalizeOAuthProvider(String(args?.provider ?? ""));
|
||||
const existing = providerSettingsManager.getProviderSettings(providerId);
|
||||
const credentials = await loginLocalProvider(
|
||||
providerId,
|
||||
existing,
|
||||
openExternalUrl,
|
||||
);
|
||||
const saved = saveLocalProviderOAuthCredentials(
|
||||
providerSettingsManager,
|
||||
providerId,
|
||||
existing,
|
||||
credentials,
|
||||
);
|
||||
return {
|
||||
provider: providerId,
|
||||
accessToken: saved.auth?.accessToken ?? saved.apiKey ?? "",
|
||||
};
|
||||
}
|
||||
if (command === "cline_account") {
|
||||
const settings = providerSettingsManager.getProviderSettings("cline");
|
||||
const accountService = new ClineAccountService({
|
||||
apiBaseUrl:
|
||||
settings?.baseUrl?.trim() || getClineEnvironmentConfig().apiBaseUrl,
|
||||
getAuthToken: async () => resolveLocalClineAuthToken(settings),
|
||||
});
|
||||
return await executeClineAccountAction(
|
||||
args as ClineAccountActionRequest,
|
||||
accountService,
|
||||
);
|
||||
}
|
||||
if (command === "get_global_settings") {
|
||||
return readGlobalSettings();
|
||||
}
|
||||
if (command === "set_telemetry_opt_out") {
|
||||
if (typeof args?.telemetry_opt_out !== "boolean") {
|
||||
throw new Error("telemetry_opt_out must be a boolean");
|
||||
}
|
||||
setTelemetryOptOutGlobally(args.telemetry_opt_out);
|
||||
return readGlobalSettings();
|
||||
}
|
||||
if (command === "list_connector_channels") {
|
||||
return connectorChannelsPayload();
|
||||
}
|
||||
if (command === "start_connector_channel") {
|
||||
const response = await startConnectorChannel(args);
|
||||
broadcastHubState(ctx);
|
||||
return response;
|
||||
}
|
||||
if (command === "stop_connector_channel") {
|
||||
const response = await stopConnectorChannel(args);
|
||||
broadcastHubState(ctx);
|
||||
return response;
|
||||
}
|
||||
if (command === "list_mcp_servers") {
|
||||
return readMcpServersResponse();
|
||||
}
|
||||
if (command === "set_mcp_server_disabled") {
|
||||
return setMcpServerDisabled(
|
||||
String(args?.name ?? "").trim(),
|
||||
Boolean(args?.disabled),
|
||||
);
|
||||
}
|
||||
if (command === "upsert_mcp_server") {
|
||||
const input =
|
||||
args?.input && typeof args.input === "object"
|
||||
? (args.input as JsonRecord)
|
||||
: ((args ?? {}) as JsonRecord);
|
||||
return upsertMcpServer(input);
|
||||
}
|
||||
if (command === "delete_mcp_server") {
|
||||
return deleteMcpServer(String(args?.name ?? "").trim());
|
||||
}
|
||||
if (command === "ensure_mcp_settings_file") {
|
||||
return ensureMcpSettingsFile();
|
||||
}
|
||||
if (command === "open_mcp_settings_file") {
|
||||
const path = ensureMcpSettingsFile();
|
||||
openExternalUrl(path);
|
||||
return path;
|
||||
}
|
||||
if (ROUTINE_SCHEDULE_COMMANDS.has(command)) {
|
||||
return await handleRoutineScheduleCommand(command, args);
|
||||
}
|
||||
if (command === "get_process_context") {
|
||||
return { workspaceRoot, cwd: workspaceRoot };
|
||||
}
|
||||
if (
|
||||
command === "list_cli_sessions" ||
|
||||
command === "list_discovered_sessions"
|
||||
) {
|
||||
return [...ctx.sessions.values()].map(toWebviewSessionSummary);
|
||||
}
|
||||
if (command === "read_session_hooks") {
|
||||
return [];
|
||||
}
|
||||
if (command === "list_user_instruction_configs") {
|
||||
return await listUserInstructionConfigs(workspaceRoot);
|
||||
}
|
||||
if (command === "toggle_disabled_plugin_tool") {
|
||||
const toolName = String(args?.name ?? "").trim();
|
||||
if (!toolName) throw new Error("tool name is required");
|
||||
toggleDisabledTool(toolName);
|
||||
return await listUserInstructionConfigs(workspaceRoot);
|
||||
}
|
||||
if (command === "set_tool_disabled") {
|
||||
const rawNames = Array.isArray(args?.names) ? args.names : [args?.name];
|
||||
const toolNames = rawNames
|
||||
.map((name) => String(name ?? "").trim())
|
||||
.filter(Boolean);
|
||||
if (toolNames.length === 0) throw new Error("tool name is required");
|
||||
setDisabledTools(toolNames, args?.disabled === true);
|
||||
return await listUserInstructionConfigs(workspaceRoot);
|
||||
}
|
||||
if (command === "set_plugin_disabled") {
|
||||
const pluginPath = String(args?.path ?? "").trim();
|
||||
if (!pluginPath) throw new Error("plugin path is required");
|
||||
setDisabledPlugin(pluginPath, args?.disabled === true);
|
||||
return await listUserInstructionConfigs(workspaceRoot);
|
||||
}
|
||||
throw new Error(`unsupported desktop command: ${command}`);
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
import { extname, join, normalize, relative } from "node:path";
|
||||
import process from "node:process";
|
||||
|
||||
export function createJsonResponse(payload: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(payload), {
|
||||
status,
|
||||
headers: { "content-type": "application/json; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
|
||||
export function createTextResponse(text: string, status = 200): Response {
|
||||
return new Response(text, {
|
||||
status,
|
||||
headers: { "content-type": "text/plain; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
|
||||
function contentTypeFor(path: string): string {
|
||||
switch (extname(path)) {
|
||||
case ".html":
|
||||
return "text/html; charset=utf-8";
|
||||
case ".js":
|
||||
return "text/javascript; charset=utf-8";
|
||||
case ".css":
|
||||
return "text/css; charset=utf-8";
|
||||
case ".svg":
|
||||
return "image/svg+xml";
|
||||
case ".png":
|
||||
return "image/png";
|
||||
case ".ico":
|
||||
return "image/x-icon";
|
||||
case ".woff2":
|
||||
return "font/woff2";
|
||||
default:
|
||||
return "application/octet-stream";
|
||||
}
|
||||
}
|
||||
|
||||
function isWebviewRoute(pathname: string): boolean {
|
||||
return (
|
||||
pathname === "/" ||
|
||||
pathname === "/index.html" ||
|
||||
pathname === "/chat" ||
|
||||
pathname === "/settings" ||
|
||||
pathname.startsWith("/settings/")
|
||||
);
|
||||
}
|
||||
|
||||
function renderDevIndexHtml(devServerUrl: string): string {
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<script type="module">
|
||||
import RefreshRuntime from "${devServerUrl}/@react-refresh";
|
||||
RefreshRuntime.injectIntoGlobalHook(window);
|
||||
window.$RefreshReg$ = () => {};
|
||||
window.$RefreshSig$ = () => (type) => type;
|
||||
window.__vite_plugin_react_preamble_installed__ = true;
|
||||
</script>
|
||||
<script type="module" src="${devServerUrl}/@vite/client"></script>
|
||||
<link rel="icon" type="image/svg+xml" href="${devServerUrl}/favicon.svg" />
|
||||
<title>Cline Hub</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="${devServerUrl}/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
/** Serves the built webview SPA and its static assets out of `webviewDistDir`. */
|
||||
export class WebviewAssets {
|
||||
constructor(private readonly webviewDistDir: string) {}
|
||||
|
||||
private resolveStaticPath(pathname: string): string | undefined {
|
||||
const decoded = decodeURIComponent(pathname);
|
||||
const requested = decoded === "/" ? "/index.html" : decoded;
|
||||
const normalized = normalize(requested).replace(/^(\.\.[/\\])+/, "");
|
||||
const relativePath = normalized.replace(/^[/\\]+/, "");
|
||||
const filePath = join(this.webviewDistDir, relativePath);
|
||||
if (relative(this.webviewDistDir, filePath).startsWith("..")) {
|
||||
return undefined;
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private async serveIndex(): Promise<Response> {
|
||||
const indexFile = Bun.file(join(this.webviewDistDir, "index.html"));
|
||||
if (await indexFile.exists()) {
|
||||
return new Response(indexFile, {
|
||||
headers: { "content-type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
return createTextResponse(
|
||||
"Cline Hub webview is not built. Run `bun run build:webview` from sdk/apps/cline-hub.",
|
||||
503,
|
||||
);
|
||||
}
|
||||
|
||||
async serve(pathname: string): Promise<Response> {
|
||||
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
|
||||
if (devServerUrl && isWebviewRoute(pathname)) {
|
||||
return new Response(renderDevIndexHtml(devServerUrl), {
|
||||
headers: { "content-type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
if (isWebviewRoute(pathname)) {
|
||||
return this.serveIndex();
|
||||
}
|
||||
|
||||
const filePath = this.resolveStaticPath(pathname);
|
||||
if (!filePath) return createTextResponse("not found", 404);
|
||||
const file = Bun.file(filePath);
|
||||
if (!(await file.exists())) {
|
||||
return createTextResponse("not found", 404);
|
||||
}
|
||||
return new Response(file, {
|
||||
headers: { "content-type": contentTypeFor(filePath) },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,273 +0,0 @@
|
||||
import {
|
||||
ClineCore,
|
||||
ensureDetachedHubServer,
|
||||
type HubServerDiscoveryRecord,
|
||||
HubUIClient,
|
||||
stopLocalHubServerGracefully,
|
||||
toHubHealthUrl,
|
||||
} from "@cline/core";
|
||||
import type { HubUINotifyPayload } from "@cline/shared";
|
||||
import { handleSessionEvent } from "./agent-events";
|
||||
import {
|
||||
rejectAllPendingApprovals,
|
||||
requestToolApprovalFromWebview,
|
||||
} from "./approvals";
|
||||
import { workspaceRoot } from "./deps";
|
||||
import {
|
||||
formatClientName,
|
||||
formatSessionCreator,
|
||||
parseSessionContext,
|
||||
trackSession,
|
||||
} from "./session-mapping";
|
||||
import type { HubContext } from "./state";
|
||||
import { broadcastHubState } from "./state-payloads";
|
||||
import type { SessionContext } from "./types";
|
||||
import { asString, basename, isActiveSession, isVisibleClient } from "./utils";
|
||||
|
||||
export async function syncHubHealth(ctx: HubContext): Promise<void> {
|
||||
if (!ctx.hubUrl) {
|
||||
ctx.hubHealthy = false;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch(toHubHealthUrl(ctx.hubUrl));
|
||||
if (!response.ok) {
|
||||
ctx.hubHealthy = false;
|
||||
return;
|
||||
}
|
||||
ctx.hubHealthy = true;
|
||||
const health = (await response.json()) as Partial<HubServerDiscoveryRecord>;
|
||||
if (typeof health.startedAt === "string")
|
||||
ctx.hubStartedAt = health.startedAt;
|
||||
if (typeof health.coreVersion === "string") {
|
||||
ctx.coreVersion = health.coreVersion;
|
||||
}
|
||||
} catch {
|
||||
ctx.hubHealthy = false;
|
||||
// best-effort
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncHubClientsAndSessions(
|
||||
ctx: HubContext,
|
||||
): Promise<void> {
|
||||
if (!ctx.uiClient) return;
|
||||
const [knownClients, knownSessions] = await Promise.all([
|
||||
ctx.uiClient.listClients(),
|
||||
ctx.uiClient.listSessions(10),
|
||||
]);
|
||||
ctx.clients.clear();
|
||||
for (const client of knownClients) {
|
||||
if (!client.clientId || !isVisibleClient(client.clientType)) continue;
|
||||
ctx.clients.set(client.clientId, {
|
||||
clientId: client.clientId,
|
||||
displayName: client.displayName,
|
||||
clientType: client.clientType,
|
||||
connectedAt: client.connectedAt,
|
||||
});
|
||||
}
|
||||
ctx.sessions.clear();
|
||||
for (const session of knownSessions) {
|
||||
const tracked = trackSession(session);
|
||||
if (tracked) ctx.sessions.set(tracked.sessionId, tracked);
|
||||
}
|
||||
if (!ctx.initialHubEventEmitted) {
|
||||
const activeSessionCount = [...ctx.sessions.values()].filter((session) =>
|
||||
isActiveSession(session.title, session.status, session.participantCount),
|
||||
).length;
|
||||
ctx.pushEvent(
|
||||
"Hub monitor connected",
|
||||
`${ctx.clients.size} connected client${ctx.clients.size === 1 ? "" : "s"}, ${activeSessionCount} active session${activeSessionCount === 1 ? "" : "s"}`,
|
||||
"success",
|
||||
);
|
||||
ctx.initialHubEventEmitted = true;
|
||||
}
|
||||
const mostRecent = [...knownSessions]
|
||||
.sort((a, b) => b.updatedAt - a.updatedAt)
|
||||
.map((s) => parseSessionContext(s))
|
||||
.find((c): c is SessionContext => Boolean(c));
|
||||
if (mostRecent) ctx.lastSessionContext = mostRecent;
|
||||
}
|
||||
|
||||
export async function attachHub(ctx: HubContext): Promise<void> {
|
||||
const hub = await ensureDetachedHubServer(workspaceRoot);
|
||||
ctx.hubUrl = hub.url;
|
||||
ctx.hubAuthToken = hub.authToken;
|
||||
|
||||
ctx.cline = await ClineCore.create({
|
||||
clientName: "cline-hub",
|
||||
backendMode: "hub",
|
||||
capabilities: {
|
||||
requestToolApproval: (request) =>
|
||||
requestToolApprovalFromWebview(ctx, request),
|
||||
},
|
||||
hub: {
|
||||
endpoint: ctx.hubUrl,
|
||||
authToken: ctx.hubAuthToken,
|
||||
clientType: "cline-hub-chat",
|
||||
displayName: "Cline Hub Chat",
|
||||
workspaceRoot,
|
||||
},
|
||||
});
|
||||
|
||||
ctx.uiClient = new HubUIClient({
|
||||
address: ctx.hubUrl,
|
||||
authToken: ctx.hubAuthToken,
|
||||
clientType: "cline-hub-server",
|
||||
displayName: "Cline Hub Server",
|
||||
});
|
||||
await ctx.uiClient.connect();
|
||||
|
||||
ctx.uiClient.subscribeUI({
|
||||
onNotify(payload: HubUINotifyPayload) {
|
||||
ctx.pushEvent(
|
||||
payload.title,
|
||||
payload.body,
|
||||
payload.severity === "error"
|
||||
? "error"
|
||||
: payload.severity === "warning"
|
||||
? "warn"
|
||||
: "info",
|
||||
);
|
||||
ctx.broadcast({
|
||||
type: "notification",
|
||||
title: payload.title,
|
||||
body: payload.body,
|
||||
severity: payload.severity ?? "info",
|
||||
});
|
||||
},
|
||||
onClientRegistered(payload) {
|
||||
const clientId = asString(payload.clientId);
|
||||
const clientType = asString(payload.clientType) ?? "unknown";
|
||||
if (!clientId || !isVisibleClient(clientType)) return;
|
||||
ctx.clients.set(clientId, {
|
||||
clientId,
|
||||
displayName: asString(payload.displayName),
|
||||
clientType,
|
||||
connectedAt: Date.now(),
|
||||
});
|
||||
ctx.pushEvent(
|
||||
"Client connected",
|
||||
`${asString(payload.displayName) ?? clientType} joined the hub`,
|
||||
"success",
|
||||
);
|
||||
broadcastHubState(ctx);
|
||||
},
|
||||
onClientDisconnected(payload) {
|
||||
const clientId = asString(payload.clientId);
|
||||
if (!clientId) return;
|
||||
const client = ctx.clients.get(clientId);
|
||||
ctx.clients.delete(clientId);
|
||||
if (client) {
|
||||
ctx.pushEvent(
|
||||
"Client disconnected",
|
||||
`${formatClientName(client)} left the hub`,
|
||||
"info",
|
||||
);
|
||||
}
|
||||
broadcastHubState(ctx);
|
||||
},
|
||||
onSessionCreated(payload) {
|
||||
const record =
|
||||
payload.session && typeof payload.session === "object"
|
||||
? (payload.session as Record<string, unknown>)
|
||||
: (payload as unknown as Record<string, unknown>);
|
||||
const tracked = trackSession(record);
|
||||
if (tracked) {
|
||||
ctx.sessions.set(tracked.sessionId, tracked);
|
||||
const context = parseSessionContext(record);
|
||||
if (context) ctx.lastSessionContext = context;
|
||||
ctx.pushEvent(
|
||||
"Session started",
|
||||
`By ${formatSessionCreator(ctx, tracked)} at ${basename(tracked.workspaceRoot || tracked.cwd)}`,
|
||||
"success",
|
||||
);
|
||||
broadcastHubState(ctx);
|
||||
}
|
||||
},
|
||||
onSessionUpdated(payload) {
|
||||
const record =
|
||||
payload.session && typeof payload.session === "object"
|
||||
? (payload.session as Record<string, unknown>)
|
||||
: (payload as unknown as Record<string, unknown>);
|
||||
const tracked = trackSession(record);
|
||||
if (tracked) {
|
||||
ctx.sessions.set(tracked.sessionId, tracked);
|
||||
const context = parseSessionContext(record);
|
||||
if (context) ctx.lastSessionContext = context;
|
||||
broadcastHubState(ctx);
|
||||
}
|
||||
},
|
||||
onSessionDetached(payload) {
|
||||
const sessionId =
|
||||
asString((payload as Record<string, unknown>).sessionId) ??
|
||||
asString(
|
||||
(
|
||||
(payload as Record<string, unknown>).session as
|
||||
| Record<string, unknown>
|
||||
| undefined
|
||||
)?.sessionId,
|
||||
);
|
||||
if (sessionId) {
|
||||
ctx.sessions.delete(sessionId);
|
||||
broadcastHubState(ctx);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
ctx.cline.subscribe((event) => handleSessionEvent(ctx, event));
|
||||
|
||||
await syncHubClientsAndSessions(ctx);
|
||||
await syncHubHealth(ctx);
|
||||
}
|
||||
|
||||
export async function detachHub(ctx: HubContext): Promise<void> {
|
||||
rejectAllPendingApprovals(
|
||||
ctx,
|
||||
"Hub disconnected before approval was resolved.",
|
||||
);
|
||||
for (const peer of ctx.peers) {
|
||||
peer.unsubscribeEvents?.();
|
||||
peer.unsubscribeEvents = undefined;
|
||||
}
|
||||
try {
|
||||
ctx.uiClient?.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
ctx.uiClient = undefined;
|
||||
try {
|
||||
await ctx.cline?.dispose();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
ctx.cline = undefined;
|
||||
ctx.clients.clear();
|
||||
ctx.sessions.clear();
|
||||
ctx.hubStartedAt = undefined;
|
||||
ctx.coreVersion = undefined;
|
||||
ctx.initialHubEventEmitted = false;
|
||||
}
|
||||
|
||||
export async function restartHub(ctx: HubContext): Promise<void> {
|
||||
ctx.broadcast({
|
||||
type: "notification",
|
||||
title: "Hub restarting",
|
||||
body: "Shutting down and respawning hub...",
|
||||
severity: "warn",
|
||||
});
|
||||
await detachHub(ctx);
|
||||
try {
|
||||
await stopLocalHubServerGracefully();
|
||||
} catch (error) {
|
||||
console.warn("stopLocalHubServerGracefully failed:", error);
|
||||
}
|
||||
await attachHub(ctx);
|
||||
broadcastHubState(ctx);
|
||||
ctx.broadcast({
|
||||
type: "notification",
|
||||
title: "Hub restarted",
|
||||
body: `Connected to ${ctx.hubUrl}`,
|
||||
severity: "info",
|
||||
});
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { resolveMcpSettingsPath } from "@cline/shared/storage";
|
||||
import type { JsonRecord } from "./types";
|
||||
|
||||
export function readMcpServersResponse(): JsonRecord {
|
||||
const settingsPath = resolveMcpSettingsPath();
|
||||
if (!existsSync(settingsPath)) {
|
||||
return { settingsPath, hasSettingsFile: false, servers: [] };
|
||||
}
|
||||
const parsed = JSON.parse(readFileSync(settingsPath, "utf8")) as JsonRecord;
|
||||
const servers = parsed.mcpServers as JsonRecord | undefined;
|
||||
const entries = Object.entries(servers ?? {}).map(([name, body]) => {
|
||||
const record = body as JsonRecord;
|
||||
const transport =
|
||||
record.transport && typeof record.transport === "object"
|
||||
? (record.transport as JsonRecord)
|
||||
: undefined;
|
||||
const transportType = String(
|
||||
transport?.type ?? record.transportType ?? record.type ?? "stdio",
|
||||
).trim();
|
||||
return {
|
||||
name,
|
||||
transportType,
|
||||
disabled: record.disabled === true,
|
||||
command:
|
||||
typeof transport?.command === "string"
|
||||
? transport.command
|
||||
: typeof record.command === "string"
|
||||
? record.command
|
||||
: undefined,
|
||||
args: Array.isArray(transport?.args)
|
||||
? transport.args
|
||||
: Array.isArray(record.args)
|
||||
? record.args
|
||||
: undefined,
|
||||
cwd:
|
||||
typeof transport?.cwd === "string"
|
||||
? transport.cwd
|
||||
: typeof record.cwd === "string"
|
||||
? record.cwd
|
||||
: undefined,
|
||||
env:
|
||||
transport?.env && typeof transport.env === "object"
|
||||
? transport.env
|
||||
: record.env && typeof record.env === "object"
|
||||
? record.env
|
||||
: undefined,
|
||||
url:
|
||||
typeof transport?.url === "string"
|
||||
? transport.url
|
||||
: typeof record.url === "string"
|
||||
? record.url
|
||||
: undefined,
|
||||
headers:
|
||||
transport?.headers && typeof transport.headers === "object"
|
||||
? transport.headers
|
||||
: record.headers && typeof record.headers === "object"
|
||||
? record.headers
|
||||
: undefined,
|
||||
metadata: record.metadata,
|
||||
};
|
||||
});
|
||||
return { settingsPath, hasSettingsFile: true, servers: entries };
|
||||
}
|
||||
|
||||
export function writeMcpServersMap(servers: JsonRecord): void {
|
||||
const path = resolveMcpSettingsPath();
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, `${JSON.stringify({ mcpServers: servers }, null, 2)}\n`);
|
||||
}
|
||||
|
||||
export function ensureMcpSettingsFile(): string {
|
||||
const path = resolveMcpSettingsPath();
|
||||
if (!existsSync(path)) {
|
||||
writeMcpServersMap({});
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
function readServersMap(): { path: string; servers: JsonRecord } {
|
||||
const path = ensureMcpSettingsFile();
|
||||
const parsed = JSON.parse(readFileSync(path, "utf8")) as JsonRecord;
|
||||
return { path, servers: (parsed.mcpServers as JsonRecord | undefined) ?? {} };
|
||||
}
|
||||
|
||||
export function setMcpServerDisabled(
|
||||
name: string,
|
||||
disabled: boolean,
|
||||
): JsonRecord {
|
||||
const { servers } = readServersMap();
|
||||
const current = servers[name];
|
||||
if (!current || typeof current !== "object") {
|
||||
throw new Error(`unknown MCP server: ${name}`);
|
||||
}
|
||||
servers[name] = { ...(current as JsonRecord), disabled };
|
||||
writeMcpServersMap(servers);
|
||||
return readMcpServersResponse();
|
||||
}
|
||||
|
||||
export function upsertMcpServer(input: JsonRecord): JsonRecord {
|
||||
const name = String(input.name ?? "").trim();
|
||||
if (!name) throw new Error("server name is required");
|
||||
const previousName = String(
|
||||
input.previousName ?? input.previous_name ?? "",
|
||||
).trim();
|
||||
const transportType = String(
|
||||
input.transportType ?? input.transport_type ?? "",
|
||||
).trim();
|
||||
const next: JsonRecord =
|
||||
transportType === "stdio"
|
||||
? {
|
||||
transport: {
|
||||
type: "stdio",
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
cwd: input.cwd,
|
||||
env: input.env,
|
||||
},
|
||||
disabled: input.disabled === true,
|
||||
}
|
||||
: {
|
||||
transport: {
|
||||
type: transportType === "sse" ? "sse" : "streamableHttp",
|
||||
url: input.url,
|
||||
headers: input.headers,
|
||||
},
|
||||
disabled: input.disabled === true,
|
||||
};
|
||||
const { servers } = readServersMap();
|
||||
if (previousName && previousName !== name) {
|
||||
delete servers[previousName];
|
||||
}
|
||||
servers[name] = next;
|
||||
writeMcpServersMap(servers);
|
||||
return readMcpServersResponse();
|
||||
}
|
||||
|
||||
export function deleteMcpServer(name: string): JsonRecord {
|
||||
if (!name) throw new Error("server name is required");
|
||||
const { servers } = readServersMap();
|
||||
delete servers[name];
|
||||
writeMcpServersMap(servers);
|
||||
return readMcpServersResponse();
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
import process from "node:process";
|
||||
import {
|
||||
ensureCustomProvidersLoaded,
|
||||
getLocalProviderModels,
|
||||
Llms,
|
||||
listLocalProviders,
|
||||
loginLocalProvider,
|
||||
normalizeOAuthProvider,
|
||||
saveLocalProviderOAuthCredentials,
|
||||
saveLocalProviderSettings,
|
||||
} from "@cline/core";
|
||||
import type {
|
||||
WebviewInboundMessage,
|
||||
WebviewProviderModel,
|
||||
} from "../webview-protocol";
|
||||
import { providerSettingsManager, workspaceRoot } from "./deps";
|
||||
import type { HubContext } from "./state";
|
||||
import type { BrowserPeer } from "./types";
|
||||
import { openExternalUrl } from "./utils";
|
||||
|
||||
export function resolveBrowserDefaults(ctx: HubContext): {
|
||||
provider?: string;
|
||||
model?: string;
|
||||
workspaceRoot: string;
|
||||
cwd: string;
|
||||
} {
|
||||
const lastUsed = providerSettingsManager.getLastUsedProviderSettings();
|
||||
return {
|
||||
provider:
|
||||
lastUsed?.provider ??
|
||||
ctx.lastSessionContext?.providerId ??
|
||||
process.env.CLINE_PROVIDER?.trim(),
|
||||
model:
|
||||
lastUsed?.model ??
|
||||
ctx.lastSessionContext?.modelId ??
|
||||
process.env.CLINE_MODEL?.trim(),
|
||||
workspaceRoot: ctx.lastSessionContext?.workspaceRoot ?? workspaceRoot,
|
||||
cwd:
|
||||
ctx.lastSessionContext?.cwd ??
|
||||
ctx.lastSessionContext?.workspaceRoot ??
|
||||
workspaceRoot,
|
||||
};
|
||||
}
|
||||
|
||||
export async function loadProviders(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
): Promise<void> {
|
||||
await ensureCustomProvidersLoaded(providerSettingsManager);
|
||||
const state = providerSettingsManager.read();
|
||||
const defaults = resolveBrowserDefaults(ctx);
|
||||
const ids = Llms.getProviderIds().sort((a, b) => a.localeCompare(b));
|
||||
const providers = (
|
||||
await Promise.all(
|
||||
ids.map(async (id) => {
|
||||
const info = await Llms.getProvider(id);
|
||||
const enabled =
|
||||
Boolean(state.providers[id]?.settings) || id === defaults.provider;
|
||||
return {
|
||||
id,
|
||||
name: info?.name ?? id,
|
||||
enabled,
|
||||
defaultModelId: info?.defaultModelId,
|
||||
};
|
||||
}),
|
||||
)
|
||||
).filter((provider) => provider.enabled);
|
||||
ctx.send(peer, { type: "providers", providers });
|
||||
const selected =
|
||||
(defaults.provider &&
|
||||
providers.find((provider) => provider.id === defaults.provider)) ||
|
||||
providers[0];
|
||||
if (selected) {
|
||||
await loadModels(ctx, peer, selected.id);
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadModels(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
providerId: string,
|
||||
): Promise<void> {
|
||||
const provider = providerId.trim();
|
||||
if (!provider) return;
|
||||
const payload = await getLocalProviderModels(
|
||||
provider,
|
||||
providerSettingsManager.getProviderConfig(provider),
|
||||
);
|
||||
const models: WebviewProviderModel[] = payload.models.map((model) => ({
|
||||
id: model.id,
|
||||
name: model.name,
|
||||
supportsReasoning: model.supportsReasoning,
|
||||
supportsThinking: model.supportsReasoning,
|
||||
}));
|
||||
ctx.send(peer, { type: "models", providerId: provider, models });
|
||||
}
|
||||
|
||||
export async function sendProviderCatalog(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
): Promise<void> {
|
||||
await ensureCustomProvidersLoaded(providerSettingsManager);
|
||||
const payload = await listLocalProviders(providerSettingsManager);
|
||||
ctx.send(peer, {
|
||||
type: "provider_catalog",
|
||||
providers: payload.providers,
|
||||
settingsPath: payload.settingsPath,
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveProviderSettings(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
frame: Extract<WebviewInboundMessage, { type: "saveProviderSettings" }>,
|
||||
): Promise<void> {
|
||||
const result = saveLocalProviderSettings(providerSettingsManager, {
|
||||
providerId: frame.providerId,
|
||||
enabled: frame.enabled,
|
||||
apiKey: frame.apiKey,
|
||||
baseUrl: frame.baseUrl,
|
||||
});
|
||||
ctx.send(peer, {
|
||||
type: "provider_settings_saved",
|
||||
providerId: result.providerId,
|
||||
enabled: result.enabled,
|
||||
});
|
||||
await sendProviderCatalog(ctx, peer);
|
||||
await loadProviders(ctx, peer);
|
||||
}
|
||||
|
||||
export async function runProviderOAuthLogin(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
providerId: string,
|
||||
): Promise<void> {
|
||||
const normalized = normalizeOAuthProvider(providerId);
|
||||
const existing = providerSettingsManager.getProviderSettings(normalized);
|
||||
const credentials = await loginLocalProvider(
|
||||
normalized,
|
||||
existing,
|
||||
openExternalUrl,
|
||||
);
|
||||
const saved = saveLocalProviderOAuthCredentials(
|
||||
providerSettingsManager,
|
||||
normalized,
|
||||
existing,
|
||||
credentials,
|
||||
);
|
||||
ctx.send(peer, {
|
||||
type: "provider_oauth_login_done",
|
||||
providerId: normalized,
|
||||
accessTokenPresent:
|
||||
(saved.auth?.accessToken?.trim() ?? saved.apiKey?.trim() ?? "").length >
|
||||
0,
|
||||
});
|
||||
await sendProviderCatalog(ctx, peer);
|
||||
await loadProviders(ctx, peer);
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
import {
|
||||
createLocalHubScheduleRuntimeHandlers,
|
||||
HubScheduleCommandService,
|
||||
HubScheduleService,
|
||||
} from "@cline/core";
|
||||
import { asTrimmedString, toPositiveInt } from "./utils";
|
||||
|
||||
let scheduleService: HubScheduleService | undefined;
|
||||
let scheduleCommands: HubScheduleCommandService | undefined;
|
||||
|
||||
function getCommands(): HubScheduleCommandService {
|
||||
if (!scheduleService || !scheduleCommands) {
|
||||
scheduleService = new HubScheduleService({
|
||||
runtimeHandlers: createLocalHubScheduleRuntimeHandlers(),
|
||||
});
|
||||
scheduleCommands = new HubScheduleCommandService(scheduleService);
|
||||
}
|
||||
return scheduleCommands;
|
||||
}
|
||||
|
||||
async function clientCommand(
|
||||
hubCommand: string,
|
||||
payload?: Record<string, unknown>,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const reply = await getCommands().handleCommand({
|
||||
version: "v1",
|
||||
clientId: "cline-hub-schedules",
|
||||
command: hubCommand as never,
|
||||
payload,
|
||||
});
|
||||
if (!reply.ok) {
|
||||
throw new Error(
|
||||
reply.error?.message ?? `hub command failed: ${hubCommand}`,
|
||||
);
|
||||
}
|
||||
return (reply.payload ?? {}) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
export async function handleRoutineScheduleCommand(
|
||||
command: string,
|
||||
args?: Record<string, unknown>,
|
||||
): Promise<unknown> {
|
||||
if (command === "list_routine_schedules") {
|
||||
const [schedules, activeExecutions, upcomingRuns] = await Promise.all([
|
||||
clientCommand("schedule.list", {
|
||||
limit: toPositiveInt(args?.limit) ?? 200,
|
||||
}),
|
||||
clientCommand("schedule.active"),
|
||||
clientCommand("schedule.upcoming", { limit: 30 }),
|
||||
]);
|
||||
const scheduleRows = Array.isArray(schedules.schedules)
|
||||
? schedules.schedules
|
||||
: [];
|
||||
const lastExecutions = await Promise.all(
|
||||
scheduleRows.map(async (schedule) => {
|
||||
const scheduleId = asTrimmedString(
|
||||
(schedule as Record<string, unknown>).scheduleId,
|
||||
);
|
||||
if (!scheduleId) return undefined;
|
||||
const reply = await clientCommand("schedule.list_executions", {
|
||||
scheduleId,
|
||||
limit: 1,
|
||||
});
|
||||
return Array.isArray(reply.executions)
|
||||
? reply.executions[0]
|
||||
: undefined;
|
||||
}),
|
||||
);
|
||||
return {
|
||||
schedules: scheduleRows,
|
||||
activeExecutions: activeExecutions.executions ?? [],
|
||||
upcomingRuns: upcomingRuns.runs ?? [],
|
||||
lastExecutions: lastExecutions.filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
if (command === "create_routine_schedule") {
|
||||
const name = asTrimmedString(args?.name);
|
||||
const cronPattern = asTrimmedString(args?.cron_pattern);
|
||||
const prompt = asTrimmedString(args?.prompt);
|
||||
const routineWorkspaceRoot = asTrimmedString(args?.workspace_root);
|
||||
if (!name || !cronPattern || !prompt || !routineWorkspaceRoot) {
|
||||
throw new Error(
|
||||
"createSchedule requires name, cron_pattern, prompt, and workspace_root",
|
||||
);
|
||||
}
|
||||
const created = await clientCommand("schedule.create", {
|
||||
name,
|
||||
cronPattern,
|
||||
prompt,
|
||||
modelSelection: {
|
||||
providerId: asTrimmedString(args?.provider) ?? "cline",
|
||||
modelId: asTrimmedString(args?.model) ?? "openai/gpt-5.3-codex",
|
||||
},
|
||||
mode: args?.mode === "plan" ? "plan" : "act",
|
||||
workspaceRoot: routineWorkspaceRoot,
|
||||
cwd: asTrimmedString(args?.cwd),
|
||||
systemPrompt: asTrimmedString(args?.system_prompt),
|
||||
maxIterations: toPositiveInt(args?.max_iterations),
|
||||
timeoutSeconds: toPositiveInt(args?.timeout_seconds),
|
||||
maxParallel: toPositiveInt(args?.max_parallel) ?? 1,
|
||||
enabled: args?.enabled !== false,
|
||||
tags:
|
||||
Array.isArray(args?.tags) && args.tags.length > 0
|
||||
? (args.tags as string[])
|
||||
.map((v) => v.trim())
|
||||
.filter((v) => v.length > 0)
|
||||
: undefined,
|
||||
});
|
||||
return { schedule: created.schedule ?? null };
|
||||
}
|
||||
|
||||
const scheduleId = asTrimmedString(args?.schedule_id);
|
||||
if (!scheduleId) throw new Error(`${command} requires schedule_id`);
|
||||
if (command === "update_routine_schedule") {
|
||||
const name = asTrimmedString(args?.name);
|
||||
const cronPattern = asTrimmedString(args?.cron_pattern);
|
||||
const prompt = asTrimmedString(args?.prompt);
|
||||
const routineWorkspaceRoot = asTrimmedString(args?.workspace_root);
|
||||
if (!name || !cronPattern || !prompt || !routineWorkspaceRoot) {
|
||||
throw new Error(
|
||||
"updateSchedule requires schedule_id, name, cron_pattern, prompt, and workspace_root",
|
||||
);
|
||||
}
|
||||
const reply = await clientCommand("schedule.update", {
|
||||
scheduleId,
|
||||
name,
|
||||
cronPattern,
|
||||
prompt,
|
||||
modelSelection: {
|
||||
providerId: asTrimmedString(args?.provider) ?? "cline",
|
||||
modelId: asTrimmedString(args?.model) ?? "openai/gpt-5.3-codex",
|
||||
},
|
||||
mode: args?.mode === "plan" ? "plan" : "act",
|
||||
workspaceRoot: routineWorkspaceRoot,
|
||||
cwd: asTrimmedString(args?.cwd) ?? null,
|
||||
systemPrompt:
|
||||
args?.system_prompt === null
|
||||
? null
|
||||
: asTrimmedString(args?.system_prompt),
|
||||
maxIterations:
|
||||
args?.max_iterations === null
|
||||
? null
|
||||
: toPositiveInt(args?.max_iterations),
|
||||
timeoutSeconds:
|
||||
args?.timeout_seconds === null
|
||||
? null
|
||||
: toPositiveInt(args?.timeout_seconds),
|
||||
maxParallel: toPositiveInt(args?.max_parallel) ?? 1,
|
||||
enabled: args?.enabled !== false,
|
||||
tags: Array.isArray(args?.tags)
|
||||
? (args.tags as string[])
|
||||
.map((v) => v.trim())
|
||||
.filter((v) => v.length > 0)
|
||||
: [],
|
||||
});
|
||||
return { schedule: reply.schedule ?? null };
|
||||
}
|
||||
if (command === "pause_routine_schedule") {
|
||||
const reply = await clientCommand("schedule.disable", { scheduleId });
|
||||
return { schedule: reply.schedule ?? null };
|
||||
}
|
||||
if (command === "resume_routine_schedule") {
|
||||
const reply = await clientCommand("schedule.enable", { scheduleId });
|
||||
return { schedule: reply.schedule ?? null };
|
||||
}
|
||||
if (command === "trigger_routine_schedule") {
|
||||
const existing = await clientCommand("schedule.get", { scheduleId });
|
||||
if (!existing.schedule)
|
||||
throw new Error(`schedule not found: ${scheduleId}`);
|
||||
const reply = await clientCommand("schedule.trigger", {
|
||||
scheduleId,
|
||||
wait: false,
|
||||
});
|
||||
return { execution: reply.execution ?? null };
|
||||
}
|
||||
if (command === "delete_routine_schedule") {
|
||||
const reply = await clientCommand("schedule.delete", { scheduleId });
|
||||
return { deleted: reply.deleted === true };
|
||||
}
|
||||
throw new Error(`unsupported routine schedule command: ${command}`);
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
import type {
|
||||
WebviewActionSessionSummary,
|
||||
WebviewChatMessage,
|
||||
WebviewClientSummary,
|
||||
WebviewOutboundMessage,
|
||||
WebviewSessionSummary,
|
||||
} from "../webview-protocol";
|
||||
import type { HubContext } from "./state";
|
||||
import type { SessionContext, TrackedClient, TrackedSession } from "./types";
|
||||
import {
|
||||
asNumber,
|
||||
asString,
|
||||
asTimestamp,
|
||||
basename,
|
||||
formatClientLabel,
|
||||
isActiveSession,
|
||||
stringifyContent,
|
||||
} from "./utils";
|
||||
|
||||
function metadataFor(record: Record<string, unknown>): Record<string, unknown> {
|
||||
return (
|
||||
(record.metadata && typeof record.metadata === "object"
|
||||
? (record.metadata as Record<string, unknown>)
|
||||
: undefined) ?? {}
|
||||
);
|
||||
}
|
||||
|
||||
function usageFor(record: Record<string, unknown>): Record<string, unknown> {
|
||||
const metadata = metadataFor(record);
|
||||
const pick = (value: unknown): Record<string, unknown> | undefined =>
|
||||
value && typeof value === "object"
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined;
|
||||
return (
|
||||
pick(record.aggregateUsage) ??
|
||||
pick(record.usage) ??
|
||||
pick(metadata.aggregateUsage) ??
|
||||
pick(metadata.usage) ??
|
||||
{}
|
||||
);
|
||||
}
|
||||
|
||||
function sessionTitle(record: Record<string, unknown>): string {
|
||||
const metadata = metadataFor(record);
|
||||
const title = asString(metadata.title);
|
||||
if (title) return title;
|
||||
const prompt = asString(record.prompt) ?? asString(metadata.prompt);
|
||||
if (prompt) return prompt.length > 34 ? `${prompt.slice(0, 31)}...` : prompt;
|
||||
return basename(asString(record.workspaceRoot) ?? asString(record.cwd));
|
||||
}
|
||||
|
||||
export function formatClientName(client: TrackedClient): string {
|
||||
return (
|
||||
client.displayName?.trim() ||
|
||||
client.clientType.trim() ||
|
||||
client.clientId.trim() ||
|
||||
"Unknown"
|
||||
);
|
||||
}
|
||||
|
||||
export function formatSessionCreator(
|
||||
ctx: HubContext,
|
||||
session: TrackedSession,
|
||||
): string {
|
||||
const clientId = session.createdByClientId?.trim();
|
||||
if (!clientId) return "Unknown client";
|
||||
const client = ctx.clients.get(clientId);
|
||||
return client ? formatClientName(client) : clientId;
|
||||
}
|
||||
|
||||
function summarizeClient(client: TrackedClient): {
|
||||
key: string;
|
||||
label: string;
|
||||
name: string;
|
||||
} {
|
||||
const normalizedType = client.clientType.trim().toLowerCase();
|
||||
if (
|
||||
normalizedType === "code-sidecar" ||
|
||||
normalizedType === "code-sidecar-approvals" ||
|
||||
normalizedType === "code-sidecar-list"
|
||||
) {
|
||||
return { key: "code-app", label: "Code App", name: "Code App" };
|
||||
}
|
||||
return {
|
||||
key: client.clientId,
|
||||
label: formatClientLabel(client.clientType),
|
||||
name: formatClientName(client),
|
||||
};
|
||||
}
|
||||
|
||||
export function mapHistoryToWebviewMessages(
|
||||
history: unknown[],
|
||||
): WebviewChatMessage[] {
|
||||
return history.map((entry, index) => {
|
||||
const record =
|
||||
entry && typeof entry === "object"
|
||||
? (entry as Record<string, unknown>)
|
||||
: { content: entry };
|
||||
const rawRole = asString(record.role)?.toLowerCase();
|
||||
const role: WebviewChatMessage["role"] =
|
||||
rawRole === "user" || rawRole === "assistant" || rawRole === "error"
|
||||
? rawRole
|
||||
: "meta";
|
||||
const text = stringifyContent(record.content ?? record.text ?? record);
|
||||
return {
|
||||
id: asString(record.id) ?? `history-${index}`,
|
||||
role,
|
||||
text,
|
||||
blocks: text ? [{ id: `history-${index}-text`, type: "text", text }] : [],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function trackSession(record: unknown): TrackedSession | undefined {
|
||||
const raw =
|
||||
record && typeof record === "object"
|
||||
? (record as Record<string, unknown>)
|
||||
: {};
|
||||
const sessionId = asString(raw.sessionId);
|
||||
if (!sessionId) return undefined;
|
||||
const metadata = metadataFor(raw);
|
||||
const usage = usageFor(raw);
|
||||
const participantCount = Array.isArray(raw.participants)
|
||||
? raw.participants.length
|
||||
: 0;
|
||||
const createdAt =
|
||||
asTimestamp(raw.createdAt) ??
|
||||
asTimestamp(raw.startedAt) ??
|
||||
asTimestamp(metadata.createdAt) ??
|
||||
Date.now();
|
||||
return {
|
||||
sessionId,
|
||||
status: asString(raw.status) ?? "running",
|
||||
title: sessionTitle(raw),
|
||||
workspaceRoot: asString(raw.workspaceRoot) ?? asString(raw.cwd) ?? "",
|
||||
cwd: asString(raw.cwd),
|
||||
provider: asString(raw.provider) ?? asString(metadata.provider),
|
||||
model: asString(raw.model) ?? asString(metadata.model),
|
||||
source: asString(raw.source) ?? asString(metadata.source),
|
||||
createdAt,
|
||||
updatedAt:
|
||||
asTimestamp(raw.updatedAt) ??
|
||||
asTimestamp(raw.endedAt) ??
|
||||
asTimestamp(metadata.updatedAt) ??
|
||||
createdAt,
|
||||
createdByClientId: asString(raw.createdByClientId),
|
||||
prompt: asString(raw.prompt) ?? asString(metadata.prompt),
|
||||
inputTokens:
|
||||
asNumber(usage.inputTokens) ??
|
||||
asNumber(usage.input) ??
|
||||
asNumber(usage.totalInputTokens),
|
||||
outputTokens:
|
||||
asNumber(usage.outputTokens) ??
|
||||
asNumber(usage.output) ??
|
||||
asNumber(usage.totalOutputTokens),
|
||||
totalCost: asNumber(usage.totalCost) ?? asNumber(metadata.totalCost),
|
||||
agentCount: Math.max(1, participantCount),
|
||||
participantCount,
|
||||
};
|
||||
}
|
||||
|
||||
export function toActionSessionSummary(
|
||||
session: TrackedSession,
|
||||
): WebviewActionSessionSummary {
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
title: session.title || basename(session.workspaceRoot || session.cwd),
|
||||
status: session.status,
|
||||
workspaceRoot: session.workspaceRoot,
|
||||
workspaceName: basename(session.workspaceRoot || session.cwd),
|
||||
cwd: session.cwd,
|
||||
model: session.model,
|
||||
provider: session.provider,
|
||||
createdAt: session.createdAt,
|
||||
updatedAt: session.updatedAt,
|
||||
createdByClientId: session.createdByClientId,
|
||||
prompt: session.prompt,
|
||||
inputTokens: session.inputTokens,
|
||||
outputTokens: session.outputTokens,
|
||||
totalCost: session.totalCost,
|
||||
agentCount: session.agentCount,
|
||||
};
|
||||
}
|
||||
|
||||
export function clientSummariesPayload(
|
||||
ctx: HubContext,
|
||||
): WebviewClientSummary[] {
|
||||
const sessionCounts = new Map<string, number>();
|
||||
for (const session of ctx.sessions.values()) {
|
||||
if (
|
||||
!isActiveSession(session.title, session.status, session.participantCount)
|
||||
)
|
||||
continue;
|
||||
const clientId = session.createdByClientId?.trim();
|
||||
if (!clientId) continue;
|
||||
sessionCounts.set(clientId, (sessionCounts.get(clientId) ?? 0) + 1);
|
||||
}
|
||||
const grouped = new Map<
|
||||
string,
|
||||
WebviewClientSummary & { firstConnectedAt: number }
|
||||
>();
|
||||
for (const client of [...ctx.clients.values()].sort(
|
||||
(a, b) => a.connectedAt - b.connectedAt,
|
||||
)) {
|
||||
const summary = summarizeClient(client);
|
||||
const existing = grouped.get(summary.key);
|
||||
if (existing) {
|
||||
existing.sessionCount += sessionCounts.get(client.clientId) ?? 0;
|
||||
existing.firstConnectedAt = Math.min(
|
||||
existing.firstConnectedAt,
|
||||
client.connectedAt,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
grouped.set(summary.key, {
|
||||
label: summary.label,
|
||||
name: summary.name,
|
||||
sessionCount: sessionCounts.get(client.clientId) ?? 0,
|
||||
firstConnectedAt: client.connectedAt,
|
||||
});
|
||||
}
|
||||
return [...grouped.values()]
|
||||
.sort((a, b) => a.firstConnectedAt - b.firstConnectedAt)
|
||||
.map(({ label, name, sessionCount }) => ({ label, name, sessionCount }));
|
||||
}
|
||||
|
||||
export function toWebviewSessionSummary(
|
||||
session: TrackedSession,
|
||||
): WebviewSessionSummary {
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
title: session.title,
|
||||
status: session.status,
|
||||
source: session.source,
|
||||
providerId: session.provider,
|
||||
model: session.model,
|
||||
workspaceRoot: session.workspaceRoot,
|
||||
updatedAt: session.updatedAt,
|
||||
inputTokens: session.inputTokens,
|
||||
outputTokens: session.outputTokens,
|
||||
totalCost: session.totalCost,
|
||||
};
|
||||
}
|
||||
|
||||
export function webviewSessionsPayload(
|
||||
ctx: HubContext,
|
||||
): WebviewOutboundMessage {
|
||||
return {
|
||||
type: "sessions",
|
||||
sessions: [...ctx.sessions.values()]
|
||||
.sort((a, b) => b.updatedAt - a.updatedAt)
|
||||
.map(toWebviewSessionSummary),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSessionContext(
|
||||
record: unknown,
|
||||
): SessionContext | undefined {
|
||||
const raw =
|
||||
record && typeof record === "object"
|
||||
? (record as Record<string, unknown>)
|
||||
: {};
|
||||
const metadata =
|
||||
raw.metadata && typeof raw.metadata === "object"
|
||||
? (raw.metadata as Record<string, unknown>)
|
||||
: {};
|
||||
const workspaceRootRaw = asString(raw.workspaceRoot);
|
||||
const providerId =
|
||||
asString(raw.providerId) ??
|
||||
asString(metadata.providerId) ??
|
||||
asString(raw.provider) ??
|
||||
asString(metadata.provider);
|
||||
const modelId =
|
||||
asString(raw.modelId) ??
|
||||
asString(metadata.modelId) ??
|
||||
asString(raw.model) ??
|
||||
asString(metadata.model);
|
||||
if (!workspaceRootRaw || !providerId || !modelId) return undefined;
|
||||
return {
|
||||
workspaceRoot: workspaceRootRaw,
|
||||
cwd: asString(raw.cwd) ?? workspaceRootRaw,
|
||||
providerId,
|
||||
modelId,
|
||||
};
|
||||
}
|
||||
@@ -1,483 +0,0 @@
|
||||
import process from "node:process";
|
||||
import {
|
||||
type ClineCoreStartInput,
|
||||
type SessionRecord,
|
||||
SessionSource,
|
||||
} from "@cline/core";
|
||||
import type { Message } from "@cline/llms";
|
||||
import type { WebviewConfig, WebviewReasonLevel } from "../webview-protocol";
|
||||
import { rejectPendingApprovalsForSession } from "./approvals";
|
||||
import { providerSettingsManager, workspaceRoot } from "./deps";
|
||||
import {
|
||||
loadProviders,
|
||||
resolveBrowserDefaults,
|
||||
sendProviderCatalog,
|
||||
} from "./providers";
|
||||
import {
|
||||
mapHistoryToWebviewMessages,
|
||||
trackSession,
|
||||
webviewSessionsPayload,
|
||||
} from "./session-mapping";
|
||||
import type { HubContext } from "./state";
|
||||
import { broadcastHubState, hubStatePayload } from "./state-payloads";
|
||||
import type { BrowserPeer, SessionContext } from "./types";
|
||||
import { asNumber, asString } from "./utils";
|
||||
|
||||
function toRuntimeReasoningOptions(
|
||||
reasonLevel?: WebviewReasonLevel,
|
||||
): Pick<ClineCoreStartInput["config"], "reasoningEffort" | "thinking"> {
|
||||
if (reasonLevel === undefined) return {};
|
||||
if (reasonLevel === "none") return { thinking: false };
|
||||
return { thinking: true, reasoningEffort: reasonLevel };
|
||||
}
|
||||
|
||||
function asWebviewReasonLevel(value: unknown): WebviewReasonLevel | undefined {
|
||||
return value === "none" ||
|
||||
value === "low" ||
|
||||
value === "medium" ||
|
||||
value === "high"
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function resolveLaunchContext(
|
||||
ctx: HubContext,
|
||||
override?: Partial<SessionContext> & WebviewConfig,
|
||||
): SessionContext {
|
||||
const providerId =
|
||||
override?.provider ??
|
||||
override?.providerId ??
|
||||
ctx.lastSessionContext?.providerId ??
|
||||
providerSettingsManager.getLastUsedProviderSettings()?.provider ??
|
||||
process.env.CLINE_PROVIDER?.trim() ??
|
||||
"";
|
||||
const modelId =
|
||||
override?.model ??
|
||||
override?.modelId ??
|
||||
ctx.lastSessionContext?.modelId ??
|
||||
providerSettingsManager.getLastUsedProviderSettings()?.model ??
|
||||
process.env.CLINE_MODEL?.trim() ??
|
||||
"";
|
||||
const root =
|
||||
override?.workspaceRoot ??
|
||||
ctx.lastSessionContext?.workspaceRoot ??
|
||||
workspaceRoot;
|
||||
if (!providerId || !modelId) {
|
||||
throw new Error(
|
||||
"No provider/model available. Start a session in another Cline client first, or set CLINE_PROVIDER and CLINE_MODEL.",
|
||||
);
|
||||
}
|
||||
return {
|
||||
workspaceRoot: root,
|
||||
cwd: override?.cwd ?? ctx.lastSessionContext?.cwd ?? root,
|
||||
providerId,
|
||||
modelId,
|
||||
};
|
||||
}
|
||||
|
||||
function buildSessionStartInput(
|
||||
context: SessionContext,
|
||||
options?: {
|
||||
mode?: "act" | "plan";
|
||||
systemPrompt?: string;
|
||||
maxIterations?: number;
|
||||
reasonLevel?: WebviewReasonLevel;
|
||||
enableTools?: boolean;
|
||||
enableSpawn?: boolean;
|
||||
enableTeams?: boolean;
|
||||
autoApproveTools?: boolean;
|
||||
teamName?: string;
|
||||
source?: SessionSource;
|
||||
sessionMetadata?: Record<string, unknown>;
|
||||
initialMessages?: Message[];
|
||||
},
|
||||
): ClineCoreStartInput {
|
||||
const mode = options?.mode === "plan" ? "plan" : "act";
|
||||
const reasoningOptions = toRuntimeReasoningOptions(options?.reasonLevel);
|
||||
return {
|
||||
source: options?.source ?? SessionSource.WEB,
|
||||
interactive: true,
|
||||
config: {
|
||||
workspaceRoot: context.workspaceRoot,
|
||||
cwd: context.cwd,
|
||||
providerId: context.providerId,
|
||||
modelId: context.modelId,
|
||||
systemPrompt: options?.systemPrompt ?? "",
|
||||
mode,
|
||||
...reasoningOptions,
|
||||
maxIterations: options?.maxIterations,
|
||||
enableTools: options?.enableTools !== false,
|
||||
enableSpawnAgent: options?.enableSpawn !== false,
|
||||
enableAgentTeams: options?.enableTeams === true,
|
||||
teamName: options?.teamName ?? "cline-hub",
|
||||
missionLogIntervalSteps: 3,
|
||||
missionLogIntervalMs: 120000,
|
||||
checkpoint: { enabled: true },
|
||||
},
|
||||
sessionMetadata: {
|
||||
source: options?.source ?? SessionSource.WEB,
|
||||
mode,
|
||||
systemPrompt: options?.systemPrompt,
|
||||
maxIterations: options?.maxIterations,
|
||||
reasonLevel: options?.reasonLevel,
|
||||
autoApproveTools: options?.autoApproveTools,
|
||||
...(options?.sessionMetadata ?? {}),
|
||||
},
|
||||
...(options?.initialMessages
|
||||
? { initialMessages: options.initialMessages }
|
||||
: {}),
|
||||
toolPolicies:
|
||||
options?.autoApproveTools === false
|
||||
? { "*": { autoApprove: false } }
|
||||
: { "*": { autoApprove: true } },
|
||||
};
|
||||
}
|
||||
|
||||
function buildStartInputFromSession(
|
||||
session: SessionRecord,
|
||||
options?: {
|
||||
sessionMetadata?: Record<string, unknown>;
|
||||
initialMessages?: Message[];
|
||||
},
|
||||
) {
|
||||
const metadata =
|
||||
session.metadata && typeof session.metadata === "object"
|
||||
? session.metadata
|
||||
: {};
|
||||
const mode = metadata.mode === "plan" ? "plan" : "act";
|
||||
return buildSessionStartInput(
|
||||
{
|
||||
workspaceRoot: session.workspaceRoot,
|
||||
cwd: session.cwd,
|
||||
providerId: session.provider,
|
||||
modelId: session.model,
|
||||
},
|
||||
{
|
||||
mode,
|
||||
systemPrompt: asString(metadata.systemPrompt),
|
||||
maxIterations: asNumber(metadata.maxIterations),
|
||||
reasonLevel: asWebviewReasonLevel(metadata.reasonLevel),
|
||||
enableTools: session.enableTools,
|
||||
enableSpawn: session.enableSpawn,
|
||||
enableTeams: session.enableTeams,
|
||||
autoApproveTools:
|
||||
typeof metadata.autoApproveTools === "boolean"
|
||||
? metadata.autoApproveTools
|
||||
: undefined,
|
||||
teamName: session.teamName,
|
||||
source: session.source,
|
||||
sessionMetadata: { ...metadata, ...(options?.sessionMetadata ?? {}) },
|
||||
initialMessages: options?.initialMessages,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function loadHistoryFor(
|
||||
ctx: HubContext,
|
||||
sessionId: string,
|
||||
): Promise<unknown[]> {
|
||||
if (!ctx.cline) return [];
|
||||
try {
|
||||
return (await ctx.cline.readMessages(sessionId)) as unknown[];
|
||||
} catch (error) {
|
||||
console.warn(`readMessages(${sessionId}) failed:`, error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function selectSession(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
sessionId: string,
|
||||
): Promise<void> {
|
||||
peer.selectedSessionId = sessionId;
|
||||
const tracked = ctx.sessions.get(sessionId);
|
||||
const history = await loadHistoryFor(ctx, sessionId);
|
||||
ctx.send(peer, { type: "session_started", sessionId });
|
||||
ctx.send(peer, {
|
||||
type: "session_hydrated",
|
||||
sessionId,
|
||||
status: tracked?.status,
|
||||
providerId: tracked?.provider,
|
||||
modelId: tracked?.model,
|
||||
messages: mapHistoryToWebviewMessages(history),
|
||||
});
|
||||
}
|
||||
|
||||
export async function createSession(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
prompt: string,
|
||||
config?: WebviewConfig,
|
||||
attachments?: { userImages?: string[] },
|
||||
): Promise<void> {
|
||||
if (!ctx.cline) throw new Error("Hub is not connected.");
|
||||
const context = resolveLaunchContext(ctx, config);
|
||||
const mode = config?.mode === "plan" ? "plan" : "act";
|
||||
const result = await ctx.cline.start(
|
||||
buildSessionStartInput(context, {
|
||||
mode,
|
||||
systemPrompt: config?.systemPrompt,
|
||||
maxIterations: config?.maxIterations,
|
||||
reasonLevel: config?.reasonLevel,
|
||||
enableTools: config?.enableTools,
|
||||
enableSpawn: config?.enableSpawn,
|
||||
enableTeams: config?.enableTeams,
|
||||
autoApproveTools: config?.autoApproveTools,
|
||||
}),
|
||||
);
|
||||
peer.selectedSessionId = result.sessionId;
|
||||
ctx.sessions.set(result.sessionId, {
|
||||
sessionId: result.sessionId,
|
||||
status: "running",
|
||||
title: prompt.length > 34 ? `${prompt.slice(0, 31)}...` : prompt,
|
||||
workspaceRoot: context.workspaceRoot,
|
||||
cwd: context.cwd,
|
||||
provider: context.providerId,
|
||||
model: context.modelId,
|
||||
source: SessionSource.WEB,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
prompt,
|
||||
agentCount: 1,
|
||||
participantCount: 1,
|
||||
});
|
||||
const tracked = ctx.sessions.get(result.sessionId);
|
||||
ctx.send(peer, { type: "session_started", sessionId: result.sessionId });
|
||||
ctx.send(peer, {
|
||||
type: "session_hydrated",
|
||||
sessionId: result.sessionId,
|
||||
status: tracked?.status,
|
||||
providerId: context.providerId,
|
||||
modelId: context.modelId,
|
||||
messages: [],
|
||||
});
|
||||
broadcastHubState(ctx);
|
||||
await ctx.cline.send({
|
||||
sessionId: result.sessionId,
|
||||
prompt,
|
||||
mode,
|
||||
userImages: attachments?.userImages,
|
||||
});
|
||||
}
|
||||
|
||||
export async function sendMessage(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
text: string,
|
||||
config?: WebviewConfig,
|
||||
attachments?: { userImages?: string[] },
|
||||
): Promise<void> {
|
||||
if (!ctx.cline) throw new Error("Hub is not connected.");
|
||||
if (!peer.selectedSessionId) {
|
||||
await createSession(ctx, peer, text, config, attachments);
|
||||
return;
|
||||
}
|
||||
await ctx.cline.send({
|
||||
sessionId: peer.selectedSessionId,
|
||||
prompt: text,
|
||||
mode: config?.mode === "plan" ? "plan" : "act",
|
||||
userImages: attachments?.userImages,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteSession(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
sessionId: string,
|
||||
): Promise<void> {
|
||||
if (!ctx.cline) throw new Error("Hub is not connected.");
|
||||
const deleted = await ctx.cline.delete(sessionId);
|
||||
if (!deleted) {
|
||||
ctx.send(peer, {
|
||||
type: "status",
|
||||
text: `Session ${sessionId} was not found.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
ctx.sessions.delete(sessionId);
|
||||
if (peer.selectedSessionId === sessionId) {
|
||||
peer.selectedSessionId = undefined;
|
||||
ctx.send(peer, { type: "reset_done" });
|
||||
}
|
||||
ctx.send(peer, { type: "status", text: `Deleted session ${sessionId}` });
|
||||
broadcastHubState(ctx);
|
||||
}
|
||||
|
||||
export async function resetPeer(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
): Promise<void> {
|
||||
if (peer.selectedSessionId) {
|
||||
rejectPendingApprovalsForSession(
|
||||
ctx,
|
||||
peer.selectedSessionId,
|
||||
"Session detached before approval was resolved.",
|
||||
);
|
||||
}
|
||||
peer.selectedSessionId = undefined;
|
||||
ctx.send(peer, { type: "reset_done" });
|
||||
ctx.send(peer, webviewSessionsPayload(ctx));
|
||||
}
|
||||
|
||||
export async function abortPeerTurn(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
): Promise<void> {
|
||||
if (!ctx.cline || !peer.selectedSessionId) return;
|
||||
rejectPendingApprovalsForSession(
|
||||
ctx,
|
||||
peer.selectedSessionId,
|
||||
"Turn aborted before approval was resolved.",
|
||||
);
|
||||
await ctx.cline.abort(peer.selectedSessionId);
|
||||
ctx.send(peer, { type: "status", text: "Abort requested." });
|
||||
}
|
||||
|
||||
export async function forkPeerSession(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
syncHubClientsAndSessions: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
if (!ctx.cline) throw new Error("Hub is not connected.");
|
||||
const forkedFromSessionId = peer.selectedSessionId;
|
||||
if (!forkedFromSessionId) {
|
||||
ctx.send(peer, { type: "fork_error", text: "No active session to fork." });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const rawMessages = (await ctx.cline.readMessages(
|
||||
forkedFromSessionId,
|
||||
)) as Message[];
|
||||
if (rawMessages.length === 0) {
|
||||
ctx.send(peer, {
|
||||
type: "fork_error",
|
||||
text: "Cannot fork an empty session.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const sourceSession = await ctx.cline.get(forkedFromSessionId);
|
||||
if (!sourceSession) {
|
||||
ctx.send(peer, {
|
||||
type: "fork_error",
|
||||
text: `Session ${forkedFromSessionId} was not found.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const checkpointMetadata = sourceSession.metadata?.checkpoint;
|
||||
const result = await ctx.cline.start(
|
||||
buildStartInputFromSession(sourceSession, {
|
||||
initialMessages: rawMessages,
|
||||
sessionMetadata: {
|
||||
...(sourceSession.metadata ?? {}),
|
||||
fork: {
|
||||
forkedFromSessionId,
|
||||
forkedAt: new Date().toISOString(),
|
||||
source: sourceSession.source,
|
||||
...(checkpointMetadata !== undefined
|
||||
? { checkpoints: checkpointMetadata }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
peer.selectedSessionId = result.sessionId;
|
||||
const newSession = await ctx.cline.get(result.sessionId);
|
||||
const tracked = newSession ? trackSession(newSession) : undefined;
|
||||
if (tracked) ctx.sessions.set(tracked.sessionId, tracked);
|
||||
ctx.send(peer, { type: "session_started", sessionId: result.sessionId });
|
||||
ctx.send(peer, {
|
||||
type: "session_hydrated",
|
||||
sessionId: result.sessionId,
|
||||
status: newSession?.status,
|
||||
providerId: newSession?.provider,
|
||||
modelId: newSession?.model,
|
||||
messages: mapHistoryToWebviewMessages(rawMessages),
|
||||
});
|
||||
ctx.send(peer, {
|
||||
type: "fork_done",
|
||||
forkedFromSessionId,
|
||||
newSessionId: result.sessionId,
|
||||
});
|
||||
await syncHubClientsAndSessions();
|
||||
broadcastHubState(ctx);
|
||||
} catch (error) {
|
||||
ctx.send(peer, {
|
||||
type: "fork_error",
|
||||
text: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function restorePeerSession(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
checkpointRunCount: number,
|
||||
syncHubClientsAndSessions: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
if (!ctx.cline) throw new Error("Hub is not connected.");
|
||||
const sourceSessionId = peer.selectedSessionId;
|
||||
if (!sourceSessionId) {
|
||||
ctx.send(peer, { type: "error", text: "No active session to restore." });
|
||||
return;
|
||||
}
|
||||
const sourceSession = await ctx.cline.get(sourceSessionId);
|
||||
if (!sourceSession) {
|
||||
ctx.send(peer, {
|
||||
type: "error",
|
||||
text: `Session ${sourceSessionId} was not found.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const result = await ctx.cline.restore({
|
||||
sessionId: sourceSessionId,
|
||||
checkpointRunCount,
|
||||
cwd: sourceSession.cwd,
|
||||
start: buildStartInputFromSession(sourceSession, {
|
||||
sessionMetadata: {
|
||||
...(sourceSession.metadata ?? {}),
|
||||
restoredFromSessionId: sourceSessionId,
|
||||
restoredCheckpointRunCount: checkpointRunCount,
|
||||
},
|
||||
}),
|
||||
restore: { messages: true, workspace: true },
|
||||
});
|
||||
if (!result.sessionId) {
|
||||
ctx.send(peer, {
|
||||
type: "error",
|
||||
text: "Checkpoint restore did not start a session.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
peer.selectedSessionId = result.sessionId;
|
||||
const restoredSession = await ctx.cline.get(result.sessionId);
|
||||
const tracked = restoredSession ? trackSession(restoredSession) : undefined;
|
||||
if (tracked) ctx.sessions.set(tracked.sessionId, tracked);
|
||||
const messages =
|
||||
result.messages ?? (await loadHistoryFor(ctx, result.sessionId));
|
||||
ctx.send(peer, { type: "session_started", sessionId: result.sessionId });
|
||||
ctx.send(peer, {
|
||||
type: "session_hydrated",
|
||||
sessionId: result.sessionId,
|
||||
status: restoredSession?.status,
|
||||
providerId: restoredSession?.provider,
|
||||
modelId: restoredSession?.model,
|
||||
messages: mapHistoryToWebviewMessages(messages),
|
||||
});
|
||||
await syncHubClientsAndSessions();
|
||||
broadcastHubState(ctx);
|
||||
}
|
||||
|
||||
export async function initializePeer(
|
||||
ctx: HubContext,
|
||||
peer: BrowserPeer,
|
||||
syncHubClientsAndSessions: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
await syncHubClientsAndSessions();
|
||||
ctx.send(peer, { type: "status", text: "Cline Hub is ready." });
|
||||
ctx.send(peer, { type: "defaults", defaults: resolveBrowserDefaults(ctx) });
|
||||
await loadProviders(ctx, peer);
|
||||
await sendProviderCatalog(ctx, peer);
|
||||
ctx.send(peer, webviewSessionsPayload(ctx));
|
||||
ctx.send(peer, hubStatePayload(ctx));
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { listActiveConnectors } from "../../../cli/src/connectors/status";
|
||||
import type { WebviewHubState } from "../webview-protocol";
|
||||
import {
|
||||
clientSummariesPayload,
|
||||
toActionSessionSummary,
|
||||
webviewSessionsPayload,
|
||||
} from "./session-mapping";
|
||||
import type { HubContext } from "./state";
|
||||
import { formatUptime, isActiveSession } from "./utils";
|
||||
|
||||
function activeSessionSummaries(ctx: HubContext) {
|
||||
return [...ctx.sessions.values()]
|
||||
.filter((session) =>
|
||||
isActiveSession(session.title, session.status, session.participantCount),
|
||||
)
|
||||
.sort((a, b) => b.updatedAt - a.updatedAt)
|
||||
.map(toActionSessionSummary);
|
||||
}
|
||||
|
||||
export function hubStatePayload(ctx: HubContext): WebviewHubState {
|
||||
const sessionSummaries = activeSessionSummaries(ctx);
|
||||
const clientList = [...ctx.clients.values()].sort(
|
||||
(a, b) => a.connectedAt - b.connectedAt,
|
||||
);
|
||||
return {
|
||||
type: "hub_state",
|
||||
connected: Boolean(ctx.cline && ctx.uiClient),
|
||||
hubUrl: ctx.hubUrl,
|
||||
hubStartedAt: ctx.hubStartedAt,
|
||||
coreVersion: ctx.coreVersion,
|
||||
hubUptime: ctx.hubStartedAt
|
||||
? formatUptime(Date.now() - Date.parse(ctx.hubStartedAt))
|
||||
: undefined,
|
||||
clients: clientList,
|
||||
connectors: listActiveConnectors(),
|
||||
sessions: sessionSummaries,
|
||||
clientSummaries: clientSummariesPayload(ctx),
|
||||
sessionSummaries,
|
||||
events: ctx.events,
|
||||
lastWorkspaceRoot: ctx.lastSessionContext?.workspaceRoot,
|
||||
};
|
||||
}
|
||||
|
||||
export function hubStatusPayload(ctx: HubContext) {
|
||||
const clientList = [...ctx.clients.values()].sort(
|
||||
(a, b) => a.connectedAt - b.connectedAt,
|
||||
);
|
||||
const sessionSummaries = activeSessionSummaries(ctx);
|
||||
return {
|
||||
address: ctx.hubUrl,
|
||||
status: ctx.hubHealthy ? "healthy" : "unhealthy",
|
||||
healthy: ctx.hubHealthy,
|
||||
connected: Boolean(ctx.cline && ctx.uiClient),
|
||||
startedAt: ctx.hubStartedAt,
|
||||
uptime: ctx.hubStartedAt
|
||||
? formatUptime(Date.now() - Date.parse(ctx.hubStartedAt))
|
||||
: undefined,
|
||||
coreVersion: ctx.coreVersion,
|
||||
clients: clientList.map((client) => ({
|
||||
clientId: client.clientId,
|
||||
displayName: client.displayName,
|
||||
clientType: client.clientType,
|
||||
connectedAt: new Date(client.connectedAt).toISOString(),
|
||||
})),
|
||||
activeSessions: sessionSummaries.length,
|
||||
};
|
||||
}
|
||||
|
||||
export function broadcastHubState(ctx: HubContext): void {
|
||||
ctx.broadcast(hubStatePayload(ctx));
|
||||
ctx.broadcast(webviewSessionsPayload(ctx));
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
import {
|
||||
type ClineCore,
|
||||
CORE_BUILD_VERSION,
|
||||
type HubUIClient,
|
||||
} from "@cline/core";
|
||||
import type { WebviewHubEvent } from "../webview-protocol";
|
||||
import type {
|
||||
BrowserPeer,
|
||||
PendingToolApproval,
|
||||
SessionContext,
|
||||
TrackedClient,
|
||||
TrackedSession,
|
||||
} from "./types";
|
||||
|
||||
/**
|
||||
* Shared mutable runtime state for the Cline Hub server. A single instance is
|
||||
* created in `server.ts` and threaded through the feature modules, replacing
|
||||
* what used to be a wall of module-level `let`s in the monolithic file.
|
||||
*/
|
||||
export class HubContext {
|
||||
readonly peers = new Set<BrowserPeer>();
|
||||
readonly clients = new Map<string, TrackedClient>();
|
||||
readonly sessions = new Map<string, TrackedSession>();
|
||||
readonly pendingToolApprovals = new Map<string, PendingToolApproval>();
|
||||
readonly events: WebviewHubEvent[] = [];
|
||||
|
||||
hubUrl = "";
|
||||
hubAuthToken = "";
|
||||
hubHealthy = false;
|
||||
cline: ClineCore | undefined;
|
||||
uiClient: HubUIClient | undefined;
|
||||
hubStartedAt: string | undefined;
|
||||
coreVersion: string | undefined = CORE_BUILD_VERSION;
|
||||
lastSessionContext: SessionContext | undefined;
|
||||
initialHubEventEmitted = false;
|
||||
|
||||
send(peer: BrowserPeer, payload: unknown): void {
|
||||
peer.socket.send(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
broadcast(payload: unknown): void {
|
||||
const data = JSON.stringify(payload);
|
||||
for (const peer of this.peers) {
|
||||
peer.socket.send(data);
|
||||
}
|
||||
}
|
||||
|
||||
pushEvent(
|
||||
title: string,
|
||||
body: string,
|
||||
severity: WebviewHubEvent["severity"] = "info",
|
||||
timestamp = Date.now(),
|
||||
): void {
|
||||
this.events.unshift({
|
||||
id: `${timestamp}-${this.events.length}-${title}`,
|
||||
title,
|
||||
body,
|
||||
severity,
|
||||
timestamp,
|
||||
});
|
||||
if (this.events.length > 30) this.events.length = 30;
|
||||
}
|
||||
|
||||
sendToSelectedPeers(sessionId: string, payload: unknown): void {
|
||||
for (const peer of this.peers) {
|
||||
if (peer.selectedSessionId === sessionId) {
|
||||
this.send(peer, payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hasSelectedPeer(sessionId: string): boolean {
|
||||
for (const peer of this.peers) {
|
||||
if (peer.selectedSessionId === sessionId) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
import type { SaveProviderSettingsActionRequest } from "@cline/core";
|
||||
import type { ToolApprovalResult } from "@cline/shared";
|
||||
import type {
|
||||
WebviewInboundMessage,
|
||||
WebviewReasonLevel,
|
||||
} from "../webview-protocol";
|
||||
|
||||
export type BrowserFrame = WebviewInboundMessage | { type: "restart_hub" };
|
||||
|
||||
export type ProviderSettingsUpdate = Partial<
|
||||
Omit<SaveProviderSettingsActionRequest, "action" | "providerId">
|
||||
>;
|
||||
|
||||
export interface BrowserConfig {
|
||||
inviteRequired: boolean;
|
||||
publicUrl: string;
|
||||
}
|
||||
|
||||
export type TrackedClient = {
|
||||
clientId: string;
|
||||
displayName?: string;
|
||||
clientType: string;
|
||||
connectedAt: number;
|
||||
};
|
||||
|
||||
export type TrackedSession = {
|
||||
sessionId: string;
|
||||
status: string;
|
||||
title: string;
|
||||
workspaceRoot: string;
|
||||
cwd?: string;
|
||||
provider?: string;
|
||||
model?: string;
|
||||
source?: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
createdByClientId?: string;
|
||||
prompt?: string;
|
||||
inputTokens?: number;
|
||||
outputTokens?: number;
|
||||
totalCost?: number;
|
||||
agentCount: number;
|
||||
participantCount: number;
|
||||
};
|
||||
|
||||
export type SessionContext = {
|
||||
workspaceRoot: string;
|
||||
cwd: string;
|
||||
providerId: string;
|
||||
modelId: string;
|
||||
};
|
||||
|
||||
export type BrowserPeer = {
|
||||
socket: Bun.ServerWebSocket<BrowserPeer>;
|
||||
displayName: string;
|
||||
selectedSessionId?: string;
|
||||
unsubscribeEvents?: () => void;
|
||||
sending: boolean;
|
||||
};
|
||||
|
||||
export type PendingToolApproval = {
|
||||
sessionId: string;
|
||||
resolve: (result: ToolApprovalResult) => void;
|
||||
timeout: ReturnType<typeof setTimeout>;
|
||||
};
|
||||
|
||||
export type JsonRecord = Record<string, unknown>;
|
||||
|
||||
export type { WebviewReasonLevel };
|
||||
@@ -1,178 +0,0 @@
|
||||
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
||||
import { extname, join, basename as pathBasename } from "node:path";
|
||||
import {
|
||||
createUserInstructionConfigService,
|
||||
discoverPluginModulePaths,
|
||||
getCoreBuiltinToolCatalog,
|
||||
listHookConfigFiles,
|
||||
listPluginTools,
|
||||
readGlobalSettings,
|
||||
resolvePluginConfigSearchPaths,
|
||||
resolveAgentConfigSearchPaths as resolveSharedAgentConfigSearchPaths,
|
||||
} from "@cline/core";
|
||||
import { readMcpServersResponse } from "./mcp";
|
||||
import type { JsonRecord } from "./types";
|
||||
|
||||
function resolveAgentConfigSearchPaths(workspaceRoot?: string): string[] {
|
||||
return resolveSharedAgentConfigSearchPaths(workspaceRoot);
|
||||
}
|
||||
|
||||
export async function listUserInstructionConfigs(
|
||||
targetWorkspaceRoot: string,
|
||||
): Promise<JsonRecord> {
|
||||
const warnings: string[] = [];
|
||||
|
||||
const loadUserInstructionSnapshot = async (
|
||||
type: "rule" | "skill" | "workflow",
|
||||
): Promise<unknown[]> => {
|
||||
const items: unknown[] = [];
|
||||
const service = createUserInstructionConfigService({
|
||||
skills: { workspacePath: targetWorkspaceRoot },
|
||||
rules: { workspacePath: targetWorkspaceRoot },
|
||||
workflows: { workspacePath: targetWorkspaceRoot },
|
||||
});
|
||||
try {
|
||||
await service.start();
|
||||
for (const record of service.listRecords(type)) {
|
||||
const item = record.item as unknown as JsonRecord;
|
||||
if (item.disabled === true) continue;
|
||||
items.push({
|
||||
id: record.id,
|
||||
name: item.name ?? record.id,
|
||||
instructions: item.instructions,
|
||||
path: record.filePath,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
warnings.push(`${type}: ${message}`);
|
||||
} finally {
|
||||
service.stop();
|
||||
}
|
||||
return items;
|
||||
};
|
||||
|
||||
const loadAgents = (): unknown[] => {
|
||||
const agentsById = new Map<string, { name: string; path: string }>();
|
||||
const directories = resolveAgentConfigSearchPaths(
|
||||
targetWorkspaceRoot,
|
||||
).filter((d) => existsSync(d));
|
||||
for (const directory of directories) {
|
||||
try {
|
||||
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||||
if (!entry.isFile()) continue;
|
||||
const ext = extname(entry.name).toLowerCase();
|
||||
if (ext !== ".yml" && ext !== ".yaml") continue;
|
||||
const filePath = join(directory, entry.name);
|
||||
const raw = readFileSync(filePath, "utf8");
|
||||
const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
||||
const fm = fmMatch?.[1] ?? "";
|
||||
const nameMatch = fm.match(/^\s*name:\s*(.+?)\s*$/m);
|
||||
const parsedName = nameMatch?.[1]?.replace(/^["']|["']$/g, "").trim();
|
||||
const name =
|
||||
parsedName && parsedName.length > 0
|
||||
? parsedName
|
||||
: pathBasename(entry.name, ext);
|
||||
const id = name.toLowerCase();
|
||||
if (!agentsById.has(id)) {
|
||||
agentsById.set(id, { name, path: filePath });
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// best-effort
|
||||
}
|
||||
}
|
||||
return [...agentsById.values()].sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
);
|
||||
};
|
||||
|
||||
const loadHooks = (): unknown[] => {
|
||||
try {
|
||||
return listHookConfigFiles(targetWorkspaceRoot);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
warnings.push(`hooks: ${message}`);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const loadPlugins = (): Array<{
|
||||
name: string;
|
||||
path: string;
|
||||
enabled: boolean;
|
||||
}> => {
|
||||
const disabledPlugins = new Set(readGlobalSettings().disabledPlugins ?? []);
|
||||
const pluginsByPath = new Map<
|
||||
string,
|
||||
{ name: string; path: string; enabled: boolean }
|
||||
>();
|
||||
const directories = resolvePluginConfigSearchPaths(
|
||||
targetWorkspaceRoot,
|
||||
).filter((d) => existsSync(d));
|
||||
for (const directory of directories) {
|
||||
try {
|
||||
for (const filePath of discoverPluginModulePaths(directory)) {
|
||||
if (pluginsByPath.has(filePath)) continue;
|
||||
pluginsByPath.set(filePath, {
|
||||
name: pathBasename(filePath, extname(filePath)),
|
||||
path: filePath,
|
||||
enabled: !disabledPlugins.has(filePath),
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// best-effort
|
||||
}
|
||||
}
|
||||
return [...pluginsByPath.values()].sort((a, b) =>
|
||||
a.name.localeCompare(b.name),
|
||||
);
|
||||
};
|
||||
|
||||
const [rules, workflows, skills, pluginTools] = await Promise.all([
|
||||
loadUserInstructionSnapshot("rule"),
|
||||
loadUserInstructionSnapshot("workflow"),
|
||||
loadUserInstructionSnapshot("skill"),
|
||||
listPluginTools({
|
||||
workspacePath: targetWorkspaceRoot,
|
||||
cwd: targetWorkspaceRoot,
|
||||
}),
|
||||
]);
|
||||
const disabledTools = new Set(readGlobalSettings().disabledTools ?? []);
|
||||
const builtinToolCatalog = getCoreBuiltinToolCatalog({
|
||||
disabledToolIds: disabledTools,
|
||||
});
|
||||
|
||||
return {
|
||||
workspaceRoot: targetWorkspaceRoot,
|
||||
rules,
|
||||
workflows,
|
||||
skills,
|
||||
agents: loadAgents(),
|
||||
plugins: loadPlugins(),
|
||||
tools: [
|
||||
...builtinToolCatalog.map((tool) => ({
|
||||
id: tool.id,
|
||||
name: tool.id,
|
||||
description: tool.description,
|
||||
enabled:
|
||||
tool.defaultEnabled &&
|
||||
!tool.headlessToolNames.some((name) => disabledTools.has(name)),
|
||||
source: "builtin",
|
||||
headlessToolNames: tool.headlessToolNames,
|
||||
})),
|
||||
...pluginTools.map((tool) => ({
|
||||
id: `${tool.pluginName}:${tool.name}:${tool.path}`,
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
enabled: tool.enabled,
|
||||
source: tool.source,
|
||||
path: tool.path,
|
||||
pluginName: tool.pluginName,
|
||||
})),
|
||||
],
|
||||
hooks: loadHooks(),
|
||||
mcp: readMcpServersResponse(),
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import process from "node:process";
|
||||
import type { ProviderSettingsUpdate } from "./types";
|
||||
|
||||
export function readProviderSettingsUpdate(
|
||||
args: Record<string, unknown> | undefined,
|
||||
): ProviderSettingsUpdate {
|
||||
return args?.settings && typeof args.settings === "object"
|
||||
? (args.settings as ProviderSettingsUpdate)
|
||||
: {};
|
||||
}
|
||||
|
||||
export function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
export function asNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value)
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function asRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
return value && typeof value === "object"
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function asTimestamp(value: unknown): number | undefined {
|
||||
const numeric = asNumber(value);
|
||||
if (numeric !== undefined) return numeric;
|
||||
if (typeof value !== "string" || !value.trim()) return undefined;
|
||||
const timestamp = Date.parse(value);
|
||||
return Number.isFinite(timestamp) ? timestamp : undefined;
|
||||
}
|
||||
|
||||
export function basename(value: string | undefined): string {
|
||||
const trimmed = value?.trim();
|
||||
if (!trimmed) return "workspace";
|
||||
const parts = trimmed.split(/[\\/]+/).filter(Boolean);
|
||||
return parts.at(-1) ?? trimmed;
|
||||
}
|
||||
|
||||
export function toPositiveInt(value: unknown): number | undefined {
|
||||
if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
|
||||
const rounded = Math.trunc(value);
|
||||
return rounded > 0 ? rounded : undefined;
|
||||
}
|
||||
|
||||
export function asTrimmedString(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
export function isVisibleClient(clientType: string): boolean {
|
||||
return clientType.trim().length > 0;
|
||||
}
|
||||
|
||||
export function isActiveSession(
|
||||
title: string | undefined,
|
||||
status: string | undefined,
|
||||
participantCount?: number,
|
||||
): boolean {
|
||||
if (!title || !status) return false;
|
||||
const normalized = status?.trim().toLowerCase();
|
||||
if (normalized !== "running" && normalized !== "idle") return false;
|
||||
return typeof participantCount === "number" ? participantCount > 0 : false;
|
||||
}
|
||||
|
||||
export function formatUptime(ms: number): string {
|
||||
const total = Math.max(0, Math.floor(ms / 1000));
|
||||
const d = Math.floor(total / 86_400);
|
||||
const h = Math.floor((total % 86_400) / 3_600);
|
||||
const m = Math.floor((total % 3_600) / 60);
|
||||
const s = total % 60;
|
||||
if (d > 0) return `${d}d ${h}h`;
|
||||
if (h > 0) return `${h}h ${m}m`;
|
||||
if (m > 0) return `${m}m ${s}s`;
|
||||
return `${s}s`;
|
||||
}
|
||||
|
||||
export function formatClientLabel(clientType: string | undefined): string {
|
||||
const normalized = clientType?.trim().toLowerCase() ?? "";
|
||||
if (!normalized || normalized === "unknown") return "Client";
|
||||
if (normalized.includes("cline")) return "Cline";
|
||||
return normalized
|
||||
.split(/[-_\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
export function stringifyContent(value: unknown): string {
|
||||
if (typeof value === "string") return value;
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.map((entry) => {
|
||||
if (typeof entry === "string") return entry;
|
||||
if (entry && typeof entry === "object") {
|
||||
const record = entry as Record<string, unknown>;
|
||||
return (
|
||||
asString(record.text) ??
|
||||
asString(record.content) ??
|
||||
asString(record.result) ??
|
||||
""
|
||||
);
|
||||
}
|
||||
return "";
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
}
|
||||
if (value == null) return "";
|
||||
try {
|
||||
return JSON.stringify(value, null, 2);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
export function chunkText(chunk: unknown): string {
|
||||
if (typeof chunk === "string") return chunk;
|
||||
if (chunk && typeof chunk === "object") {
|
||||
const record = chunk as Record<string, unknown>;
|
||||
if (typeof record.text === "string") return record.text;
|
||||
if (typeof record.content === "string") return record.content;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export function openExternalUrl(url: string): void {
|
||||
const platform = process.platform;
|
||||
const command =
|
||||
platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
|
||||
const args = platform === "win32" ? ["/c", "start", "", url] : [url];
|
||||
const child = spawn(command, args, { stdio: "ignore", detached: true });
|
||||
child.unref();
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { buildInviteUrl, resolveClineHubServerOptions } from "./options";
|
||||
|
||||
function expectEqual<T>(actual: T, expected: T, label: string): void {
|
||||
if (actual !== expected) {
|
||||
throw new Error(
|
||||
`${label}: expected ${String(expected)}, got ${String(actual)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function expectThrows(fn: () => unknown, label: string): void {
|
||||
try {
|
||||
fn();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
throw new Error(`${label}: expected an error`);
|
||||
}
|
||||
|
||||
const defaults = resolveClineHubServerOptions({});
|
||||
expectEqual(defaults.host, "127.0.0.1", "default host");
|
||||
expectEqual(defaults.port, 8787, "default port");
|
||||
expectEqual(defaults.publicUrl, "http://127.0.0.1:8787", "default public URL");
|
||||
expectEqual(defaults.roomSecret, undefined, "default room secret");
|
||||
|
||||
const lan = resolveClineHubServerOptions({
|
||||
HOST: "0.0.0.0",
|
||||
CLINE_HUB_DASHBOARD_PORT: "9000",
|
||||
PUBLIC_URL: "https://example.ngrok-free.app/",
|
||||
ROOM_SECRET: "invite-123",
|
||||
WORKSPACE_ROOT: "/tmp/workspace",
|
||||
});
|
||||
expectEqual(lan.host, "0.0.0.0", "LAN host");
|
||||
expectEqual(lan.port, 9000, "LAN port");
|
||||
expectEqual(lan.publicUrl, "https://example.ngrok-free.app", "LAN public URL");
|
||||
expectEqual(lan.roomSecret, "invite-123", "LAN room secret");
|
||||
expectEqual(lan.workspaceRoot, "/tmp/workspace", "workspace root");
|
||||
expectEqual(
|
||||
buildInviteUrl(lan.publicUrl, lan.roomSecret),
|
||||
"https://example.ngrok-free.app/?roomSecret=invite-123",
|
||||
"invite URL",
|
||||
);
|
||||
|
||||
expectThrows(
|
||||
() => resolveClineHubServerOptions({ HOST: "0.0.0.0" }),
|
||||
"non-local bind without ROOM_SECRET",
|
||||
);
|
||||
expectThrows(
|
||||
() => resolveClineHubServerOptions({ CLINE_HUB_DASHBOARD_PORT: "70000" }),
|
||||
"invalid dashboard port",
|
||||
);
|
||||
expectThrows(
|
||||
() => resolveClineHubServerOptions({ PUBLIC_URL: "ftp://example.test" }),
|
||||
"invalid PUBLIC_URL protocol",
|
||||
);
|
||||
|
||||
console.log("cline-hub option validation passed");
|
||||
@@ -1,335 +0,0 @@
|
||||
import type {
|
||||
ChatMessage as CoreChatMessage,
|
||||
ProviderListItem,
|
||||
ProviderModel,
|
||||
} from "@cline/core";
|
||||
|
||||
export type WebviewUsage = {
|
||||
inputTokens?: number;
|
||||
outputTokens?: number;
|
||||
cacheCreationInputTokens?: number;
|
||||
cacheReadInputTokens?: number;
|
||||
totalCost?: number;
|
||||
};
|
||||
|
||||
export type WebviewProviderModel = Pick<
|
||||
ProviderModel,
|
||||
"id" | "name" | "supportsReasoning"
|
||||
> & {
|
||||
supportsThinking?: boolean;
|
||||
};
|
||||
|
||||
export type WebviewProviderCatalogItem = ProviderListItem;
|
||||
|
||||
export type WebviewReasonLevel = "none" | "low" | "medium" | "high";
|
||||
|
||||
export type WebviewToolEvent = {
|
||||
toolCallId?: string;
|
||||
toolName?: string;
|
||||
status: "running" | "completed" | "failed";
|
||||
input?: unknown;
|
||||
output?: unknown;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type WebviewChatMessageBlock =
|
||||
| { id: string; type: "text"; text: string }
|
||||
| { id: string; type: "reasoning"; text: string; redacted?: boolean }
|
||||
| {
|
||||
id: string;
|
||||
type: "tool";
|
||||
toolEvent: NonNullable<WebviewChatMessage["toolEvents"]>[number];
|
||||
};
|
||||
|
||||
export type WebviewChatMessage = Omit<
|
||||
CoreChatMessage,
|
||||
"content" | "createdAt" | "meta" | "role" | "sessionId"
|
||||
> & {
|
||||
role:
|
||||
| Extract<CoreChatMessage["role"], "user" | "assistant" | "error">
|
||||
| "meta";
|
||||
text: string;
|
||||
reasoning?: string;
|
||||
reasoningRedacted?: boolean;
|
||||
checkpoint?: NonNullable<CoreChatMessage["meta"]>["checkpoint"];
|
||||
toolEvents?: Array<{
|
||||
id: string;
|
||||
toolCallId?: string;
|
||||
name: string;
|
||||
text: string;
|
||||
state: "input-available" | "output-available" | "output-error";
|
||||
input?: unknown;
|
||||
output?: unknown;
|
||||
error?: string;
|
||||
}>;
|
||||
blocks?: WebviewChatMessageBlock[];
|
||||
};
|
||||
|
||||
export type WebviewConfig = {
|
||||
provider?: string;
|
||||
model?: string;
|
||||
mode?: "act" | "plan";
|
||||
systemPrompt?: string;
|
||||
maxIterations?: number;
|
||||
reasonLevel?: WebviewReasonLevel;
|
||||
enableTools?: boolean;
|
||||
enableSpawn?: boolean;
|
||||
enableTeams?: boolean;
|
||||
autoApproveTools?: boolean;
|
||||
};
|
||||
|
||||
export type WebviewChatAttachments = {
|
||||
userImages?: string[];
|
||||
};
|
||||
|
||||
export type WebviewToolApprovalRequest = {
|
||||
approvalId: string;
|
||||
sessionId: string;
|
||||
agentId: string;
|
||||
conversationId: string;
|
||||
iteration: number;
|
||||
toolCallId: string;
|
||||
toolName: string;
|
||||
input: unknown;
|
||||
policy?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type WebviewDefaults = {
|
||||
provider?: string;
|
||||
model?: string;
|
||||
workspaceRoot: string;
|
||||
cwd: string;
|
||||
};
|
||||
|
||||
export type WebviewSessionSummary = {
|
||||
sessionId: string;
|
||||
title?: string;
|
||||
status?: string;
|
||||
source?: string;
|
||||
providerId?: string;
|
||||
model?: string;
|
||||
workspaceRoot?: string;
|
||||
updatedAt?: number;
|
||||
inputTokens?: number;
|
||||
outputTokens?: number;
|
||||
totalCost?: number;
|
||||
};
|
||||
|
||||
export type WebviewConnectedClient = {
|
||||
clientId: string;
|
||||
displayName?: string;
|
||||
clientType: string;
|
||||
connectedAt: number;
|
||||
};
|
||||
|
||||
export type WebviewClientSummary = {
|
||||
label: string;
|
||||
name: string;
|
||||
sessionCount: number;
|
||||
};
|
||||
|
||||
export type WebviewConnectorField = {
|
||||
flag: string;
|
||||
label: string;
|
||||
placeholder?: string;
|
||||
required?: boolean;
|
||||
help?: string[];
|
||||
};
|
||||
|
||||
export type WebviewConnectorSecurityField = {
|
||||
key: string;
|
||||
label: string;
|
||||
placeholder?: string;
|
||||
help?: string[];
|
||||
requiredMessage: string;
|
||||
};
|
||||
|
||||
export type WebviewConnectorChannel = {
|
||||
id: string;
|
||||
name: string;
|
||||
type: "polling" | "webhook";
|
||||
hint: string;
|
||||
fields: WebviewConnectorField[];
|
||||
security?: {
|
||||
prompt: string;
|
||||
fields: WebviewConnectorSecurityField[];
|
||||
};
|
||||
};
|
||||
|
||||
export type WebviewActiveConnector = {
|
||||
id: string;
|
||||
type: string;
|
||||
pid: number;
|
||||
hubUrl: string;
|
||||
startedAt?: string;
|
||||
applicationId?: string;
|
||||
botUsername?: string;
|
||||
userName?: string;
|
||||
phoneNumberId?: string;
|
||||
port?: number;
|
||||
baseUrl?: string;
|
||||
};
|
||||
|
||||
export type WebviewConnectorChannelsResponse = {
|
||||
available: WebviewConnectorChannel[];
|
||||
active: WebviewActiveConnector[];
|
||||
};
|
||||
|
||||
export type WebviewActionSessionSummary = {
|
||||
sessionId: string;
|
||||
title: string;
|
||||
status: string;
|
||||
workspaceRoot: string;
|
||||
workspaceName: string;
|
||||
cwd?: string;
|
||||
model?: string;
|
||||
provider?: string;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
createdByClientId?: string;
|
||||
prompt?: string;
|
||||
inputTokens?: number;
|
||||
outputTokens?: number;
|
||||
totalCost?: number;
|
||||
agentCount: number;
|
||||
};
|
||||
|
||||
export type WebviewHubEvent = {
|
||||
id: string;
|
||||
title: string;
|
||||
body: string;
|
||||
severity: "info" | "success" | "warn" | "error";
|
||||
timestamp: number;
|
||||
};
|
||||
|
||||
export type WebviewHubState = {
|
||||
type: "hub_state";
|
||||
connected: boolean;
|
||||
hubUrl?: string;
|
||||
hubStartedAt?: string;
|
||||
coreVersion?: string;
|
||||
hubUptime?: string;
|
||||
clients: WebviewConnectedClient[];
|
||||
connectors: WebviewActiveConnector[];
|
||||
sessions: WebviewActionSessionSummary[];
|
||||
clientSummaries: WebviewClientSummary[];
|
||||
sessionSummaries: WebviewActionSessionSummary[];
|
||||
events: WebviewHubEvent[];
|
||||
lastWorkspaceRoot?: string;
|
||||
};
|
||||
|
||||
export type WebviewInboundMessage =
|
||||
| { type: "ready" }
|
||||
| { type: "restart_hub" }
|
||||
| {
|
||||
type: "desktopCommand";
|
||||
id: string;
|
||||
command: string;
|
||||
args?: Record<string, unknown>;
|
||||
}
|
||||
| {
|
||||
type: "send";
|
||||
prompt: string;
|
||||
config?: WebviewConfig;
|
||||
attachments?: WebviewChatAttachments;
|
||||
}
|
||||
| { type: "abort" }
|
||||
| { type: "reset" }
|
||||
| {
|
||||
type: "approval_response";
|
||||
approvalId: string;
|
||||
approved: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
| { type: "loadModels"; providerId: string }
|
||||
| { type: "loadProviderCatalog" }
|
||||
| {
|
||||
type: "saveProviderSettings";
|
||||
providerId: string;
|
||||
enabled?: boolean;
|
||||
apiKey?: string;
|
||||
baseUrl?: string;
|
||||
}
|
||||
| { type: "runProviderOAuthLogin"; providerId: string }
|
||||
| { type: "attachSession"; sessionId: string }
|
||||
| { type: "deleteSession"; sessionId: string }
|
||||
| {
|
||||
type: "updateSessionMetadata";
|
||||
sessionId: string;
|
||||
metadata: Record<string, unknown>;
|
||||
}
|
||||
| { type: "restore"; checkpointRunCount: number }
|
||||
| { type: "forkSession" };
|
||||
|
||||
export type WebviewOutboundMessage =
|
||||
| { type: "status"; text: string }
|
||||
| { type: "error"; text: string }
|
||||
| {
|
||||
type: "desktopCommandResult";
|
||||
id: string;
|
||||
ok: true;
|
||||
result: unknown;
|
||||
}
|
||||
| {
|
||||
type: "desktopCommandResult";
|
||||
id: string;
|
||||
ok: false;
|
||||
error: string;
|
||||
}
|
||||
| { type: "session_started"; sessionId: string }
|
||||
| {
|
||||
type: "session_hydrated";
|
||||
sessionId: string;
|
||||
status?: string;
|
||||
providerId?: string;
|
||||
modelId?: string;
|
||||
messages: WebviewChatMessage[];
|
||||
}
|
||||
| { type: "assistant_delta"; text: string }
|
||||
| { type: "reasoning_delta"; text: string; redacted?: boolean }
|
||||
| { type: "tool_event"; text: string; event?: WebviewToolEvent }
|
||||
| ({ type: "approval_request" } & WebviewToolApprovalRequest)
|
||||
| {
|
||||
type: "approval_resolved";
|
||||
approvalId: string;
|
||||
approved: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
| {
|
||||
type: "turn_done";
|
||||
finishReason: string;
|
||||
iterations: number;
|
||||
usage?: WebviewUsage;
|
||||
}
|
||||
| {
|
||||
type: "providers";
|
||||
providers: Array<
|
||||
Pick<ProviderListItem, "defaultModelId" | "enabled" | "id" | "name">
|
||||
>;
|
||||
}
|
||||
| {
|
||||
type: "provider_catalog";
|
||||
providers: WebviewProviderCatalogItem[];
|
||||
settingsPath: string;
|
||||
}
|
||||
| {
|
||||
type: "provider_settings_saved";
|
||||
providerId: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
| {
|
||||
type: "provider_oauth_login_done";
|
||||
providerId: string;
|
||||
accessTokenPresent: boolean;
|
||||
}
|
||||
| { type: "models"; providerId: string; models: WebviewProviderModel[] }
|
||||
| { type: "sessions"; sessions: WebviewSessionSummary[] }
|
||||
| WebviewHubState
|
||||
| { type: "defaults"; defaults: WebviewDefaults }
|
||||
| { type: "reset_done" }
|
||||
| {
|
||||
type: "fork_done";
|
||||
forkedFromSessionId: string;
|
||||
newSessionId: string;
|
||||
}
|
||||
| { type: "fork_error"; text: string };
|
||||
@@ -1,15 +0,0 @@
|
||||
# v0 sandbox internal files
|
||||
__v0_runtime_loader.js
|
||||
__v0_devtools.tsx
|
||||
__v0_jsx-dev-runtime.ts
|
||||
.snowflake/
|
||||
.v0-trash/
|
||||
.vercel/
|
||||
|
||||
# Environment variables
|
||||
.env*.local
|
||||
|
||||
# Common ignores
|
||||
node_modules
|
||||
.next/
|
||||
.DS_Store
|
||||
@@ -1,21 +0,0 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": true,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "app/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import js from "@eslint/js";
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import reactHooks from "eslint-plugin-react-hooks";
|
||||
import reactRefresh from "eslint-plugin-react-refresh";
|
||||
import globals from "globals";
|
||||
import tseslint from "typescript-eslint";
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(["dist"]),
|
||||
{
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
reactHooks.configs.flat.recommended,
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
rules: {
|
||||
"react-refresh/only-export-components": [
|
||||
"warn",
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
},
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
]);
|
||||
@@ -1,13 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>webview</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,64 +0,0 @@
|
||||
{
|
||||
"name": "@cline/cline-hub-webview",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.3.0",
|
||||
"@fontsource-variable/geist": "^5.2.8",
|
||||
"@radix-ui/react-use-controllable-state": "^1.2.2",
|
||||
"@rive-app/react-webgl2": "^4.27.2",
|
||||
"@streamdown/cjk": "^1.0.3",
|
||||
"@streamdown/code": "^1.1.1",
|
||||
"@streamdown/math": "^1.0.2",
|
||||
"@streamdown/mermaid": "^1.0.2",
|
||||
"@tailwindcss/vite": "^4.2.1",
|
||||
"@xyflow/react": "^12.10.1",
|
||||
"ai": "^6.0.116",
|
||||
"ansi-to-react": "^6.2.6",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"lucide-react": "^0.577.0",
|
||||
"media-chrome": "^4.18.1",
|
||||
"motion": "^12.38.0",
|
||||
"nanoid": "^5.1.7",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
"react-jsx-parser": "^2.4.1",
|
||||
"recharts": "2.15.4",
|
||||
"shadcn": "^4.0.8",
|
||||
"shiki": "^4.0.2",
|
||||
"sonner": "^2.0.7",
|
||||
"streamdown": "^2.5.0",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tokenlens": "^1.3.1",
|
||||
"use-stick-to-bottom": "^1.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.4",
|
||||
"@tailwindcss/postcss": "^4.2.0",
|
||||
"@types/node": "^24.12.0",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react-swc": "^4.3.0",
|
||||
"esbuild": "^0.27.0",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.4.0",
|
||||
"postcss": "^8.5",
|
||||
"tailwindcss": "^4.2.1",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"typescript": "^5.9.3",
|
||||
"typescript-eslint": "^8.56.1",
|
||||
"vite": "^8.0.0"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.9 KiB |
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 9.3 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 39 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 77 KiB |
@@ -1,16 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="92px" height="96px" viewBox="0 0 92 96" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<title>Group Copy 2</title>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="icon-copy" transform="translate(-34, -40)" fill="#24292F">
|
||||
<g id="Group-Copy-2" transform="translate(34, 40.5)">
|
||||
<g id="Group-3-Copy-4" transform="translate(0, 0)">
|
||||
<path d="M65.4492701,16.3 C76.3374701,16.3 85.1635558,25.16479 85.1635558,36.1 L85.1635558,42.7 L90.9027661,54.1647464 C91.4694141,55.2966923 91.4668177,56.6300535 90.8957658,57.7597839 L85.1635558,69.1 L85.1635558,75.7 C85.1635558,86.63554 76.3374701,95.5 65.4492701,95.5 L26.0206986,95.5 C15.1328272,95.5 6.30641291,86.63554 6.30641291,75.7 L6.30641291,69.1 L0.448507752,57.7954874 C-0.14693501,56.6464093 -0.149634367,55.2802504 0.441262896,54.1288283 L6.30641291,42.7 L6.30641291,36.1 C6.30641291,25.16479 15.1328272,16.3 26.0206986,16.3 L65.4492701,16.3 Z M62.9301895,22 L29.189529,22 C19.8723267,22 12.3191987,29.5552188 12.3191987,38.875 L12.3191987,44.5 L7.44288578,53.9634655 C6.84794449,55.1180686 6.85066096,56.4896598 7.45017099,57.6418974 L12.3191987,67 L12.3191987,72.625 C12.3191987,81.9450625 19.8723267,89.5 29.189529,89.5 L62.9301895,89.5 C72.2476729,89.5 79.8005198,81.9450625 79.8005198,72.625 L79.8005198,67 L84.5682187,57.6061395 C85.1432011,56.473244 85.1458141,55.1345713 84.5752587,53.9994398 L79.8005198,44.5 L79.8005198,38.875 C79.8005198,29.5552188 72.2476729,22 62.9301895,22 Z" id="Combined-Shape" fill-rule="nonzero"></path>
|
||||
<circle id="Oval" cx="45.7349843" cy="11" r="11"></circle>
|
||||
</g>
|
||||
<rect id="Rectangle-Copy" stroke="#24292F" stroke-width="8" x="31" y="44.5" width="5" height="22" rx="2.5"></rect>
|
||||
<rect id="Rectangle-Copy-2" stroke="#24292F" stroke-width="8" x="55" y="44.5" width="5" height="22" rx="2.5"></rect>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.0 KiB |
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,566 +0,0 @@
|
||||
import {
|
||||
CheckIcon,
|
||||
HatGlassesIcon,
|
||||
PaperclipIcon,
|
||||
PlayIcon,
|
||||
Settings2Icon,
|
||||
SignalHigh,
|
||||
SignalLow,
|
||||
SignalMedium,
|
||||
} from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
Attachment,
|
||||
AttachmentPreview,
|
||||
AttachmentRemove,
|
||||
Attachments,
|
||||
} from "@/components/ai-elements/attachments";
|
||||
import {
|
||||
ModelSelector,
|
||||
ModelSelectorContent,
|
||||
ModelSelectorEmpty,
|
||||
ModelSelectorGroup,
|
||||
ModelSelectorInput,
|
||||
ModelSelectorItem,
|
||||
ModelSelectorList,
|
||||
ModelSelectorLogo,
|
||||
ModelSelectorLogoGroup,
|
||||
ModelSelectorName,
|
||||
ModelSelectorTrigger,
|
||||
} from "@/components/ai-elements/model-selector";
|
||||
import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
||||
import {
|
||||
PromptInput,
|
||||
PromptInputBody,
|
||||
PromptInputButton,
|
||||
PromptInputFooter,
|
||||
PromptInputHeader,
|
||||
PromptInputSubmit,
|
||||
PromptInputTextarea,
|
||||
PromptInputTools,
|
||||
usePromptInputAttachments,
|
||||
usePromptInputController,
|
||||
} from "@/components/ai-elements/prompt-input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import type {
|
||||
WebviewChatAttachments,
|
||||
WebviewOutboundMessage,
|
||||
WebviewProviderModel,
|
||||
WebviewReasonLevel,
|
||||
} from "../../../webview-protocol";
|
||||
|
||||
type ProviderOption = Extract<
|
||||
WebviewOutboundMessage,
|
||||
{ type: "providers" }
|
||||
>["providers"][number];
|
||||
|
||||
function PromptAttachmentsDisplay() {
|
||||
const attachments = usePromptInputAttachments();
|
||||
|
||||
if (attachments.files.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Attachments variant="inline">
|
||||
{attachments.files.map((attachment) => (
|
||||
<Attachment
|
||||
data={attachment}
|
||||
key={attachment.id}
|
||||
onRemove={() => attachments.remove(attachment.id)}
|
||||
>
|
||||
<AttachmentPreview />
|
||||
<AttachmentRemove />
|
||||
</Attachment>
|
||||
))}
|
||||
</Attachments>
|
||||
);
|
||||
}
|
||||
|
||||
function ComposerSettings({
|
||||
autoApproveTools,
|
||||
enableSpawn,
|
||||
enableTeams,
|
||||
model,
|
||||
modelSelectorOpen,
|
||||
models,
|
||||
onAutoApproveToolsChange,
|
||||
onEnableSpawnChange,
|
||||
onEnableTeamsChange,
|
||||
onModelChange,
|
||||
onModelSelectorOpenChange,
|
||||
onProviderChange,
|
||||
provider,
|
||||
providers,
|
||||
workspaceRoot,
|
||||
}: {
|
||||
autoApproveTools: boolean;
|
||||
enableSpawn: boolean;
|
||||
enableTeams: boolean;
|
||||
enableTools: boolean;
|
||||
maxIterations: string;
|
||||
model: string;
|
||||
modelSelectorOpen: boolean;
|
||||
models: WebviewProviderModel[];
|
||||
onAutoApproveToolsChange: (value: boolean) => void;
|
||||
onEnableSpawnChange: (value: boolean) => void;
|
||||
onEnableTeamsChange: (value: boolean) => void;
|
||||
onEnableToolsChange: (value: boolean) => void;
|
||||
onMaxIterationsChange: (value: string) => void;
|
||||
onModelChange: (value: string) => void;
|
||||
onModelSelectorOpenChange: (value: boolean) => void;
|
||||
onProviderChange: (value: string) => void;
|
||||
onSystemPromptChange: (value: string) => void;
|
||||
provider: string;
|
||||
providers: ProviderOption[];
|
||||
systemPrompt: string;
|
||||
workspaceRoot: string;
|
||||
}) {
|
||||
const selectedProvider = providers.find((item) => item.id === provider);
|
||||
const selectedModel =
|
||||
models.find((item) => item.id === model) ?? models[0] ?? undefined;
|
||||
|
||||
return (
|
||||
<div className="grid gap-3 bg-background/70 p-3">
|
||||
<div className="grid gap-2 md:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label className="text-xs uppercase tracking-[0.16em] text-muted-foreground">
|
||||
Provider
|
||||
</Label>
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
if (value) {
|
||||
onProviderChange(value);
|
||||
}
|
||||
}}
|
||||
value={provider}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Select provider" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{providers.map((item) => (
|
||||
<SelectItem key={item.id} value={item.id}>
|
||||
<div className="flex items-center gap-2">
|
||||
{renderProviderLogo(item.id)}
|
||||
<span>{item.name}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label className="text-xs uppercase tracking-[0.16em] text-muted-foreground">
|
||||
Model
|
||||
</Label>
|
||||
<ModelSelector
|
||||
onOpenChange={onModelSelectorOpenChange}
|
||||
open={modelSelectorOpen}
|
||||
>
|
||||
<ModelSelectorTrigger>
|
||||
<Button className="w-full justify-between" variant="outline">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
{selectedProvider && renderProviderLogo(selectedProvider.id)}
|
||||
<span className="truncate">
|
||||
{selectedModel?.name || selectedModel?.id || "Select model"}
|
||||
</span>
|
||||
</div>
|
||||
</Button>
|
||||
</ModelSelectorTrigger>
|
||||
<ModelSelectorContent>
|
||||
<ModelSelectorInput placeholder="Search models..." />
|
||||
<ModelSelectorList>
|
||||
<ModelSelectorEmpty>No models found.</ModelSelectorEmpty>
|
||||
<ModelSelectorGroup
|
||||
heading={selectedProvider?.name || "Models"}
|
||||
>
|
||||
{models.map((item) => (
|
||||
<ModelSelectorItem
|
||||
key={item.id}
|
||||
onSelect={() => {
|
||||
onModelChange(item.id);
|
||||
onModelSelectorOpenChange(false);
|
||||
}}
|
||||
value={item.id}
|
||||
>
|
||||
{selectedProvider &&
|
||||
renderProviderLogo(selectedProvider.id)}
|
||||
<ModelSelectorName>
|
||||
{item.name || item.id}
|
||||
</ModelSelectorName>
|
||||
<ModelSelectorLogoGroup>
|
||||
{selectedProvider &&
|
||||
renderProviderLogo(selectedProvider.id)}
|
||||
</ModelSelectorLogoGroup>
|
||||
{model === item.id ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
))}
|
||||
</ModelSelectorGroup>
|
||||
</ModelSelectorList>
|
||||
</ModelSelectorContent>
|
||||
</ModelSelector>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2 md:grid-cols-2">
|
||||
<div className="grid gap-2">
|
||||
<Label
|
||||
className="text-xs uppercase tracking-[0.16em] text-muted-foreground"
|
||||
htmlFor="workspace-root"
|
||||
>
|
||||
Workspace
|
||||
</Label>
|
||||
<Input id="workspace-root" readOnly value={workspaceRoot} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-2 md:grid-cols-2">
|
||||
<Toggle
|
||||
checked={enableSpawn}
|
||||
label="Subagents"
|
||||
onChange={onEnableSpawnChange}
|
||||
/>
|
||||
<Toggle
|
||||
checked={enableTeams}
|
||||
label="Agent Teams"
|
||||
onChange={onEnableTeamsChange}
|
||||
/>
|
||||
<Toggle
|
||||
checked={autoApproveTools}
|
||||
label="Auto-approves"
|
||||
onChange={onAutoApproveToolsChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function renderProviderLogo(providerId: string) {
|
||||
return (
|
||||
<ModelSelectorLogo className="size-3.5" provider={providerId || "openai"} />
|
||||
);
|
||||
}
|
||||
|
||||
function Toggle({
|
||||
checked,
|
||||
label,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
checked: boolean;
|
||||
label: string;
|
||||
onChange: (value: boolean) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center justify-between rounded-lg border bg-background/60 px-3 py-2">
|
||||
<Label className="text-sm" htmlFor={label}>
|
||||
{label}
|
||||
</Label>
|
||||
<Switch
|
||||
checked={checked}
|
||||
id={label}
|
||||
onCheckedChange={(value) => onChange(value)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ReasonLevel = {
|
||||
None: "none",
|
||||
Low: "low",
|
||||
Medium: "medium",
|
||||
High: "high",
|
||||
} as const;
|
||||
|
||||
const reasonLevels = [
|
||||
{ value: ReasonLevel.None, label: "Thinking Off", icon: SignalHigh },
|
||||
{ value: ReasonLevel.Low, label: "Low", icon: SignalLow },
|
||||
{ value: ReasonLevel.Medium, label: "Medium", icon: SignalMedium },
|
||||
{ value: ReasonLevel.High, label: "High", icon: SignalHigh },
|
||||
];
|
||||
|
||||
export function Composer({
|
||||
autoApproveTools,
|
||||
disabled = false,
|
||||
enableSpawn,
|
||||
enableTeams,
|
||||
enableTools,
|
||||
maxIterations,
|
||||
model,
|
||||
mode,
|
||||
modelSelectorOpen,
|
||||
models,
|
||||
onAbort,
|
||||
onAutoApproveToolsChange,
|
||||
onEnableSpawnChange,
|
||||
onEnableTeamsChange,
|
||||
onEnableToolsChange,
|
||||
onModeChange,
|
||||
onMaxIterationsChange,
|
||||
onModelChange,
|
||||
onModelSelectorOpenChange,
|
||||
onProviderChange,
|
||||
onSend,
|
||||
onSystemPromptChange,
|
||||
onReasonLevelChange,
|
||||
provider,
|
||||
providers,
|
||||
sending,
|
||||
status,
|
||||
systemPrompt,
|
||||
reasonLevel,
|
||||
workspaceRoot,
|
||||
}: {
|
||||
autoApproveTools: boolean;
|
||||
disabled?: boolean;
|
||||
enableSpawn: boolean;
|
||||
enableTeams: boolean;
|
||||
enableTools: boolean;
|
||||
maxIterations: string;
|
||||
model: string;
|
||||
mode: "act" | "plan";
|
||||
modelSelectorOpen: boolean;
|
||||
models: WebviewProviderModel[];
|
||||
onAbort: () => void;
|
||||
onAutoApproveToolsChange: (value: boolean) => void;
|
||||
onEnableSpawnChange: (value: boolean) => void;
|
||||
onEnableTeamsChange: (value: boolean) => void;
|
||||
onEnableToolsChange: (value: boolean) => void;
|
||||
onModeChange: (value: "act" | "plan") => void;
|
||||
onMaxIterationsChange: (value: string) => void;
|
||||
onModelChange: (value: string) => void;
|
||||
onModelSelectorOpenChange: (value: boolean) => void;
|
||||
onProviderChange: (value: string) => void;
|
||||
onSend: (input: {
|
||||
prompt: string;
|
||||
attachments?: WebviewChatAttachments;
|
||||
attachmentCount: number;
|
||||
}) => void;
|
||||
onSystemPromptChange: (value: string) => void;
|
||||
onReasonLevelChange: (value: WebviewReasonLevel) => void;
|
||||
provider: string;
|
||||
providers: ProviderOption[];
|
||||
sending: boolean;
|
||||
status: string;
|
||||
systemPrompt: string;
|
||||
reasonLevel: WebviewReasonLevel;
|
||||
workspaceRoot: string;
|
||||
}) {
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const controller = usePromptInputController();
|
||||
const attachments = usePromptInputAttachments();
|
||||
const selectedModel = models.find((item) => item.id === model);
|
||||
const thinkingSupported = selectedModel?.supportsThinking === true;
|
||||
const activeReasonLevel = thinkingSupported ? reasonLevel : ReasonLevel.None;
|
||||
const reasonLevelOption = Math.max(
|
||||
reasonLevels.findIndex((item) => item.value === activeReasonLevel),
|
||||
0,
|
||||
);
|
||||
const ReasonIcon = reasonLevels[reasonLevelOption].icon;
|
||||
|
||||
return (
|
||||
<div className="border-t bg-background">
|
||||
<PromptInput
|
||||
accept="image/*,.txt,.md,.json,.ts,.tsx,.js,.jsx"
|
||||
globalDrop
|
||||
className="rounded-none [&>[data-slot=input-group]]:border-0! [&>[data-slot=input-group]]:ring-0! [&>[data-slot=input-group]]:has-[[data-slot=input-group-control]:focus-visible]:border-0! [&>[data-slot=input-group]]:has-[[data-slot=input-group-control]:focus-visible]:ring-0!"
|
||||
maxFiles={8}
|
||||
multiple
|
||||
onError={(error) => toast.error(error.message)}
|
||||
onSubmit={async (message: PromptInputMessage) => {
|
||||
const prompt = message.text.trim();
|
||||
if (!prompt && !message.files.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
let attachments: WebviewChatAttachments | undefined;
|
||||
if (message.files.length > 0) {
|
||||
const userImages = (
|
||||
await Promise.all(
|
||||
message.files.map((file) => toImageDataUrl(file.url)),
|
||||
)
|
||||
).filter((value): value is string => Boolean(value));
|
||||
if (userImages.length > 0) {
|
||||
attachments = { userImages };
|
||||
}
|
||||
if (userImages.length !== message.files.length) {
|
||||
toast.warning(
|
||||
"Only image attachments are currently sent in the VS Code chat runtime.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!prompt && !attachments?.userImages?.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
onSend({
|
||||
prompt,
|
||||
attachments,
|
||||
attachmentCount: message.files.length,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<PromptInputHeader>
|
||||
<PromptAttachmentsDisplay />
|
||||
</PromptInputHeader>
|
||||
<PromptInputBody>
|
||||
<PromptInputTextarea
|
||||
disabled={disabled || status.includes("Failed")}
|
||||
onChange={(event) =>
|
||||
controller.textInput.setInput(event.target.value)
|
||||
}
|
||||
placeholder="Type @ for context and / for skills"
|
||||
value={controller.textInput.value}
|
||||
className="text-sm outline-none ring-0"
|
||||
/>
|
||||
</PromptInputBody>
|
||||
<PromptInputFooter className="flex-col items-stretch gap-1 px-0">
|
||||
{settingsOpen ? (
|
||||
<ComposerSettings
|
||||
autoApproveTools={autoApproveTools}
|
||||
enableSpawn={enableSpawn}
|
||||
enableTeams={enableTeams}
|
||||
enableTools={enableTools}
|
||||
maxIterations={maxIterations}
|
||||
model={model}
|
||||
modelSelectorOpen={modelSelectorOpen}
|
||||
models={models}
|
||||
onAutoApproveToolsChange={onAutoApproveToolsChange}
|
||||
onEnableSpawnChange={onEnableSpawnChange}
|
||||
onEnableTeamsChange={onEnableTeamsChange}
|
||||
onEnableToolsChange={onEnableToolsChange}
|
||||
onMaxIterationsChange={onMaxIterationsChange}
|
||||
onModelChange={onModelChange}
|
||||
onModelSelectorOpenChange={onModelSelectorOpenChange}
|
||||
onProviderChange={onProviderChange}
|
||||
onSystemPromptChange={onSystemPromptChange}
|
||||
provider={provider}
|
||||
providers={providers}
|
||||
systemPrompt={systemPrompt}
|
||||
workspaceRoot={workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<PromptInputTools className="shrink-0">
|
||||
<PromptInputButton
|
||||
disabled={disabled}
|
||||
onClick={() => attachments.openFileDialog()}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
>
|
||||
<PaperclipIcon className="size-3" />
|
||||
</PromptInputButton>
|
||||
<PromptInputButton
|
||||
disabled={disabled}
|
||||
onClick={() => setSettingsOpen((open) => !open)}
|
||||
type="button"
|
||||
variant={settingsOpen ? "default" : "ghost"}
|
||||
>
|
||||
<Settings2Icon className="size-3" />
|
||||
<span>
|
||||
{provider}:{model}
|
||||
</span>
|
||||
</PromptInputButton>
|
||||
<PromptInputButton
|
||||
disabled={disabled || !thinkingSupported}
|
||||
onClick={() => {
|
||||
const nextOption =
|
||||
(reasonLevelOption + 1) % reasonLevels.length;
|
||||
onReasonLevelChange(reasonLevels[nextOption].value);
|
||||
}}
|
||||
type="button"
|
||||
title={reasonLevels[reasonLevelOption].label}
|
||||
variant={
|
||||
activeReasonLevel !== ReasonLevel.None ? "default" : "ghost"
|
||||
}
|
||||
>
|
||||
<ReasonIcon className="size-3" />
|
||||
</PromptInputButton>
|
||||
<PromptInputButton
|
||||
disabled={disabled}
|
||||
onClick={() => onModeChange(mode === "act" ? "plan" : "act")}
|
||||
type="button"
|
||||
variant={mode === "plan" ? "default" : "ghost"}
|
||||
className="hidden"
|
||||
>
|
||||
{mode === "act" ? (
|
||||
<PlayIcon className="size-3" />
|
||||
) : (
|
||||
<HatGlassesIcon className="size-3" />
|
||||
)}
|
||||
{mode}
|
||||
</PromptInputButton>
|
||||
<Badge
|
||||
className="rounded-sm px-3 py-1 text-xs hidden"
|
||||
variant={status.includes("Error") ? "destructive" : "secondary"}
|
||||
>
|
||||
{status}
|
||||
</Badge>
|
||||
</PromptInputTools>
|
||||
<div className="flex items-center gap-2">
|
||||
{sending ? (
|
||||
<Button onClick={onAbort} type="button" variant="destructive">
|
||||
Abort
|
||||
</Button>
|
||||
) : null}
|
||||
<PromptInputSubmit
|
||||
disabled={disabled || status.includes("Failed")}
|
||||
status={sending ? "submitted" : "ready"}
|
||||
variant="ghost"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</PromptInputFooter>
|
||||
</PromptInput>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function toImageDataUrl(
|
||||
url: string | undefined,
|
||||
): Promise<string | undefined> {
|
||||
if (!url) {
|
||||
return undefined;
|
||||
}
|
||||
if (url.startsWith("data:image/")) {
|
||||
return url;
|
||||
}
|
||||
if (!url.startsWith("blob:")) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
const blob = await response.blob();
|
||||
if (!blob.type.startsWith("image/")) {
|
||||
return undefined;
|
||||
}
|
||||
return await new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
resolve(typeof reader.result === "string" ? reader.result : undefined);
|
||||
};
|
||||
reader.onerror = () => resolve(undefined);
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { UsersIcon } from "lucide-react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import {
|
||||
Task,
|
||||
TaskContent,
|
||||
TaskItem,
|
||||
TaskTrigger,
|
||||
} from "@/components/ai-elements/task";
|
||||
|
||||
export type TeamToolEvent = {
|
||||
id: string;
|
||||
name: string;
|
||||
state: "input-available" | "output-available" | "output-error";
|
||||
input?: unknown;
|
||||
output?: unknown;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
return typeof value === "object" && value !== null
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function asStringArray(value: unknown): string[] | undefined {
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === "string")
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function prefixForState(state: TeamToolEvent["state"]): string {
|
||||
if (state === "output-error") {
|
||||
return "Failed";
|
||||
}
|
||||
if (state === "output-available") {
|
||||
return "Done";
|
||||
}
|
||||
return "Running";
|
||||
}
|
||||
|
||||
function summarizeTeamTool(event: TeamToolEvent): ReactNode {
|
||||
const input = asRecord(event.input);
|
||||
const output = asRecord(event.output);
|
||||
const statePrefix = prefixForState(event.state);
|
||||
|
||||
switch (event.name) {
|
||||
case "team_spawn_teammate":
|
||||
return `${statePrefix} spawn teammate ${asString(input?.agentId) ?? asString(output?.agentId) ?? "agent"}`;
|
||||
case "team_shutdown_teammate":
|
||||
return `${statePrefix} shutdown teammate ${asString(input?.agentId) ?? asString(output?.agentId) ?? "agent"}`;
|
||||
case "team_status":
|
||||
return `${statePrefix} fetch team status`;
|
||||
case "team_task": {
|
||||
const action = asString(input?.action);
|
||||
if (action === "create") {
|
||||
return `${statePrefix} create task ${asString(output?.taskId) ?? ""}${asString(input?.title) ? `: ${asString(input?.title)}` : ""}`.trim();
|
||||
}
|
||||
if (action === "list") {
|
||||
return `${statePrefix} list team tasks`;
|
||||
}
|
||||
if (action === "claim") {
|
||||
return `${statePrefix} claim task ${asString(input?.taskId) ?? asString(output?.taskId) ?? ""}`.trim();
|
||||
}
|
||||
if (action === "complete") {
|
||||
return `${statePrefix} complete task ${asString(input?.taskId) ?? asString(output?.taskId) ?? ""}`.trim();
|
||||
}
|
||||
if (action === "block") {
|
||||
return `${statePrefix} block task ${asString(input?.taskId) ?? asString(output?.taskId) ?? ""}`.trim();
|
||||
}
|
||||
return `${statePrefix} update team task`;
|
||||
}
|
||||
case "team_run_task": {
|
||||
const agentId =
|
||||
asString(input?.agentId) ?? asString(output?.agentId) ?? "agent";
|
||||
const mode = asString(output?.mode) ?? asString(input?.runMode);
|
||||
const status = asString(output?.status);
|
||||
const task = asString(input?.task);
|
||||
const suffix = task ? `: ${task}` : "";
|
||||
const action =
|
||||
mode === "async" ? "queue" : status === "joined" ? "join" : "run";
|
||||
const state = status ? ` (${status})` : "";
|
||||
return `${statePrefix} ${action} task with ${agentId}${state}${suffix}`;
|
||||
}
|
||||
case "team_cancel_run":
|
||||
return `${statePrefix} cancel run ${asString(input?.runId) ?? asString(output?.runId) ?? ""}`.trim();
|
||||
case "team_list_runs":
|
||||
return `${statePrefix} list teammate runs`;
|
||||
case "team_await_run":
|
||||
return `${statePrefix} await run ${asString(input?.runId) ?? ""}`.trim();
|
||||
case "team_await_all_runs":
|
||||
return `${statePrefix} await all active runs`;
|
||||
case "team_send_message":
|
||||
return `${statePrefix} message ${asString(input?.toAgentId) ?? asString(output?.toAgentId) ?? "agent"}${asString(input?.subject) ? `: ${asString(input?.subject)}` : ""}`;
|
||||
case "team_broadcast":
|
||||
return `${statePrefix} broadcast${asString(input?.subject) ? `: ${asString(input?.subject)}` : ""}`;
|
||||
case "team_read_mailbox":
|
||||
return `${statePrefix} read mailbox`;
|
||||
case "team_mission_log":
|
||||
return `${statePrefix} log ${asString(input?.kind) ?? "update"}${asString(input?.summary) ? `: ${asString(input?.summary)}` : ""}`;
|
||||
case "team_cleanup":
|
||||
return `${statePrefix} clean up team runtime`;
|
||||
case "team_create_outcome":
|
||||
return `${statePrefix} create outcome${asString(input?.title) ? `: ${asString(input?.title)}` : ""}`;
|
||||
case "team_attach_outcome_fragment":
|
||||
return `${statePrefix} attach fragment to ${asString(input?.section) ?? "section"}`;
|
||||
case "team_review_outcome_fragment":
|
||||
return `${statePrefix} ${input?.approved === false ? "reject" : "review"} fragment ${asString(input?.fragmentId) ?? ""}`.trim();
|
||||
case "team_finalize_outcome":
|
||||
return `${statePrefix} finalize outcome ${asString(input?.outcomeId) ?? asString(output?.outcomeId) ?? ""}`.trim();
|
||||
case "team_list_outcomes":
|
||||
return `${statePrefix} list outcomes`;
|
||||
default:
|
||||
return `${statePrefix} ${event.name.replace(/^team_/, "").replaceAll("_", " ")}`;
|
||||
}
|
||||
}
|
||||
|
||||
function describeTeamTool(event: TeamToolEvent): string | undefined {
|
||||
if (event.error) {
|
||||
return event.error;
|
||||
}
|
||||
|
||||
const input = asRecord(event.input);
|
||||
const output = asRecord(event.output);
|
||||
|
||||
switch (event.name) {
|
||||
case "team_task": {
|
||||
const action = asString(input?.action);
|
||||
if (action === "create") {
|
||||
return asString(input?.description);
|
||||
}
|
||||
if (action === "block") {
|
||||
return asString(input?.reason);
|
||||
}
|
||||
if (action === "list") {
|
||||
const tasks = Array.isArray(output?.tasks)
|
||||
? output.tasks.length
|
||||
: undefined;
|
||||
return typeof tasks === "number"
|
||||
? `${tasks} task${tasks === 1 ? "" : "s"}`
|
||||
: undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
case "team_run_task":
|
||||
return (
|
||||
asString(output?.message) ??
|
||||
asString(output?.runId) ??
|
||||
asString(output?.text)
|
||||
);
|
||||
case "team_send_message":
|
||||
case "team_broadcast":
|
||||
return asString(input?.body);
|
||||
case "team_mission_log":
|
||||
return asString(input?.nextAction) ?? asString(input?.summary);
|
||||
case "team_attach_outcome_fragment":
|
||||
return asString(input?.content);
|
||||
case "team_status": {
|
||||
const members = Array.isArray(output?.members)
|
||||
? output.members.length
|
||||
: undefined;
|
||||
const tasks = Array.isArray(output?.tasks)
|
||||
? output.tasks.length
|
||||
: undefined;
|
||||
const runs = Array.isArray(output?.runs) ? output.runs.length : undefined;
|
||||
const parts = [
|
||||
typeof members === "number" ? `${members} members` : undefined,
|
||||
typeof tasks === "number" ? `${tasks} tasks` : undefined,
|
||||
typeof runs === "number" ? `${runs} runs` : undefined,
|
||||
].filter(Boolean);
|
||||
return parts.join(" • ") || undefined;
|
||||
}
|
||||
case "team_list_runs": {
|
||||
const runs = Array.isArray(event.output) ? event.output : undefined;
|
||||
if (!runs?.length) {
|
||||
return "No runs";
|
||||
}
|
||||
return `${runs.length} run${runs.length === 1 ? "" : "s"}`;
|
||||
}
|
||||
case "team_read_mailbox": {
|
||||
const messages = Array.isArray(event.output) ? event.output : undefined;
|
||||
if (!messages?.length) {
|
||||
return "No messages";
|
||||
}
|
||||
return `${messages.length} message${messages.length === 1 ? "" : "s"}`;
|
||||
}
|
||||
case "team_create_outcome": {
|
||||
const sections = asStringArray(input?.requiredSections);
|
||||
return sections?.length ? sections.join(", ") : undefined;
|
||||
}
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export default function TeamTasks({
|
||||
className,
|
||||
defaultOpen = true,
|
||||
events,
|
||||
...props
|
||||
}: Omit<ComponentProps<typeof Task>, "children"> & {
|
||||
events: TeamToolEvent[];
|
||||
}) {
|
||||
if (events.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const title =
|
||||
events.length === 1 ? "Team activity" : `Team activity (${events.length})`;
|
||||
|
||||
return (
|
||||
<Task className={className} defaultOpen={defaultOpen} {...props}>
|
||||
<TaskTrigger title={title}>
|
||||
<div className="flex w-full cursor-pointer items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground">
|
||||
<UsersIcon className="size-4" />
|
||||
<p className="text-sm">{title}</p>
|
||||
</div>
|
||||
</TaskTrigger>
|
||||
<TaskContent>
|
||||
{events.map((event) => {
|
||||
const description = describeTeamTool(event);
|
||||
return (
|
||||
<TaskItem className="space-y-1" key={event.id}>
|
||||
<div>{summarizeTeamTool(event)}</div>
|
||||
{description ? (
|
||||
<div className="line-clamp-3 text-xs text-muted-foreground/90">
|
||||
{description}
|
||||
</div>
|
||||
) : null}
|
||||
</TaskItem>
|
||||
);
|
||||
})}
|
||||
</TaskContent>
|
||||
</Task>
|
||||
);
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { Tool } from "ai";
|
||||
import { BotIcon } from "lucide-react";
|
||||
import type { ComponentProps } from "react";
|
||||
import { memo } from "react";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { CodeBlock } from "./code-block";
|
||||
|
||||
export type AgentProps = ComponentProps<"div">;
|
||||
|
||||
export const Agent = memo(({ className, ...props }: AgentProps) => (
|
||||
<div
|
||||
className={cn("not-prose w-full rounded-md border", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
|
||||
export type AgentHeaderProps = ComponentProps<"div"> & {
|
||||
name: string;
|
||||
model?: string;
|
||||
};
|
||||
|
||||
export const AgentHeader = memo(
|
||||
({ className, name, model, ...props }: AgentHeaderProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex w-full items-center justify-between gap-4 p-3",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<BotIcon className="size-4 text-muted-foreground" />
|
||||
<span className="font-medium text-sm">{name}</span>
|
||||
{model && (
|
||||
<Badge className="font-mono text-xs" variant="secondary">
|
||||
{model}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
);
|
||||
|
||||
export type AgentContentProps = ComponentProps<"div">;
|
||||
|
||||
export const AgentContent = memo(
|
||||
({ className, ...props }: AgentContentProps) => (
|
||||
<div className={cn("space-y-4 p-4 pt-0", className)} {...props} />
|
||||
),
|
||||
);
|
||||
|
||||
export type AgentInstructionsProps = ComponentProps<"div"> & {
|
||||
children: string;
|
||||
};
|
||||
|
||||
export const AgentInstructions = memo(
|
||||
({ className, children, ...props }: AgentInstructionsProps) => (
|
||||
<div className={cn("space-y-2", className)} {...props}>
|
||||
<span className="font-medium text-muted-foreground text-sm">
|
||||
Instructions
|
||||
</span>
|
||||
<div className="rounded-md bg-muted/50 p-3 text-muted-foreground text-sm">
|
||||
<p>{children}</p>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
);
|
||||
|
||||
export type AgentToolsProps = ComponentProps<typeof Accordion>;
|
||||
|
||||
export const AgentTools = memo(({ className, ...props }: AgentToolsProps) => (
|
||||
<div className={cn("space-y-2", className)}>
|
||||
<span className="font-medium text-muted-foreground text-sm">Tools</span>
|
||||
<Accordion className="rounded-md border" {...props} />
|
||||
</div>
|
||||
));
|
||||
|
||||
export type AgentToolProps = ComponentProps<typeof AccordionItem> & {
|
||||
tool: Tool;
|
||||
};
|
||||
|
||||
export const AgentTool = memo(
|
||||
({ className, tool, value, ...props }: AgentToolProps) => {
|
||||
const schema =
|
||||
"jsonSchema" in tool && tool.jsonSchema
|
||||
? tool.jsonSchema
|
||||
: tool.inputSchema;
|
||||
|
||||
return (
|
||||
<AccordionItem
|
||||
className={cn("border-b last:border-b-0", className)}
|
||||
value={value}
|
||||
{...props}
|
||||
>
|
||||
<AccordionTrigger className="px-3 py-2 text-sm hover:no-underline">
|
||||
{tool.description ?? "No description"}
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-3 pb-3">
|
||||
<div className="rounded-md bg-muted/50">
|
||||
<CodeBlock code={JSON.stringify(schema, null, 2)} language="json" />
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
export type AgentOutputProps = ComponentProps<"div"> & {
|
||||
schema: string;
|
||||
};
|
||||
|
||||
export const AgentOutput = memo(
|
||||
({ className, schema, ...props }: AgentOutputProps) => (
|
||||
<div className={cn("space-y-2", className)} {...props}>
|
||||
<span className="font-medium text-muted-foreground text-sm">
|
||||
Output Schema
|
||||
</span>
|
||||
<div className="rounded-md bg-muted/50">
|
||||
<CodeBlock code={schema} language="typescript" />
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
);
|
||||
|
||||
Agent.displayName = "Agent";
|
||||
AgentHeader.displayName = "AgentHeader";
|
||||
AgentContent.displayName = "AgentContent";
|
||||
AgentInstructions.displayName = "AgentInstructions";
|
||||
AgentTools.displayName = "AgentTools";
|
||||
AgentTool.displayName = "AgentTool";
|
||||
AgentOutput.displayName = "AgentOutput";
|
||||
@@ -1,148 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { XIcon } from "lucide-react";
|
||||
import type { ComponentProps, HTMLAttributes } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ArtifactProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const Artifact = ({ className, ...props }: ArtifactProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col overflow-hidden rounded-lg border bg-background shadow-sm",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ArtifactHeaderProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const ArtifactHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: ArtifactHeaderProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between border-b bg-muted/50 px-4 py-3",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ArtifactCloseProps = ComponentProps<typeof Button>;
|
||||
|
||||
export const ArtifactClose = ({
|
||||
className,
|
||||
children,
|
||||
size = "sm",
|
||||
variant = "ghost",
|
||||
...props
|
||||
}: ArtifactCloseProps) => (
|
||||
<Button
|
||||
className={cn(
|
||||
"size-8 p-0 text-muted-foreground hover:text-foreground",
|
||||
className,
|
||||
)}
|
||||
size={size}
|
||||
type="button"
|
||||
variant={variant}
|
||||
{...props}
|
||||
>
|
||||
{children ?? <XIcon className="size-4" />}
|
||||
<span className="sr-only">Close</span>
|
||||
</Button>
|
||||
);
|
||||
|
||||
export type ArtifactTitleProps = HTMLAttributes<HTMLParagraphElement>;
|
||||
|
||||
export const ArtifactTitle = ({ className, ...props }: ArtifactTitleProps) => (
|
||||
<p
|
||||
className={cn("font-medium text-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ArtifactDescriptionProps = HTMLAttributes<HTMLParagraphElement>;
|
||||
|
||||
export const ArtifactDescription = ({
|
||||
className,
|
||||
...props
|
||||
}: ArtifactDescriptionProps) => (
|
||||
<p className={cn("text-muted-foreground text-sm", className)} {...props} />
|
||||
);
|
||||
|
||||
export type ArtifactActionsProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const ArtifactActions = ({
|
||||
className,
|
||||
...props
|
||||
}: ArtifactActionsProps) => (
|
||||
<div className={cn("flex items-center gap-1", className)} {...props} />
|
||||
);
|
||||
|
||||
export type ArtifactActionProps = ComponentProps<typeof Button> & {
|
||||
tooltip?: string;
|
||||
label?: string;
|
||||
icon?: LucideIcon;
|
||||
};
|
||||
|
||||
export const ArtifactAction = ({
|
||||
tooltip,
|
||||
label,
|
||||
icon: Icon,
|
||||
children,
|
||||
className,
|
||||
size = "sm",
|
||||
variant = "ghost",
|
||||
...props
|
||||
}: ArtifactActionProps) => {
|
||||
const button = (
|
||||
<Button
|
||||
className={cn(
|
||||
"size-8 p-0 text-muted-foreground hover:text-foreground",
|
||||
className,
|
||||
)}
|
||||
size={size}
|
||||
type="button"
|
||||
variant={variant}
|
||||
{...props}
|
||||
>
|
||||
{Icon ? <Icon className="size-4" /> : children}
|
||||
<span className="sr-only">{label || tooltip}</span>
|
||||
</Button>
|
||||
);
|
||||
|
||||
if (tooltip) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger>{button}</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{tooltip}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
return button;
|
||||
};
|
||||
|
||||
export type ArtifactContentProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const ArtifactContent = ({
|
||||
className,
|
||||
...props
|
||||
}: ArtifactContentProps) => (
|
||||
<div className={cn("flex-1 overflow-auto p-4", className)} {...props} />
|
||||
);
|
||||
@@ -1,425 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { FileUIPart, SourceDocumentUIPart } from "ai";
|
||||
import {
|
||||
FileTextIcon,
|
||||
GlobeIcon,
|
||||
ImageIcon,
|
||||
Music2Icon,
|
||||
PaperclipIcon,
|
||||
VideoIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import type { ComponentProps, HTMLAttributes, ReactNode } from "react";
|
||||
import { createContext, useCallback, useContext, useMemo } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
HoverCard,
|
||||
HoverCardContent,
|
||||
HoverCardTrigger,
|
||||
} from "@/components/ui/hover-card";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
export type AttachmentData =
|
||||
| (FileUIPart & { id: string })
|
||||
| (SourceDocumentUIPart & { id: string });
|
||||
|
||||
export type AttachmentMediaCategory =
|
||||
| "image"
|
||||
| "video"
|
||||
| "audio"
|
||||
| "document"
|
||||
| "source"
|
||||
| "unknown";
|
||||
|
||||
export type AttachmentVariant = "grid" | "inline" | "list";
|
||||
|
||||
const mediaCategoryIcons: Record<AttachmentMediaCategory, typeof ImageIcon> = {
|
||||
audio: Music2Icon,
|
||||
document: FileTextIcon,
|
||||
image: ImageIcon,
|
||||
source: GlobeIcon,
|
||||
unknown: PaperclipIcon,
|
||||
video: VideoIcon,
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Utility Functions
|
||||
// ============================================================================
|
||||
|
||||
export const getMediaCategory = (
|
||||
data: AttachmentData,
|
||||
): AttachmentMediaCategory => {
|
||||
if (data.type === "source-document") {
|
||||
return "source";
|
||||
}
|
||||
|
||||
const mediaType = data.mediaType ?? "";
|
||||
|
||||
if (mediaType.startsWith("image/")) {
|
||||
return "image";
|
||||
}
|
||||
if (mediaType.startsWith("video/")) {
|
||||
return "video";
|
||||
}
|
||||
if (mediaType.startsWith("audio/")) {
|
||||
return "audio";
|
||||
}
|
||||
if (mediaType.startsWith("application/") || mediaType.startsWith("text/")) {
|
||||
return "document";
|
||||
}
|
||||
|
||||
return "unknown";
|
||||
};
|
||||
|
||||
export const getAttachmentLabel = (data: AttachmentData): string => {
|
||||
if (data.type === "source-document") {
|
||||
return data.title || data.filename || "Source";
|
||||
}
|
||||
|
||||
const category = getMediaCategory(data);
|
||||
return data.filename || (category === "image" ? "Image" : "Attachment");
|
||||
};
|
||||
|
||||
const renderAttachmentImage = (
|
||||
url: string,
|
||||
filename: string | undefined,
|
||||
isGrid: boolean,
|
||||
) =>
|
||||
isGrid ? (
|
||||
<img
|
||||
alt={filename || "Image"}
|
||||
className="size-full object-cover"
|
||||
height={96}
|
||||
src={url}
|
||||
width={96}
|
||||
/>
|
||||
) : (
|
||||
<img
|
||||
alt={filename || "Image"}
|
||||
className="size-full rounded object-cover"
|
||||
height={20}
|
||||
src={url}
|
||||
width={20}
|
||||
/>
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// Contexts
|
||||
// ============================================================================
|
||||
|
||||
interface AttachmentsContextValue {
|
||||
variant: AttachmentVariant;
|
||||
}
|
||||
|
||||
const AttachmentsContext = createContext<AttachmentsContextValue | null>(null);
|
||||
|
||||
interface AttachmentContextValue {
|
||||
data: AttachmentData;
|
||||
mediaCategory: AttachmentMediaCategory;
|
||||
onRemove?: () => void;
|
||||
variant: AttachmentVariant;
|
||||
}
|
||||
|
||||
const AttachmentContext = createContext<AttachmentContextValue | null>(null);
|
||||
|
||||
// ============================================================================
|
||||
// Hooks
|
||||
// ============================================================================
|
||||
|
||||
export const useAttachmentsContext = () =>
|
||||
useContext(AttachmentsContext) ?? { variant: "grid" as const };
|
||||
|
||||
export const useAttachmentContext = () => {
|
||||
const ctx = useContext(AttachmentContext);
|
||||
if (!ctx) {
|
||||
throw new Error("Attachment components must be used within <Attachment>");
|
||||
}
|
||||
return ctx;
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Attachments - Container
|
||||
// ============================================================================
|
||||
|
||||
export type AttachmentsProps = HTMLAttributes<HTMLDivElement> & {
|
||||
variant?: AttachmentVariant;
|
||||
};
|
||||
|
||||
export const Attachments = ({
|
||||
variant = "grid",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: AttachmentsProps) => {
|
||||
const contextValue = useMemo(() => ({ variant }), [variant]);
|
||||
|
||||
return (
|
||||
<AttachmentsContext.Provider value={contextValue}>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-start",
|
||||
variant === "list" ? "flex-col gap-2" : "flex-wrap gap-2",
|
||||
variant === "grid" && "ml-auto w-fit",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</AttachmentsContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Attachment - Item
|
||||
// ============================================================================
|
||||
|
||||
export type AttachmentProps = HTMLAttributes<HTMLDivElement> & {
|
||||
data: AttachmentData;
|
||||
onRemove?: () => void;
|
||||
};
|
||||
|
||||
export const Attachment = ({
|
||||
data,
|
||||
onRemove,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: AttachmentProps) => {
|
||||
const { variant } = useAttachmentsContext();
|
||||
const mediaCategory = getMediaCategory(data);
|
||||
|
||||
const contextValue = useMemo<AttachmentContextValue>(
|
||||
() => ({ data, mediaCategory, onRemove, variant }),
|
||||
[data, mediaCategory, onRemove, variant],
|
||||
);
|
||||
|
||||
return (
|
||||
<AttachmentContext.Provider value={contextValue}>
|
||||
<div
|
||||
className={cn(
|
||||
"group relative",
|
||||
variant === "grid" && "size-24 overflow-hidden rounded-lg",
|
||||
variant === "inline" && [
|
||||
"flex h-8 cursor-pointer select-none items-center gap-1.5",
|
||||
"rounded-md border border-border px-1.5",
|
||||
"font-medium text-sm transition-all",
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
],
|
||||
variant === "list" && [
|
||||
"flex w-full items-center gap-3 rounded-lg border p-3",
|
||||
"hover:bg-accent/50",
|
||||
],
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</AttachmentContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// AttachmentPreview - Media preview
|
||||
// ============================================================================
|
||||
|
||||
export type AttachmentPreviewProps = HTMLAttributes<HTMLDivElement> & {
|
||||
fallbackIcon?: ReactNode;
|
||||
};
|
||||
|
||||
export const AttachmentPreview = ({
|
||||
fallbackIcon,
|
||||
className,
|
||||
...props
|
||||
}: AttachmentPreviewProps) => {
|
||||
const { data, mediaCategory, variant } = useAttachmentContext();
|
||||
|
||||
const iconSize = variant === "inline" ? "size-3" : "size-4";
|
||||
|
||||
const renderIcon = (Icon: typeof ImageIcon) => (
|
||||
<Icon className={cn(iconSize, "text-muted-foreground")} />
|
||||
);
|
||||
|
||||
const renderContent = () => {
|
||||
if (mediaCategory === "image" && data.type === "file" && data.url) {
|
||||
return renderAttachmentImage(data.url, data.filename, variant === "grid");
|
||||
}
|
||||
|
||||
if (mediaCategory === "video" && data.type === "file" && data.url) {
|
||||
return <video className="size-full object-cover" muted src={data.url} />;
|
||||
}
|
||||
|
||||
const Icon = mediaCategoryIcons[mediaCategory];
|
||||
return fallbackIcon ?? renderIcon(Icon);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex shrink-0 items-center justify-center overflow-hidden",
|
||||
variant === "grid" && "size-full bg-muted",
|
||||
variant === "inline" && "size-5 rounded bg-background",
|
||||
variant === "list" && "size-12 rounded bg-muted",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{renderContent()}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// AttachmentInfo - Name and type display
|
||||
// ============================================================================
|
||||
|
||||
export type AttachmentInfoProps = HTMLAttributes<HTMLDivElement> & {
|
||||
showMediaType?: boolean;
|
||||
};
|
||||
|
||||
export const AttachmentInfo = ({
|
||||
showMediaType = false,
|
||||
className,
|
||||
...props
|
||||
}: AttachmentInfoProps) => {
|
||||
const { data, variant } = useAttachmentContext();
|
||||
const label = getAttachmentLabel(data);
|
||||
|
||||
if (variant === "grid") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("min-w-0 flex-1", className)} {...props}>
|
||||
<span className="block truncate">{label}</span>
|
||||
{showMediaType && data.mediaType && (
|
||||
<span className="block truncate text-muted-foreground text-xs">
|
||||
{data.mediaType}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// AttachmentRemove - Remove button
|
||||
// ============================================================================
|
||||
|
||||
export type AttachmentRemoveProps = ComponentProps<typeof Button> & {
|
||||
label?: string;
|
||||
};
|
||||
|
||||
export const AttachmentRemove = ({
|
||||
label = "Remove",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: AttachmentRemoveProps) => {
|
||||
const { onRemove, variant } = useAttachmentContext();
|
||||
|
||||
const handleClick = useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
onRemove?.();
|
||||
},
|
||||
[onRemove],
|
||||
);
|
||||
|
||||
if (!onRemove) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
aria-label={label}
|
||||
className={cn(
|
||||
variant === "grid" && [
|
||||
"absolute top-2 right-2 size-6 rounded-full p-0",
|
||||
"bg-background/80 backdrop-blur-sm",
|
||||
"opacity-0 transition-opacity group-hover:opacity-100",
|
||||
"hover:bg-background",
|
||||
"[&>svg]:size-3",
|
||||
],
|
||||
variant === "inline" && [
|
||||
"size-5 rounded p-0",
|
||||
"opacity-0 transition-opacity group-hover:opacity-100",
|
||||
"[&>svg]:size-2.5",
|
||||
],
|
||||
variant === "list" && ["size-8 shrink-0 rounded p-0", "[&>svg]:size-4"],
|
||||
className,
|
||||
)}
|
||||
onClick={handleClick}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
{children ?? <XIcon />}
|
||||
<span className="sr-only">{label}</span>
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// AttachmentHoverCard - Hover preview
|
||||
// ============================================================================
|
||||
|
||||
export type AttachmentHoverCardProps = ComponentProps<typeof HoverCard> & {
|
||||
openDelay?: number;
|
||||
closeDelay?: number;
|
||||
};
|
||||
|
||||
export const AttachmentHoverCard = ({ ...props }: AttachmentHoverCardProps) => (
|
||||
<HoverCard {...props} />
|
||||
);
|
||||
|
||||
export type AttachmentHoverCardTriggerProps = ComponentProps<
|
||||
typeof HoverCardTrigger
|
||||
>;
|
||||
|
||||
export const AttachmentHoverCardTrigger = (
|
||||
props: AttachmentHoverCardTriggerProps,
|
||||
) => <HoverCardTrigger {...props} />;
|
||||
|
||||
export type AttachmentHoverCardContentProps = ComponentProps<
|
||||
typeof HoverCardContent
|
||||
>;
|
||||
|
||||
export const AttachmentHoverCardContent = ({
|
||||
align = "start",
|
||||
className,
|
||||
...props
|
||||
}: AttachmentHoverCardContentProps) => (
|
||||
<HoverCardContent
|
||||
align={align}
|
||||
className={cn("w-auto p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
// ============================================================================
|
||||
// AttachmentEmpty - Empty state
|
||||
// ============================================================================
|
||||
|
||||
export type AttachmentEmptyProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const AttachmentEmpty = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: AttachmentEmptyProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-center p-4 text-muted-foreground text-sm",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? "No attachments"}
|
||||
</div>
|
||||
);
|
||||
@@ -1,255 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { Experimental_SpeechResult as SpeechResult } from "ai";
|
||||
import {
|
||||
MediaControlBar,
|
||||
MediaController,
|
||||
MediaDurationDisplay,
|
||||
MediaMuteButton,
|
||||
MediaPlayButton,
|
||||
MediaSeekBackwardButton,
|
||||
MediaSeekForwardButton,
|
||||
MediaTimeDisplay,
|
||||
MediaTimeRange,
|
||||
MediaVolumeRange,
|
||||
} from "media-chrome/react";
|
||||
import type { ComponentProps, CSSProperties } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ButtonGroup, ButtonGroupText } from "@/components/ui/button-group";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type AudioPlayerProps = Omit<
|
||||
ComponentProps<typeof MediaController>,
|
||||
"audio"
|
||||
>;
|
||||
|
||||
export const AudioPlayer = ({
|
||||
children,
|
||||
style,
|
||||
...props
|
||||
}: AudioPlayerProps) => (
|
||||
<MediaController
|
||||
audio
|
||||
data-slot="audio-player"
|
||||
style={
|
||||
{
|
||||
"--media-background-color": "transparent",
|
||||
"--media-button-icon-height": "1rem",
|
||||
"--media-button-icon-width": "1rem",
|
||||
"--media-control-background": "transparent",
|
||||
"--media-control-hover-background": "var(--color-accent)",
|
||||
"--media-control-padding": "0",
|
||||
"--media-font": "var(--font-sans)",
|
||||
"--media-font-size": "10px",
|
||||
"--media-icon-color": "currentColor",
|
||||
"--media-preview-time-background": "var(--color-background)",
|
||||
"--media-preview-time-border-radius": "var(--radius-md)",
|
||||
"--media-preview-time-text-shadow": "none",
|
||||
"--media-primary-color": "var(--color-primary)",
|
||||
"--media-range-bar-color": "var(--color-primary)",
|
||||
"--media-range-track-background": "var(--color-secondary)",
|
||||
"--media-secondary-color": "var(--color-secondary)",
|
||||
"--media-text-color": "var(--color-foreground)",
|
||||
"--media-tooltip-arrow-display": "none",
|
||||
"--media-tooltip-background": "var(--color-background)",
|
||||
"--media-tooltip-border-radius": "var(--radius-md)",
|
||||
...style,
|
||||
} as CSSProperties
|
||||
}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</MediaController>
|
||||
);
|
||||
|
||||
export type AudioPlayerElementProps = Omit<ComponentProps<"audio">, "src"> &
|
||||
(
|
||||
| {
|
||||
data: SpeechResult["audio"];
|
||||
}
|
||||
| {
|
||||
src: string;
|
||||
}
|
||||
);
|
||||
|
||||
export const AudioPlayerElement = ({ ...props }: AudioPlayerElementProps) => (
|
||||
// oxlint-disable-next-line eslint-plugin-jsx-a11y(media-has-caption) -- audio player captions are provided by consumer
|
||||
<audio
|
||||
data-slot="audio-player-element"
|
||||
slot="media"
|
||||
src={
|
||||
"src" in props
|
||||
? props.src
|
||||
: `data:${props.data.mediaType};base64,${props.data.base64}`
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type AudioPlayerControlBarProps = ComponentProps<typeof MediaControlBar>;
|
||||
|
||||
export const AudioPlayerControlBar = ({
|
||||
children,
|
||||
...props
|
||||
}: AudioPlayerControlBarProps) => (
|
||||
<MediaControlBar data-slot="audio-player-control-bar" {...props}>
|
||||
<ButtonGroup orientation="horizontal">{children}</ButtonGroup>
|
||||
</MediaControlBar>
|
||||
);
|
||||
|
||||
export type AudioPlayerPlayButtonProps = ComponentProps<typeof MediaPlayButton>;
|
||||
|
||||
export const AudioPlayerPlayButton = ({
|
||||
className,
|
||||
...props
|
||||
}: AudioPlayerPlayButtonProps) => (
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="outline"
|
||||
render={
|
||||
<MediaPlayButton
|
||||
className={cn("bg-transparent", className)}
|
||||
data-slot="audio-player-play-button"
|
||||
{...props}
|
||||
/>
|
||||
}
|
||||
></Button>
|
||||
);
|
||||
|
||||
export type AudioPlayerSeekBackwardButtonProps = ComponentProps<
|
||||
typeof MediaSeekBackwardButton
|
||||
>;
|
||||
|
||||
export const AudioPlayerSeekBackwardButton = ({
|
||||
seekOffset = 10,
|
||||
...props
|
||||
}: AudioPlayerSeekBackwardButtonProps) => (
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="outline"
|
||||
render={
|
||||
<MediaSeekBackwardButton
|
||||
data-slot="audio-player-seek-backward-button"
|
||||
seekOffset={seekOffset}
|
||||
{...props}
|
||||
/>
|
||||
}
|
||||
></Button>
|
||||
);
|
||||
|
||||
export type AudioPlayerSeekForwardButtonProps = ComponentProps<
|
||||
typeof MediaSeekForwardButton
|
||||
>;
|
||||
|
||||
export const AudioPlayerSeekForwardButton = ({
|
||||
seekOffset = 10,
|
||||
...props
|
||||
}: AudioPlayerSeekForwardButtonProps) => (
|
||||
<Button
|
||||
size="icon-sm"
|
||||
variant="outline"
|
||||
render={
|
||||
<MediaSeekForwardButton
|
||||
data-slot="audio-player-seek-forward-button"
|
||||
seekOffset={seekOffset}
|
||||
{...props}
|
||||
/>
|
||||
}
|
||||
></Button>
|
||||
);
|
||||
|
||||
export type AudioPlayerTimeDisplayProps = ComponentProps<
|
||||
typeof MediaTimeDisplay
|
||||
>;
|
||||
|
||||
export const AudioPlayerTimeDisplay = ({
|
||||
className,
|
||||
...props
|
||||
}: AudioPlayerTimeDisplayProps) => (
|
||||
<ButtonGroupText
|
||||
className="bg-transparent"
|
||||
render={
|
||||
<MediaTimeDisplay
|
||||
className={cn("tabular-nums", className)}
|
||||
data-slot="audio-player-time-display"
|
||||
{...props}
|
||||
/>
|
||||
}
|
||||
></ButtonGroupText>
|
||||
);
|
||||
|
||||
export type AudioPlayerTimeRangeProps = ComponentProps<typeof MediaTimeRange>;
|
||||
|
||||
export const AudioPlayerTimeRange = ({
|
||||
className,
|
||||
...props
|
||||
}: AudioPlayerTimeRangeProps) => (
|
||||
<ButtonGroupText
|
||||
className="bg-transparent"
|
||||
render={
|
||||
<MediaTimeRange
|
||||
className={cn("", className)}
|
||||
data-slot="audio-player-time-range"
|
||||
{...props}
|
||||
/>
|
||||
}
|
||||
></ButtonGroupText>
|
||||
);
|
||||
|
||||
export type AudioPlayerDurationDisplayProps = ComponentProps<
|
||||
typeof MediaDurationDisplay
|
||||
>;
|
||||
|
||||
export const AudioPlayerDurationDisplay = ({
|
||||
className,
|
||||
...props
|
||||
}: AudioPlayerDurationDisplayProps) => (
|
||||
<ButtonGroupText
|
||||
className="bg-transparent"
|
||||
render={
|
||||
<MediaDurationDisplay
|
||||
className={cn("tabular-nums", className)}
|
||||
data-slot="audio-player-duration-display"
|
||||
{...props}
|
||||
/>
|
||||
}
|
||||
></ButtonGroupText>
|
||||
);
|
||||
|
||||
export type AudioPlayerMuteButtonProps = ComponentProps<typeof MediaMuteButton>;
|
||||
|
||||
export const AudioPlayerMuteButton = ({
|
||||
className,
|
||||
...props
|
||||
}: AudioPlayerMuteButtonProps) => (
|
||||
<ButtonGroupText
|
||||
className="bg-transparent"
|
||||
render={
|
||||
<MediaMuteButton
|
||||
className={cn("", className)}
|
||||
data-slot="audio-player-mute-button"
|
||||
{...props}
|
||||
/>
|
||||
}
|
||||
></ButtonGroupText>
|
||||
);
|
||||
|
||||
export type AudioPlayerVolumeRangeProps = ComponentProps<
|
||||
typeof MediaVolumeRange
|
||||
>;
|
||||
|
||||
export const AudioPlayerVolumeRange = ({
|
||||
className,
|
||||
...props
|
||||
}: AudioPlayerVolumeRangeProps) => (
|
||||
<ButtonGroupText
|
||||
className="bg-transparent"
|
||||
render={
|
||||
<MediaVolumeRange
|
||||
className={cn("", className)}
|
||||
data-slot="audio-player-volume-range"
|
||||
{...props}
|
||||
/>
|
||||
}
|
||||
></ButtonGroupText>
|
||||
);
|
||||
@@ -1,26 +0,0 @@
|
||||
import type { ReactFlowProps } from "@xyflow/react";
|
||||
import { Background, ReactFlow } from "@xyflow/react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import "@xyflow/react/dist/style.css";
|
||||
|
||||
type CanvasProps = ReactFlowProps & {
|
||||
children?: ReactNode;
|
||||
};
|
||||
|
||||
const deleteKeyCode = ["Backspace", "Delete"];
|
||||
|
||||
export const Canvas = ({ children, ...props }: CanvasProps) => (
|
||||
<ReactFlow
|
||||
deleteKeyCode={deleteKeyCode}
|
||||
fitView
|
||||
panOnDrag={false}
|
||||
panOnScroll
|
||||
selectionOnDrag={true}
|
||||
zoomOnDoubleClick={false}
|
||||
{...props}
|
||||
>
|
||||
<Background bgColor="var(--sidebar)" />
|
||||
{children}
|
||||
</ReactFlow>
|
||||
);
|
||||
@@ -1,222 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useControllableState } from "@radix-ui/react-use-controllable-state";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { BrainIcon, ChevronDownIcon, DotIcon } from "lucide-react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { createContext, memo, useContext, useMemo } from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "@/components/ui/collapsible";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ChainOfThoughtContextValue {
|
||||
isOpen: boolean;
|
||||
setIsOpen: (open: boolean) => void;
|
||||
}
|
||||
|
||||
const ChainOfThoughtContext = createContext<ChainOfThoughtContextValue | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const useChainOfThought = () => {
|
||||
const context = useContext(ChainOfThoughtContext);
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
"ChainOfThought components must be used within ChainOfThought",
|
||||
);
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export type ChainOfThoughtProps = ComponentProps<"div"> & {
|
||||
open?: boolean;
|
||||
defaultOpen?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
};
|
||||
|
||||
export const ChainOfThought = memo(
|
||||
({
|
||||
className,
|
||||
open,
|
||||
defaultOpen = false,
|
||||
onOpenChange,
|
||||
children,
|
||||
...props
|
||||
}: ChainOfThoughtProps) => {
|
||||
const [isOpen, setIsOpen] = useControllableState({
|
||||
defaultProp: defaultOpen,
|
||||
onChange: onOpenChange,
|
||||
prop: open,
|
||||
});
|
||||
|
||||
const chainOfThoughtContext = useMemo(
|
||||
() => ({ isOpen, setIsOpen }),
|
||||
[isOpen, setIsOpen],
|
||||
);
|
||||
|
||||
return (
|
||||
<ChainOfThoughtContext.Provider value={chainOfThoughtContext}>
|
||||
<div className={cn("not-prose w-full space-y-4", className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
</ChainOfThoughtContext.Provider>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
export type ChainOfThoughtHeaderProps = ComponentProps<
|
||||
typeof CollapsibleTrigger
|
||||
>;
|
||||
|
||||
export const ChainOfThoughtHeader = memo(
|
||||
({ className, children, ...props }: ChainOfThoughtHeaderProps) => {
|
||||
const { isOpen, setIsOpen } = useChainOfThought();
|
||||
|
||||
return (
|
||||
<Collapsible onOpenChange={setIsOpen} open={isOpen}>
|
||||
<CollapsibleTrigger
|
||||
className={cn(
|
||||
"flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<BrainIcon className="size-4" />
|
||||
<span className="flex-1 text-left">
|
||||
{children ?? "Chain of Thought"}
|
||||
</span>
|
||||
<ChevronDownIcon
|
||||
className={cn(
|
||||
"size-4 transition-transform",
|
||||
isOpen ? "rotate-180" : "rotate-0",
|
||||
)}
|
||||
/>
|
||||
</CollapsibleTrigger>
|
||||
</Collapsible>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
export type ChainOfThoughtStepProps = ComponentProps<"div"> & {
|
||||
icon?: LucideIcon;
|
||||
label: ReactNode;
|
||||
description?: ReactNode;
|
||||
status?: "complete" | "active" | "pending";
|
||||
};
|
||||
|
||||
const stepStatusStyles = {
|
||||
active: "text-foreground",
|
||||
complete: "text-muted-foreground",
|
||||
pending: "text-muted-foreground/50",
|
||||
};
|
||||
|
||||
export const ChainOfThoughtStep = memo(
|
||||
({
|
||||
className,
|
||||
icon: Icon = DotIcon,
|
||||
label,
|
||||
description,
|
||||
status = "complete",
|
||||
children,
|
||||
...props
|
||||
}: ChainOfThoughtStepProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex gap-2 text-sm",
|
||||
stepStatusStyles[status],
|
||||
"fade-in-0 slide-in-from-top-2 animate-in",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="relative mt-0.5">
|
||||
<Icon className="size-4" />
|
||||
<div className="absolute top-7 bottom-0 left-1/2 -mx-px w-px bg-border" />
|
||||
</div>
|
||||
<div className="flex-1 space-y-2 overflow-hidden">
|
||||
<div>{label}</div>
|
||||
{description && (
|
||||
<div className="text-muted-foreground text-xs">{description}</div>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
);
|
||||
|
||||
export type ChainOfThoughtSearchResultsProps = ComponentProps<"div">;
|
||||
|
||||
export const ChainOfThoughtSearchResults = memo(
|
||||
({ className, ...props }: ChainOfThoughtSearchResultsProps) => (
|
||||
<div
|
||||
className={cn("flex flex-wrap items-center gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
);
|
||||
|
||||
export type ChainOfThoughtSearchResultProps = ComponentProps<typeof Badge>;
|
||||
|
||||
export const ChainOfThoughtSearchResult = memo(
|
||||
({ className, children, ...props }: ChainOfThoughtSearchResultProps) => (
|
||||
<Badge
|
||||
className={cn("gap-1 px-2 py-0.5 font-normal text-xs", className)}
|
||||
variant="secondary"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</Badge>
|
||||
),
|
||||
);
|
||||
|
||||
export type ChainOfThoughtContentProps = ComponentProps<
|
||||
typeof CollapsibleContent
|
||||
>;
|
||||
|
||||
export const ChainOfThoughtContent = memo(
|
||||
({ className, children, ...props }: ChainOfThoughtContentProps) => {
|
||||
const { isOpen } = useChainOfThought();
|
||||
|
||||
return (
|
||||
<Collapsible open={isOpen}>
|
||||
<CollapsibleContent
|
||||
className={cn(
|
||||
"mt-2 space-y-3",
|
||||
"data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
export type ChainOfThoughtImageProps = ComponentProps<"div"> & {
|
||||
caption?: string;
|
||||
};
|
||||
|
||||
export const ChainOfThoughtImage = memo(
|
||||
({ className, children, caption, ...props }: ChainOfThoughtImageProps) => (
|
||||
<div className={cn("mt-2 space-y-2", className)} {...props}>
|
||||
<div className="relative flex max-h-[22rem] items-center justify-center overflow-hidden rounded-lg bg-muted p-3">
|
||||
{children}
|
||||
</div>
|
||||
{caption && <p className="text-muted-foreground text-xs">{caption}</p>}
|
||||
</div>
|
||||
),
|
||||
);
|
||||
|
||||
ChainOfThought.displayName = "ChainOfThought";
|
||||
ChainOfThoughtHeader.displayName = "ChainOfThoughtHeader";
|
||||
ChainOfThoughtStep.displayName = "ChainOfThoughtStep";
|
||||
ChainOfThoughtSearchResults.displayName = "ChainOfThoughtSearchResults";
|
||||
ChainOfThoughtSearchResult.displayName = "ChainOfThoughtSearchResult";
|
||||
ChainOfThoughtContent.displayName = "ChainOfThoughtContent";
|
||||
ChainOfThoughtImage.displayName = "ChainOfThoughtImage";
|
||||
@@ -1,73 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { LucideProps } from "lucide-react";
|
||||
import { BookmarkIcon } from "lucide-react";
|
||||
import type { ComponentProps, HTMLAttributes } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type CheckpointProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const Checkpoint = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CheckpointProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-0.5 overflow-hidden text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<Separator />
|
||||
</div>
|
||||
);
|
||||
|
||||
export type CheckpointIconProps = LucideProps;
|
||||
|
||||
export const CheckpointIcon = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CheckpointIconProps) =>
|
||||
children ?? (
|
||||
<BookmarkIcon className={cn("size-4 shrink-0", className)} {...props} />
|
||||
);
|
||||
|
||||
export type CheckpointTriggerProps = ComponentProps<typeof Button> & {
|
||||
tooltip?: string;
|
||||
};
|
||||
|
||||
export const CheckpointTrigger = ({
|
||||
children,
|
||||
variant = "ghost",
|
||||
size = "sm",
|
||||
tooltip,
|
||||
...props
|
||||
}: CheckpointTriggerProps) =>
|
||||
tooltip ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button size={size} type="button" variant={variant} {...props} />
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</TooltipTrigger>
|
||||
<TooltipContent align="start" side="bottom">
|
||||
{tooltip}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Button size={size} type="button" variant={variant} {...props}>
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
@@ -1,558 +0,0 @@
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import type { ComponentProps, CSSProperties, HTMLAttributes } from "react";
|
||||
import {
|
||||
createContext,
|
||||
memo,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import type {
|
||||
BundledLanguage,
|
||||
BundledTheme,
|
||||
HighlighterGeneric,
|
||||
ThemedToken,
|
||||
} from "shiki";
|
||||
import { createHighlighter } from "shiki";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Shiki uses bitflags for font styles: 1=italic, 2=bold, 4=underline
|
||||
// oxlint-disable-next-line eslint(no-bitwise)
|
||||
const isItalic = (fontStyle: number | undefined) => fontStyle && fontStyle & 1;
|
||||
// oxlint-disable-next-line eslint(no-bitwise)
|
||||
const isBold = (fontStyle: number | undefined) => fontStyle && fontStyle & 2;
|
||||
const isUnderline = (fontStyle: number | undefined) =>
|
||||
// oxlint-disable-next-line eslint(no-bitwise)
|
||||
fontStyle && fontStyle & 4;
|
||||
|
||||
// Transform tokens to include pre-computed keys to avoid noArrayIndexKey lint
|
||||
interface KeyedToken {
|
||||
token: ThemedToken;
|
||||
key: string;
|
||||
}
|
||||
interface KeyedLine {
|
||||
tokens: KeyedToken[];
|
||||
key: string;
|
||||
}
|
||||
|
||||
const addKeysToTokens = (lines: ThemedToken[][]): KeyedLine[] =>
|
||||
lines.map((line, lineIdx) => ({
|
||||
key: `line-${lineIdx}`,
|
||||
tokens: line.map((token, tokenIdx) => ({
|
||||
key: `line-${lineIdx}-${tokenIdx}`,
|
||||
token,
|
||||
})),
|
||||
}));
|
||||
|
||||
// Token rendering component
|
||||
const TokenSpan = ({ token }: { token: ThemedToken }) => (
|
||||
<span
|
||||
className="dark:bg-(--shiki-dark-bg)! dark:text-(--shiki-dark)!"
|
||||
style={
|
||||
{
|
||||
backgroundColor: token.bgColor,
|
||||
color: token.color,
|
||||
fontStyle: isItalic(token.fontStyle) ? "italic" : undefined,
|
||||
fontWeight: isBold(token.fontStyle) ? "bold" : undefined,
|
||||
textDecoration: isUnderline(token.fontStyle) ? "underline" : undefined,
|
||||
...token.htmlStyle,
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
{token.content}
|
||||
</span>
|
||||
);
|
||||
|
||||
// Line number styles using CSS counters
|
||||
const LINE_NUMBER_CLASSES = cn(
|
||||
"block",
|
||||
"before:content-[counter(line)]",
|
||||
"before:inline-block",
|
||||
"before:[counter-increment:line]",
|
||||
"before:w-8",
|
||||
"before:mr-4",
|
||||
"before:text-right",
|
||||
"before:text-muted-foreground/50",
|
||||
"before:font-mono",
|
||||
"before:select-none",
|
||||
);
|
||||
|
||||
// Line rendering component
|
||||
const LineSpan = ({
|
||||
keyedLine,
|
||||
showLineNumbers,
|
||||
}: {
|
||||
keyedLine: KeyedLine;
|
||||
showLineNumbers: boolean;
|
||||
}) => (
|
||||
<span className={showLineNumbers ? LINE_NUMBER_CLASSES : "block"}>
|
||||
{keyedLine.tokens.length === 0
|
||||
? "\n"
|
||||
: keyedLine.tokens.map(({ token, key }) => (
|
||||
<TokenSpan key={key} token={token} />
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
|
||||
// Types
|
||||
type CodeBlockProps = HTMLAttributes<HTMLDivElement> & {
|
||||
code: string;
|
||||
language: BundledLanguage;
|
||||
showLineNumbers?: boolean;
|
||||
};
|
||||
|
||||
interface TokenizedCode {
|
||||
tokens: ThemedToken[][];
|
||||
fg: string;
|
||||
bg: string;
|
||||
}
|
||||
|
||||
interface CodeBlockContextType {
|
||||
code: string;
|
||||
}
|
||||
|
||||
// Context
|
||||
const CodeBlockContext = createContext<CodeBlockContextType>({
|
||||
code: "",
|
||||
});
|
||||
|
||||
// Highlighter cache (singleton per language)
|
||||
const highlighterCache = new Map<
|
||||
string,
|
||||
Promise<HighlighterGeneric<BundledLanguage, BundledTheme>>
|
||||
>();
|
||||
|
||||
// Token cache
|
||||
const tokensCache = new Map<string, TokenizedCode>();
|
||||
|
||||
// Subscribers for async token updates
|
||||
const subscribers = new Map<string, Set<(result: TokenizedCode) => void>>();
|
||||
|
||||
const getTokensCacheKey = (code: string, language: BundledLanguage) => {
|
||||
const start = code.slice(0, 100);
|
||||
const end = code.length > 100 ? code.slice(-100) : "";
|
||||
return `${language}:${code.length}:${start}:${end}`;
|
||||
};
|
||||
|
||||
const getHighlighter = (
|
||||
language: BundledLanguage,
|
||||
): Promise<HighlighterGeneric<BundledLanguage, BundledTheme>> => {
|
||||
const cached = highlighterCache.get(language);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const highlighterPromise = createHighlighter({
|
||||
langs: [language],
|
||||
themes: ["github-light", "github-dark"],
|
||||
});
|
||||
|
||||
highlighterCache.set(language, highlighterPromise);
|
||||
return highlighterPromise;
|
||||
};
|
||||
|
||||
// Create raw tokens for immediate display while highlighting loads
|
||||
const createRawTokens = (code: string): TokenizedCode => ({
|
||||
bg: "transparent",
|
||||
fg: "inherit",
|
||||
tokens: code.split("\n").map((line) =>
|
||||
line === ""
|
||||
? []
|
||||
: [
|
||||
{
|
||||
color: "inherit",
|
||||
content: line,
|
||||
} as ThemedToken,
|
||||
],
|
||||
),
|
||||
});
|
||||
|
||||
// Synchronous highlight with callback for async results
|
||||
export const highlightCode = (
|
||||
code: string,
|
||||
language: BundledLanguage,
|
||||
// oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-callbacks)
|
||||
callback?: (result: TokenizedCode) => void,
|
||||
): TokenizedCode | null => {
|
||||
const tokensCacheKey = getTokensCacheKey(code, language);
|
||||
|
||||
// Return cached result if available
|
||||
const cached = tokensCache.get(tokensCacheKey);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
// Subscribe callback if provided
|
||||
if (callback) {
|
||||
if (!subscribers.has(tokensCacheKey)) {
|
||||
subscribers.set(tokensCacheKey, new Set());
|
||||
}
|
||||
subscribers.get(tokensCacheKey)?.add(callback);
|
||||
}
|
||||
|
||||
// Start highlighting in background - fire-and-forget async pattern
|
||||
getHighlighter(language)
|
||||
// oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-then)
|
||||
.then((highlighter) => {
|
||||
const availableLangs = highlighter.getLoadedLanguages();
|
||||
const langToUse = availableLangs.includes(language) ? language : "text";
|
||||
|
||||
const result = highlighter.codeToTokens(code, {
|
||||
lang: langToUse,
|
||||
themes: {
|
||||
dark: "github-dark",
|
||||
light: "github-light",
|
||||
},
|
||||
});
|
||||
|
||||
const tokenized: TokenizedCode = {
|
||||
bg: result.bg ?? "transparent",
|
||||
fg: result.fg ?? "inherit",
|
||||
tokens: result.tokens,
|
||||
};
|
||||
|
||||
// Cache the result
|
||||
tokensCache.set(tokensCacheKey, tokenized);
|
||||
|
||||
// Notify all subscribers
|
||||
const subs = subscribers.get(tokensCacheKey);
|
||||
if (subs) {
|
||||
for (const sub of subs) {
|
||||
sub(tokenized);
|
||||
}
|
||||
subscribers.delete(tokensCacheKey);
|
||||
}
|
||||
})
|
||||
// oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-then), eslint-plugin-promise(prefer-await-to-callbacks)
|
||||
.catch((error) => {
|
||||
console.error("Failed to highlight code:", error);
|
||||
subscribers.delete(tokensCacheKey);
|
||||
});
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const CodeBlockBody = memo(
|
||||
({
|
||||
tokenized,
|
||||
showLineNumbers,
|
||||
className,
|
||||
}: {
|
||||
tokenized: TokenizedCode;
|
||||
showLineNumbers: boolean;
|
||||
className?: string;
|
||||
}) => {
|
||||
const preStyle = useMemo(
|
||||
() => ({
|
||||
backgroundColor: tokenized.bg,
|
||||
color: tokenized.fg,
|
||||
}),
|
||||
[tokenized.bg, tokenized.fg],
|
||||
);
|
||||
|
||||
const keyedLines = useMemo(
|
||||
() => addKeysToTokens(tokenized.tokens),
|
||||
[tokenized.tokens],
|
||||
);
|
||||
|
||||
return (
|
||||
<pre
|
||||
className={cn(
|
||||
"dark:bg-(--shiki-dark-bg)! dark:text-(--shiki-dark)! m-0 p-4 text-sm",
|
||||
className,
|
||||
)}
|
||||
style={preStyle}
|
||||
>
|
||||
<code
|
||||
className={cn(
|
||||
"font-mono text-sm",
|
||||
showLineNumbers &&
|
||||
"[counter-increment:line_0] [counter-reset:line]",
|
||||
)}
|
||||
>
|
||||
{keyedLines.map((keyedLine) => (
|
||||
<LineSpan
|
||||
key={keyedLine.key}
|
||||
keyedLine={keyedLine}
|
||||
showLineNumbers={showLineNumbers}
|
||||
/>
|
||||
))}
|
||||
</code>
|
||||
</pre>
|
||||
);
|
||||
},
|
||||
(prevProps, nextProps) =>
|
||||
prevProps.tokenized === nextProps.tokenized &&
|
||||
prevProps.showLineNumbers === nextProps.showLineNumbers &&
|
||||
prevProps.className === nextProps.className,
|
||||
);
|
||||
|
||||
CodeBlockBody.displayName = "CodeBlockBody";
|
||||
|
||||
export const CodeBlockContainer = ({
|
||||
className,
|
||||
language,
|
||||
style,
|
||||
...props
|
||||
}: HTMLAttributes<HTMLDivElement> & { language: string }) => (
|
||||
<div
|
||||
className={cn(
|
||||
"group relative w-full overflow-hidden rounded-sm border bg-background text-foreground",
|
||||
className,
|
||||
)}
|
||||
data-language={language}
|
||||
style={{
|
||||
containIntrinsicSize: "auto 200px",
|
||||
contentVisibility: "auto",
|
||||
...style,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export const CodeBlockHeader = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between border-b bg-muted/80 px-3 py-2 text-muted-foreground text-xs",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export const CodeBlockTitle = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn("flex items-center gap-2", className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export const CodeBlockFilename = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: HTMLAttributes<HTMLSpanElement>) => (
|
||||
<span className={cn("font-mono", className)} {...props}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
|
||||
export const CodeBlockActions = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn("-my-1 -mr-1 flex items-center gap-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export const CodeBlockContent = ({
|
||||
code,
|
||||
language,
|
||||
showLineNumbers = false,
|
||||
}: {
|
||||
code: string;
|
||||
language: BundledLanguage;
|
||||
showLineNumbers?: boolean;
|
||||
}) => {
|
||||
// Memoized raw tokens for immediate display
|
||||
const rawTokens = useMemo(() => createRawTokens(code), [code]);
|
||||
|
||||
// Synchronous cache lookup — avoids setState in effect for cached results
|
||||
const syncTokens = useMemo(
|
||||
() => highlightCode(code, language) ?? rawTokens,
|
||||
[code, language, rawTokens],
|
||||
);
|
||||
|
||||
// Async highlighting — keyed by identity-stable memo so stale tokens are
|
||||
// discarded without reading a ref during render or setState in effect body.
|
||||
const asyncKey = useMemo(() => ({ code, language }), [code, language]);
|
||||
const [asyncState, setAsyncState] = useState<{
|
||||
key: { code: string; language: string };
|
||||
tokens: TokenizedCode | null;
|
||||
}>({ key: asyncKey, tokens: null });
|
||||
|
||||
const asyncTokens = asyncState.key === asyncKey ? asyncState.tokens : null;
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
highlightCode(code, language, (result) => {
|
||||
if (!cancelled) {
|
||||
setAsyncState({ key: asyncKey, tokens: result });
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [code, language, asyncKey]);
|
||||
|
||||
const tokenized = asyncTokens ?? syncTokens;
|
||||
|
||||
return (
|
||||
<div className="relative overflow-auto">
|
||||
<CodeBlockBody showLineNumbers={showLineNumbers} tokenized={tokenized} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const CodeBlock = ({
|
||||
code,
|
||||
language,
|
||||
showLineNumbers = false,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CodeBlockProps) => {
|
||||
const contextValue = useMemo(() => ({ code }), [code]);
|
||||
|
||||
return (
|
||||
<CodeBlockContext.Provider value={contextValue}>
|
||||
<CodeBlockContainer className={className} language={language} {...props}>
|
||||
{children}
|
||||
<CodeBlockContent
|
||||
code={code}
|
||||
language={language}
|
||||
showLineNumbers={showLineNumbers}
|
||||
/>
|
||||
</CodeBlockContainer>
|
||||
</CodeBlockContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type CodeBlockCopyButtonProps = ComponentProps<typeof Button> & {
|
||||
onCopy?: () => void;
|
||||
onError?: (error: Error) => void;
|
||||
timeout?: number;
|
||||
};
|
||||
|
||||
export const CodeBlockCopyButton = ({
|
||||
onCopy,
|
||||
onError,
|
||||
timeout = 2000,
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: CodeBlockCopyButtonProps) => {
|
||||
const [isCopied, setIsCopied] = useState(false);
|
||||
const timeoutRef = useRef<number>(0);
|
||||
const { code } = useContext(CodeBlockContext);
|
||||
|
||||
const copyToClipboard = useCallback(async () => {
|
||||
if (typeof window === "undefined" || !navigator?.clipboard?.writeText) {
|
||||
onError?.(new Error("Clipboard API not available"));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!isCopied) {
|
||||
await navigator.clipboard.writeText(code);
|
||||
setIsCopied(true);
|
||||
onCopy?.();
|
||||
timeoutRef.current = window.setTimeout(
|
||||
() => setIsCopied(false),
|
||||
timeout,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
onError?.(error as Error);
|
||||
}
|
||||
}, [code, onCopy, onError, timeout, isCopied]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
window.clearTimeout(timeoutRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const Icon = isCopied ? CheckIcon : CopyIcon;
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn("shrink-0", className)}
|
||||
onClick={copyToClipboard}
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
{children ?? <Icon size={14} />}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export type CodeBlockLanguageSelectorProps = ComponentProps<typeof Select>;
|
||||
|
||||
export const CodeBlockLanguageSelector = (
|
||||
props: CodeBlockLanguageSelectorProps,
|
||||
) => <Select {...props} />;
|
||||
|
||||
export type CodeBlockLanguageSelectorTriggerProps = ComponentProps<
|
||||
typeof SelectTrigger
|
||||
>;
|
||||
|
||||
export const CodeBlockLanguageSelectorTrigger = ({
|
||||
className,
|
||||
...props
|
||||
}: CodeBlockLanguageSelectorTriggerProps) => (
|
||||
<SelectTrigger
|
||||
className={cn(
|
||||
"h-7 border-none bg-transparent px-2 text-xs shadow-none",
|
||||
className,
|
||||
)}
|
||||
size="sm"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type CodeBlockLanguageSelectorValueProps = ComponentProps<
|
||||
typeof SelectValue
|
||||
>;
|
||||
|
||||
export const CodeBlockLanguageSelectorValue = (
|
||||
props: CodeBlockLanguageSelectorValueProps,
|
||||
) => <SelectValue {...props} />;
|
||||
|
||||
export type CodeBlockLanguageSelectorContentProps = ComponentProps<
|
||||
typeof SelectContent
|
||||
>;
|
||||
|
||||
export const CodeBlockLanguageSelectorContent = ({
|
||||
align = "end",
|
||||
...props
|
||||
}: CodeBlockLanguageSelectorContentProps) => (
|
||||
<SelectContent align={align} {...props} />
|
||||
);
|
||||
|
||||
export type CodeBlockLanguageSelectorItemProps = ComponentProps<
|
||||
typeof SelectItem
|
||||
>;
|
||||
|
||||
export const CodeBlockLanguageSelectorItem = (
|
||||
props: CodeBlockLanguageSelectorItemProps,
|
||||
) => <SelectItem {...props} />;
|
||||
@@ -1,462 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
CheckIcon,
|
||||
CopyIcon,
|
||||
FileIcon,
|
||||
GitCommitIcon,
|
||||
MinusIcon,
|
||||
PlusIcon,
|
||||
} from "lucide-react";
|
||||
import type { ComponentProps, HTMLAttributes } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "@/components/ui/collapsible";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type CommitProps = ComponentProps<typeof Collapsible>;
|
||||
|
||||
export const Commit = ({ className, children, ...props }: CommitProps) => (
|
||||
<Collapsible
|
||||
className={cn("rounded-lg border bg-background", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</Collapsible>
|
||||
);
|
||||
|
||||
export type CommitHeaderProps = ComponentProps<typeof CollapsibleTrigger>;
|
||||
|
||||
export const CommitHeader = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitHeaderProps) => (
|
||||
<CollapsibleTrigger
|
||||
{...props}
|
||||
render={
|
||||
<div
|
||||
className={cn(
|
||||
"group flex cursor-pointer items-center justify-between gap-4 p-3 text-left transition-colors hover:opacity-80",
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</CollapsibleTrigger>
|
||||
);
|
||||
|
||||
export type CommitHashProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const CommitHash = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitHashProps) => (
|
||||
<span className={cn("font-mono text-xs", className)} {...props}>
|
||||
<GitCommitIcon className="mr-1 inline-block size-3" />
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
|
||||
export type CommitMessageProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const CommitMessage = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitMessageProps) => (
|
||||
<span className={cn("font-medium text-sm", className)} {...props}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
|
||||
export type CommitMetadataProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const CommitMetadata = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitMetadataProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-muted-foreground text-xs",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type CommitSeparatorProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const CommitSeparator = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitSeparatorProps) => (
|
||||
<span className={className} {...props}>
|
||||
{children ?? "•"}
|
||||
</span>
|
||||
);
|
||||
|
||||
export type CommitInfoProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const CommitInfo = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitInfoProps) => (
|
||||
<div className={cn("flex flex-1 flex-col", className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type CommitAuthorProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const CommitAuthor = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitAuthorProps) => (
|
||||
<div className={cn("flex items-center", className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type CommitAuthorAvatarProps = ComponentProps<typeof Avatar> & {
|
||||
initials: string;
|
||||
};
|
||||
|
||||
export const CommitAuthorAvatar = ({
|
||||
initials,
|
||||
className,
|
||||
...props
|
||||
}: CommitAuthorAvatarProps) => (
|
||||
<Avatar className={cn("size-8", className)} {...props}>
|
||||
<AvatarFallback className="text-xs">{initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
|
||||
export type CommitTimestampProps = HTMLAttributes<HTMLTimeElement> & {
|
||||
date: Date;
|
||||
};
|
||||
|
||||
const relativeTimeFormat = new Intl.RelativeTimeFormat("en", {
|
||||
numeric: "auto",
|
||||
});
|
||||
|
||||
const formatRelativeDate = (date: Date) => {
|
||||
const days = Math.round(
|
||||
(date.getTime() - Date.now()) / (1000 * 60 * 60 * 24),
|
||||
);
|
||||
return relativeTimeFormat.format(days, "day");
|
||||
};
|
||||
|
||||
export const CommitTimestamp = ({
|
||||
date,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitTimestampProps) => {
|
||||
const [formatted, setFormatted] = useState("");
|
||||
|
||||
const updateFormatted = useCallback(() => {
|
||||
setFormatted(formatRelativeDate(date));
|
||||
}, [date]);
|
||||
|
||||
useEffect(() => {
|
||||
updateFormatted();
|
||||
}, [updateFormatted]);
|
||||
|
||||
return (
|
||||
<time
|
||||
className={cn("text-xs", className)}
|
||||
dateTime={date.toISOString()}
|
||||
{...props}
|
||||
>
|
||||
{children ?? formatted}
|
||||
</time>
|
||||
);
|
||||
};
|
||||
|
||||
export type CommitActionsProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
const handleActionsClick = (e: React.MouseEvent) => e.stopPropagation();
|
||||
const handleActionsKeyDown = (e: React.KeyboardEvent) => e.stopPropagation();
|
||||
|
||||
export const CommitActions = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitActionsProps) => (
|
||||
// biome-ignore lint/a11y/useSemanticElements: fieldset would break layout styling
|
||||
<div
|
||||
className={cn("flex items-center gap-1", className)}
|
||||
onClick={handleActionsClick}
|
||||
onKeyDown={handleActionsKeyDown}
|
||||
role="group"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type CommitCopyButtonProps = ComponentProps<typeof Button> & {
|
||||
hash: string;
|
||||
onCopy?: () => void;
|
||||
onError?: (error: Error) => void;
|
||||
timeout?: number;
|
||||
};
|
||||
|
||||
export const CommitCopyButton = ({
|
||||
hash,
|
||||
onCopy,
|
||||
onError,
|
||||
timeout = 2000,
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: CommitCopyButtonProps) => {
|
||||
const [isCopied, setIsCopied] = useState(false);
|
||||
const timeoutRef = useRef<number>(0);
|
||||
|
||||
const copyToClipboard = useCallback(async () => {
|
||||
if (typeof window === "undefined" || !navigator?.clipboard?.writeText) {
|
||||
onError?.(new Error("Clipboard API not available"));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!isCopied) {
|
||||
await navigator.clipboard.writeText(hash);
|
||||
setIsCopied(true);
|
||||
onCopy?.();
|
||||
timeoutRef.current = window.setTimeout(
|
||||
() => setIsCopied(false),
|
||||
timeout,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
onError?.(error as Error);
|
||||
}
|
||||
}, [hash, onCopy, onError, timeout, isCopied]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
window.clearTimeout(timeoutRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const Icon = isCopied ? CheckIcon : CopyIcon;
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn("size-7 shrink-0", className)}
|
||||
onClick={copyToClipboard}
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
{children ?? <Icon size={14} />}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export type CommitContentProps = ComponentProps<typeof CollapsibleContent>;
|
||||
|
||||
export const CommitContent = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitContentProps) => (
|
||||
<CollapsibleContent className={cn("border-t p-3", className)} {...props}>
|
||||
{children}
|
||||
</CollapsibleContent>
|
||||
);
|
||||
|
||||
export type CommitFilesProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const CommitFiles = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitFilesProps) => (
|
||||
<div className={cn("space-y-1", className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type CommitFileProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const CommitFile = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitFileProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-2 rounded px-2 py-1 text-sm hover:bg-muted/50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type CommitFileInfoProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const CommitFileInfo = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitFileInfoProps) => (
|
||||
<div className={cn("flex min-w-0 items-center gap-2", className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
const fileStatusStyles = {
|
||||
added: "text-green-600 dark:text-green-400",
|
||||
deleted: "text-red-600 dark:text-red-400",
|
||||
modified: "text-yellow-600 dark:text-yellow-400",
|
||||
renamed: "text-blue-600 dark:text-blue-400",
|
||||
};
|
||||
|
||||
const fileStatusLabels = {
|
||||
added: "A",
|
||||
deleted: "D",
|
||||
modified: "M",
|
||||
renamed: "R",
|
||||
};
|
||||
|
||||
export type CommitFileStatusProps = HTMLAttributes<HTMLSpanElement> & {
|
||||
status: "added" | "modified" | "deleted" | "renamed";
|
||||
};
|
||||
|
||||
export const CommitFileStatus = ({
|
||||
status,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitFileStatusProps) => (
|
||||
<span
|
||||
className={cn(
|
||||
"font-medium font-mono text-xs",
|
||||
fileStatusStyles[status],
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? fileStatusLabels[status]}
|
||||
</span>
|
||||
);
|
||||
|
||||
export type CommitFileIconProps = ComponentProps<typeof FileIcon>;
|
||||
|
||||
export const CommitFileIcon = ({
|
||||
className,
|
||||
...props
|
||||
}: CommitFileIconProps) => (
|
||||
<FileIcon
|
||||
className={cn("size-3.5 shrink-0 text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type CommitFilePathProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const CommitFilePath = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitFilePathProps) => (
|
||||
<span className={cn("truncate font-mono text-xs", className)} {...props}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
|
||||
export type CommitFileChangesProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const CommitFileChanges = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitFileChangesProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex shrink-0 items-center gap-1 font-mono text-xs",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type CommitFileAdditionsProps = HTMLAttributes<HTMLSpanElement> & {
|
||||
count: number;
|
||||
};
|
||||
|
||||
export const CommitFileAdditions = ({
|
||||
count,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitFileAdditionsProps) => {
|
||||
if (count <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn("text-green-600 dark:text-green-400", className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? (
|
||||
<>
|
||||
<PlusIcon className="inline-block size-3" />
|
||||
{count}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
export type CommitFileDeletionsProps = HTMLAttributes<HTMLSpanElement> & {
|
||||
count: number;
|
||||
};
|
||||
|
||||
export const CommitFileDeletions = ({
|
||||
count,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CommitFileDeletionsProps) => {
|
||||
if (count <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn("text-red-600 dark:text-red-400", className)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? (
|
||||
<>
|
||||
<MinusIcon className="inline-block size-3" />
|
||||
{count}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
@@ -1,174 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { ToolUIPart } from "ai";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { createContext, useContext, useMemo } from "react";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type ToolUIPartApproval =
|
||||
| {
|
||||
id: string;
|
||||
approved?: never;
|
||||
reason?: never;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
approved: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
approved: true;
|
||||
reason?: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
approved: true;
|
||||
reason?: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
approved: false;
|
||||
reason?: string;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
interface ConfirmationContextValue {
|
||||
approval: ToolUIPartApproval;
|
||||
state: ToolUIPart["state"];
|
||||
}
|
||||
|
||||
const ConfirmationContext = createContext<ConfirmationContextValue | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const useConfirmation = () => {
|
||||
const context = useContext(ConfirmationContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error("Confirmation components must be used within Confirmation");
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
export type ConfirmationProps = ComponentProps<typeof Alert> & {
|
||||
approval?: ToolUIPartApproval;
|
||||
state: ToolUIPart["state"];
|
||||
};
|
||||
|
||||
export const Confirmation = ({
|
||||
className,
|
||||
approval,
|
||||
state,
|
||||
...props
|
||||
}: ConfirmationProps) => {
|
||||
const contextValue = useMemo(() => ({ approval, state }), [approval, state]);
|
||||
|
||||
if (!approval || state === "input-streaming" || state === "input-available") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<ConfirmationContext.Provider value={contextValue}>
|
||||
<Alert className={cn("flex flex-col gap-2", className)} {...props} />
|
||||
</ConfirmationContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type ConfirmationTitleProps = ComponentProps<typeof AlertDescription>;
|
||||
|
||||
export const ConfirmationTitle = ({
|
||||
className,
|
||||
...props
|
||||
}: ConfirmationTitleProps) => (
|
||||
<AlertDescription className={cn("inline", className)} {...props} />
|
||||
);
|
||||
|
||||
export interface ConfirmationRequestProps {
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
export const ConfirmationRequest = ({ children }: ConfirmationRequestProps) => {
|
||||
const { state } = useConfirmation();
|
||||
|
||||
// Only show when approval is requested
|
||||
if (state !== "approval-requested") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return children;
|
||||
};
|
||||
|
||||
export interface ConfirmationAcceptedProps {
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
export const ConfirmationAccepted = ({
|
||||
children,
|
||||
}: ConfirmationAcceptedProps) => {
|
||||
const { approval, state } = useConfirmation();
|
||||
|
||||
// Only show when approved and in response states
|
||||
if (
|
||||
!approval?.approved ||
|
||||
(state !== "approval-responded" &&
|
||||
state !== "output-denied" &&
|
||||
state !== "output-available")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return children;
|
||||
};
|
||||
|
||||
export interface ConfirmationRejectedProps {
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
export const ConfirmationRejected = ({
|
||||
children,
|
||||
}: ConfirmationRejectedProps) => {
|
||||
const { approval, state } = useConfirmation();
|
||||
|
||||
// Only show when rejected and in response states
|
||||
if (
|
||||
approval?.approved !== false ||
|
||||
(state !== "approval-responded" &&
|
||||
state !== "output-denied" &&
|
||||
state !== "output-available")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return children;
|
||||
};
|
||||
|
||||
export type ConfirmationActionsProps = ComponentProps<"div">;
|
||||
|
||||
export const ConfirmationActions = ({
|
||||
className,
|
||||
...props
|
||||
}: ConfirmationActionsProps) => {
|
||||
const { state } = useConfirmation();
|
||||
|
||||
// Only show when approval is requested
|
||||
if (state !== "approval-requested") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn("flex items-center justify-end gap-2 self-end", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export type ConfirmationActionProps = ComponentProps<typeof Button>;
|
||||
|
||||
export const ConfirmationAction = (props: ConfirmationActionProps) => (
|
||||
<Button className="h-8 px-3 text-sm" type="button" {...props} />
|
||||
);
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { ConnectionLineComponent } from "@xyflow/react";
|
||||
|
||||
const HALF = 0.5;
|
||||
|
||||
export const Connection: ConnectionLineComponent = ({
|
||||
fromX,
|
||||
fromY,
|
||||
toX,
|
||||
toY,
|
||||
}) => (
|
||||
<g>
|
||||
<path
|
||||
className="animated"
|
||||
d={`M${fromX},${fromY} C ${fromX + (toX - fromX) * HALF},${fromY} ${fromX + (toX - fromX) * HALF},${toY} ${toX},${toY}`}
|
||||
fill="none"
|
||||
stroke="var(--color-ring)"
|
||||
strokeWidth={1}
|
||||
/>
|
||||
<circle
|
||||
cx={toX}
|
||||
cy={toY}
|
||||
fill="#fff"
|
||||
r={3}
|
||||
stroke="var(--color-ring)"
|
||||
strokeWidth={1}
|
||||
/>
|
||||
</g>
|
||||
);
|
||||
@@ -1,409 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { LanguageModelUsage } from "ai";
|
||||
import type { ComponentProps } from "react";
|
||||
import { createContext, useContext, useMemo } from "react";
|
||||
import { getUsage } from "tokenlens";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
HoverCard,
|
||||
HoverCardContent,
|
||||
HoverCardTrigger,
|
||||
} from "@/components/ui/hover-card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const PERCENT_MAX = 100;
|
||||
const ICON_RADIUS = 10;
|
||||
const ICON_VIEWBOX = 24;
|
||||
const ICON_CENTER = 12;
|
||||
const ICON_STROKE_WIDTH = 2;
|
||||
|
||||
type ModelId = string;
|
||||
|
||||
interface ContextSchema {
|
||||
usedTokens: number;
|
||||
maxTokens: number;
|
||||
usage?: LanguageModelUsage;
|
||||
modelId?: ModelId;
|
||||
}
|
||||
|
||||
const ContextContext = createContext<ContextSchema | null>(null);
|
||||
|
||||
const useContextValue = () => {
|
||||
const context = useContext(ContextContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error("Context components must be used within Context");
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
export type ContextProps = ComponentProps<typeof HoverCard> & ContextSchema;
|
||||
|
||||
export const Context = ({
|
||||
usedTokens,
|
||||
maxTokens,
|
||||
usage,
|
||||
modelId,
|
||||
...props
|
||||
}: ContextProps) => {
|
||||
const contextValue = useMemo(
|
||||
() => ({ maxTokens, modelId, usage, usedTokens }),
|
||||
[maxTokens, modelId, usage, usedTokens],
|
||||
);
|
||||
|
||||
return (
|
||||
<ContextContext.Provider value={contextValue}>
|
||||
<HoverCard closeDelay={0} openDelay={0} {...props} />
|
||||
</ContextContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
const ContextIcon = () => {
|
||||
const { usedTokens, maxTokens } = useContextValue();
|
||||
const circumference = 2 * Math.PI * ICON_RADIUS;
|
||||
const usedPercent = usedTokens / maxTokens;
|
||||
const dashOffset = circumference * (1 - usedPercent);
|
||||
|
||||
return (
|
||||
<svg
|
||||
aria-label="Model context usage"
|
||||
height="20"
|
||||
role="img"
|
||||
style={{ color: "currentcolor" }}
|
||||
viewBox={`0 0 ${ICON_VIEWBOX} ${ICON_VIEWBOX}`}
|
||||
width="20"
|
||||
>
|
||||
<circle
|
||||
cx={ICON_CENTER}
|
||||
cy={ICON_CENTER}
|
||||
fill="none"
|
||||
opacity="0.25"
|
||||
r={ICON_RADIUS}
|
||||
stroke="currentColor"
|
||||
strokeWidth={ICON_STROKE_WIDTH}
|
||||
/>
|
||||
<circle
|
||||
cx={ICON_CENTER}
|
||||
cy={ICON_CENTER}
|
||||
fill="none"
|
||||
opacity="0.7"
|
||||
r={ICON_RADIUS}
|
||||
stroke="currentColor"
|
||||
strokeDasharray={`${circumference} ${circumference}`}
|
||||
strokeDashoffset={dashOffset}
|
||||
strokeLinecap="round"
|
||||
strokeWidth={ICON_STROKE_WIDTH}
|
||||
style={{ transform: "rotate(-90deg)", transformOrigin: "center" }}
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
export type ContextTriggerProps = ComponentProps<typeof Button>;
|
||||
|
||||
export const ContextTrigger = ({ children, ...props }: ContextTriggerProps) => {
|
||||
const { usedTokens, maxTokens } = useContextValue();
|
||||
const usedPercent = usedTokens / maxTokens;
|
||||
const renderedPercent = new Intl.NumberFormat("en-US", {
|
||||
maximumFractionDigits: 1,
|
||||
style: "percent",
|
||||
}).format(usedPercent);
|
||||
|
||||
return (
|
||||
<HoverCardTrigger>
|
||||
{children ?? (
|
||||
<Button type="button" variant="ghost" {...props}>
|
||||
<span className="font-medium text-muted-foreground">
|
||||
{renderedPercent}
|
||||
</span>
|
||||
<ContextIcon />
|
||||
</Button>
|
||||
)}
|
||||
</HoverCardTrigger>
|
||||
);
|
||||
};
|
||||
|
||||
export type ContextContentProps = ComponentProps<typeof HoverCardContent>;
|
||||
|
||||
export const ContextContent = ({
|
||||
className,
|
||||
...props
|
||||
}: ContextContentProps) => (
|
||||
<HoverCardContent
|
||||
className={cn("min-w-60 divide-y overflow-hidden p-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ContextContentHeaderProps = ComponentProps<"div">;
|
||||
|
||||
export const ContextContentHeader = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: ContextContentHeaderProps) => {
|
||||
const { usedTokens, maxTokens } = useContextValue();
|
||||
const usedPercent = usedTokens / maxTokens;
|
||||
const displayPct = new Intl.NumberFormat("en-US", {
|
||||
maximumFractionDigits: 1,
|
||||
style: "percent",
|
||||
}).format(usedPercent);
|
||||
const used = new Intl.NumberFormat("en-US", {
|
||||
notation: "compact",
|
||||
}).format(usedTokens);
|
||||
const total = new Intl.NumberFormat("en-US", {
|
||||
notation: "compact",
|
||||
}).format(maxTokens);
|
||||
|
||||
return (
|
||||
<div className={cn("w-full space-y-2 p-3", className)} {...props}>
|
||||
{children ?? (
|
||||
<>
|
||||
<div className="flex items-center justify-between gap-3 text-xs">
|
||||
<p>{displayPct}</p>
|
||||
<p className="font-mono text-muted-foreground">
|
||||
{used} / {total}
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Progress className="bg-muted" value={usedPercent * PERCENT_MAX} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export type ContextContentBodyProps = ComponentProps<"div">;
|
||||
|
||||
export const ContextContentBody = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: ContextContentBodyProps) => (
|
||||
<div className={cn("w-full p-3", className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type ContextContentFooterProps = ComponentProps<"div">;
|
||||
|
||||
export const ContextContentFooter = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: ContextContentFooterProps) => {
|
||||
const { modelId, usage } = useContextValue();
|
||||
const costUSD = modelId
|
||||
? getUsage({
|
||||
modelId,
|
||||
usage: {
|
||||
input: usage?.inputTokens ?? 0,
|
||||
output: usage?.outputTokens ?? 0,
|
||||
},
|
||||
}).costUSD?.totalUSD
|
||||
: undefined;
|
||||
const totalCost = new Intl.NumberFormat("en-US", {
|
||||
currency: "USD",
|
||||
style: "currency",
|
||||
}).format(costUSD ?? 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex w-full items-center justify-between gap-3 bg-secondary p-3 text-xs",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? (
|
||||
<>
|
||||
<span className="text-muted-foreground">Total cost</span>
|
||||
<span>{totalCost}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const TokensWithCost = ({
|
||||
tokens,
|
||||
costText,
|
||||
}: {
|
||||
tokens?: number;
|
||||
costText?: string;
|
||||
}) => (
|
||||
<span>
|
||||
{tokens === undefined
|
||||
? "—"
|
||||
: new Intl.NumberFormat("en-US", {
|
||||
notation: "compact",
|
||||
}).format(tokens)}
|
||||
{costText ? (
|
||||
<span className="ml-2 text-muted-foreground">• {costText}</span>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
|
||||
export type ContextInputUsageProps = ComponentProps<"div">;
|
||||
|
||||
export const ContextInputUsage = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: ContextInputUsageProps) => {
|
||||
const { usage, modelId } = useContextValue();
|
||||
const inputTokens = usage?.inputTokens ?? 0;
|
||||
|
||||
if (children) {
|
||||
return children;
|
||||
}
|
||||
|
||||
if (!inputTokens) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const inputCost = modelId
|
||||
? getUsage({
|
||||
modelId,
|
||||
usage: { input: inputTokens, output: 0 },
|
||||
}).costUSD?.totalUSD
|
||||
: undefined;
|
||||
const inputCostText = new Intl.NumberFormat("en-US", {
|
||||
currency: "USD",
|
||||
style: "currency",
|
||||
}).format(inputCost ?? 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn("flex items-center justify-between text-xs", className)}
|
||||
{...props}
|
||||
>
|
||||
<span className="text-muted-foreground">Input</span>
|
||||
<TokensWithCost costText={inputCostText} tokens={inputTokens} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export type ContextOutputUsageProps = ComponentProps<"div">;
|
||||
|
||||
export const ContextOutputUsage = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: ContextOutputUsageProps) => {
|
||||
const { usage, modelId } = useContextValue();
|
||||
const outputTokens = usage?.outputTokens ?? 0;
|
||||
|
||||
if (children) {
|
||||
return children;
|
||||
}
|
||||
|
||||
if (!outputTokens) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const outputCost = modelId
|
||||
? getUsage({
|
||||
modelId,
|
||||
usage: { input: 0, output: outputTokens },
|
||||
}).costUSD?.totalUSD
|
||||
: undefined;
|
||||
const outputCostText = new Intl.NumberFormat("en-US", {
|
||||
currency: "USD",
|
||||
style: "currency",
|
||||
}).format(outputCost ?? 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn("flex items-center justify-between text-xs", className)}
|
||||
{...props}
|
||||
>
|
||||
<span className="text-muted-foreground">Output</span>
|
||||
<TokensWithCost costText={outputCostText} tokens={outputTokens} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export type ContextReasoningUsageProps = ComponentProps<"div">;
|
||||
|
||||
export const ContextReasoningUsage = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: ContextReasoningUsageProps) => {
|
||||
const { usage, modelId } = useContextValue();
|
||||
const reasoningTokens = usage?.outputTokenDetails?.reasoningTokens ?? 0;
|
||||
|
||||
if (children) {
|
||||
return children;
|
||||
}
|
||||
|
||||
if (!reasoningTokens) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const reasoningCost = modelId
|
||||
? getUsage({
|
||||
modelId,
|
||||
usage: { reasoningTokens },
|
||||
}).costUSD?.totalUSD
|
||||
: undefined;
|
||||
const reasoningCostText = new Intl.NumberFormat("en-US", {
|
||||
currency: "USD",
|
||||
style: "currency",
|
||||
}).format(reasoningCost ?? 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn("flex items-center justify-between text-xs", className)}
|
||||
{...props}
|
||||
>
|
||||
<span className="text-muted-foreground">Reasoning</span>
|
||||
<TokensWithCost costText={reasoningCostText} tokens={reasoningTokens} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export type ContextCacheUsageProps = ComponentProps<"div">;
|
||||
|
||||
export const ContextCacheUsage = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: ContextCacheUsageProps) => {
|
||||
const { usage, modelId } = useContextValue();
|
||||
const cacheTokens = usage?.inputTokenDetails?.cacheReadTokens ?? 0;
|
||||
|
||||
if (children) {
|
||||
return children;
|
||||
}
|
||||
|
||||
if (!cacheTokens) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cacheCost = modelId
|
||||
? getUsage({
|
||||
modelId,
|
||||
usage: { cacheReads: cacheTokens, input: 0, output: 0 },
|
||||
}).costUSD?.totalUSD
|
||||
: undefined;
|
||||
const cacheCostText = new Intl.NumberFormat("en-US", {
|
||||
currency: "USD",
|
||||
style: "currency",
|
||||
}).format(cacheCost ?? 0);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn("flex items-center justify-between text-xs", className)}
|
||||
{...props}
|
||||
>
|
||||
<span className="text-muted-foreground">Cache</span>
|
||||
<TokensWithCost costText={cacheCostText} tokens={cacheTokens} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,18 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Controls as ControlsPrimitive } from "@xyflow/react";
|
||||
import type { ComponentProps } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ControlsProps = ComponentProps<typeof ControlsPrimitive>;
|
||||
|
||||
export const Controls = ({ className, ...props }: ControlsProps) => (
|
||||
<ControlsPrimitive
|
||||
className={cn(
|
||||
"gap-px overflow-hidden rounded-md border bg-card p-1 shadow-none!",
|
||||
"[&>button]:rounded-md [&>button]:border-none! [&>button]:bg-transparent! [&>button]:hover:bg-secondary!",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
@@ -1,168 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { UIMessage } from "ai";
|
||||
import { ArrowDownIcon, DownloadIcon } from "lucide-react";
|
||||
import type { ComponentProps } from "react";
|
||||
import { useCallback } from "react";
|
||||
import { StickToBottom, useStickToBottomContext } from "use-stick-to-bottom";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ConversationProps = ComponentProps<typeof StickToBottom>;
|
||||
|
||||
export const Conversation = ({ className, ...props }: ConversationProps) => (
|
||||
<StickToBottom
|
||||
className={cn("relative flex-1 overflow-y-hidden", className)}
|
||||
initial="smooth"
|
||||
resize="smooth"
|
||||
role="log"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ConversationContentProps = ComponentProps<
|
||||
typeof StickToBottom.Content
|
||||
>;
|
||||
|
||||
export const ConversationContent = ({
|
||||
className,
|
||||
...props
|
||||
}: ConversationContentProps) => (
|
||||
<StickToBottom.Content
|
||||
className={cn("flex flex-col gap-8 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ConversationEmptyStateProps = ComponentProps<"div"> & {
|
||||
title?: string;
|
||||
description?: string;
|
||||
icon?: React.ReactNode;
|
||||
};
|
||||
|
||||
export const ConversationEmptyState = ({
|
||||
className,
|
||||
title = "No messages yet",
|
||||
description = "Start a conversation to see messages here",
|
||||
icon,
|
||||
children,
|
||||
...props
|
||||
}: ConversationEmptyStateProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex size-full flex-col items-center justify-center gap-3 p-8 text-center",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? (
|
||||
<>
|
||||
{icon && <div className="text-muted-foreground">{icon}</div>}
|
||||
<div className="space-y-1">
|
||||
<h3 className="font-medium text-sm">{title}</h3>
|
||||
{description && (
|
||||
<p className="text-muted-foreground text-sm">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type ConversationScrollButtonProps = ComponentProps<typeof Button>;
|
||||
|
||||
export const ConversationScrollButton = ({
|
||||
className,
|
||||
...props
|
||||
}: ConversationScrollButtonProps) => {
|
||||
const { isAtBottom, scrollToBottom } = useStickToBottomContext();
|
||||
|
||||
const handleScrollToBottom = useCallback(() => {
|
||||
scrollToBottom();
|
||||
}, [scrollToBottom]);
|
||||
|
||||
return (
|
||||
!isAtBottom && (
|
||||
<Button
|
||||
className={cn(
|
||||
"absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full dark:bg-background dark:hover:bg-muted",
|
||||
className,
|
||||
)}
|
||||
onClick={handleScrollToBottom}
|
||||
size="icon"
|
||||
type="button"
|
||||
variant="outline"
|
||||
{...props}
|
||||
>
|
||||
<ArrowDownIcon className="size-4" />
|
||||
</Button>
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const getMessageText = (message: UIMessage): string =>
|
||||
message.parts
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.join("");
|
||||
|
||||
export type ConversationDownloadProps = Omit<
|
||||
ComponentProps<typeof Button>,
|
||||
"onClick"
|
||||
> & {
|
||||
messages: UIMessage[];
|
||||
filename?: string;
|
||||
formatMessage?: (message: UIMessage, index: number) => string;
|
||||
};
|
||||
|
||||
const defaultFormatMessage = (message: UIMessage): string => {
|
||||
const roleLabel =
|
||||
message.role.charAt(0).toUpperCase() + message.role.slice(1);
|
||||
return `**${roleLabel}:** ${getMessageText(message)}`;
|
||||
};
|
||||
|
||||
export const messagesToMarkdown = (
|
||||
messages: UIMessage[],
|
||||
formatMessage: (
|
||||
message: UIMessage,
|
||||
index: number,
|
||||
) => string = defaultFormatMessage,
|
||||
): string => messages.map((msg, i) => formatMessage(msg, i)).join("\n\n");
|
||||
|
||||
export const ConversationDownload = ({
|
||||
messages,
|
||||
filename = "conversation.md",
|
||||
formatMessage = defaultFormatMessage,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: ConversationDownloadProps) => {
|
||||
const handleDownload = useCallback(() => {
|
||||
const markdown = messagesToMarkdown(messages, formatMessage);
|
||||
const blob = new Blob([markdown], { type: "text/markdown" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
}, [messages, filename, formatMessage]);
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn(
|
||||
"absolute top-4 right-4 rounded-full dark:bg-background dark:hover:bg-muted",
|
||||
className,
|
||||
)}
|
||||
onClick={handleDownload}
|
||||
size="icon"
|
||||
type="button"
|
||||
variant="outline"
|
||||
{...props}
|
||||
>
|
||||
{children ?? <DownloadIcon className="size-4" />}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
@@ -1,143 +0,0 @@
|
||||
import type { EdgeProps, InternalNode, Node } from "@xyflow/react";
|
||||
import {
|
||||
BaseEdge,
|
||||
getBezierPath,
|
||||
getSimpleBezierPath,
|
||||
Position,
|
||||
useInternalNode,
|
||||
} from "@xyflow/react";
|
||||
|
||||
const Temporary = ({
|
||||
id,
|
||||
sourceX,
|
||||
sourceY,
|
||||
targetX,
|
||||
targetY,
|
||||
sourcePosition,
|
||||
targetPosition,
|
||||
}: EdgeProps) => {
|
||||
const [edgePath] = getSimpleBezierPath({
|
||||
sourcePosition,
|
||||
sourceX,
|
||||
sourceY,
|
||||
targetPosition,
|
||||
targetX,
|
||||
targetY,
|
||||
});
|
||||
|
||||
return (
|
||||
<BaseEdge
|
||||
className="stroke-1 stroke-ring"
|
||||
id={id}
|
||||
path={edgePath}
|
||||
style={{
|
||||
strokeDasharray: "5, 5",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const getHandleCoordsByPosition = (
|
||||
node: InternalNode<Node>,
|
||||
handlePosition: Position,
|
||||
) => {
|
||||
// Choose the handle type based on position - Left is for target, Right is for source
|
||||
const handleType = handlePosition === Position.Left ? "target" : "source";
|
||||
|
||||
const handle = node.internals.handleBounds?.[handleType]?.find(
|
||||
(h) => h.position === handlePosition,
|
||||
);
|
||||
|
||||
if (!handle) {
|
||||
return [0, 0] as const;
|
||||
}
|
||||
|
||||
let offsetX = handle.width / 2;
|
||||
let offsetY = handle.height / 2;
|
||||
|
||||
// this is a tiny detail to make the markerEnd of an edge visible.
|
||||
// The handle position that gets calculated has the origin top-left, so depending which side we are using, we add a little offset
|
||||
// when the handlePosition is Position.Right for example, we need to add an offset as big as the handle itself in order to get the correct position
|
||||
switch (handlePosition) {
|
||||
case Position.Left: {
|
||||
offsetX = 0;
|
||||
break;
|
||||
}
|
||||
case Position.Right: {
|
||||
offsetX = handle.width;
|
||||
break;
|
||||
}
|
||||
case Position.Top: {
|
||||
offsetY = 0;
|
||||
break;
|
||||
}
|
||||
case Position.Bottom: {
|
||||
offsetY = handle.height;
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
throw new Error(`Invalid handle position: ${handlePosition}`);
|
||||
}
|
||||
}
|
||||
|
||||
const x = node.internals.positionAbsolute.x + handle.x + offsetX;
|
||||
const y = node.internals.positionAbsolute.y + handle.y + offsetY;
|
||||
|
||||
return [x, y] as const;
|
||||
};
|
||||
|
||||
const getEdgeParams = (
|
||||
source: InternalNode<Node>,
|
||||
target: InternalNode<Node>,
|
||||
) => {
|
||||
const sourcePos = Position.Right;
|
||||
const [sx, sy] = getHandleCoordsByPosition(source, sourcePos);
|
||||
const targetPos = Position.Left;
|
||||
const [tx, ty] = getHandleCoordsByPosition(target, targetPos);
|
||||
|
||||
return {
|
||||
sourcePos,
|
||||
sx,
|
||||
sy,
|
||||
targetPos,
|
||||
tx,
|
||||
ty,
|
||||
};
|
||||
};
|
||||
|
||||
const Animated = ({ id, source, target, markerEnd, style }: EdgeProps) => {
|
||||
const sourceNode = useInternalNode(source);
|
||||
const targetNode = useInternalNode(target);
|
||||
|
||||
if (!(sourceNode && targetNode)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { sx, sy, tx, ty, sourcePos, targetPos } = getEdgeParams(
|
||||
sourceNode,
|
||||
targetNode,
|
||||
);
|
||||
|
||||
const [edgePath] = getBezierPath({
|
||||
sourcePosition: sourcePos,
|
||||
sourceX: sx,
|
||||
sourceY: sy,
|
||||
targetPosition: targetPos,
|
||||
targetX: tx,
|
||||
targetY: ty,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<BaseEdge id={id} markerEnd={markerEnd} path={edgePath} style={style} />
|
||||
<circle fill="var(--primary)" r="4">
|
||||
<animateMotion dur="2s" path={edgePath} repeatCount="indefinite" />
|
||||
</circle>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export const Edge = {
|
||||
Animated,
|
||||
Temporary,
|
||||
};
|
||||
@@ -1,324 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { CheckIcon, CopyIcon, EyeIcon, EyeOffIcon } from "lucide-react";
|
||||
import type { ComponentProps, HTMLAttributes } from "react";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface EnvironmentVariablesContextType {
|
||||
showValues: boolean;
|
||||
setShowValues: (show: boolean) => void;
|
||||
}
|
||||
|
||||
// Default noop for context default value
|
||||
// oxlint-disable-next-line eslint(no-empty-function)
|
||||
const noop = () => {};
|
||||
|
||||
const EnvironmentVariablesContext =
|
||||
createContext<EnvironmentVariablesContextType>({
|
||||
setShowValues: noop,
|
||||
showValues: false,
|
||||
});
|
||||
|
||||
export type EnvironmentVariablesProps = HTMLAttributes<HTMLDivElement> & {
|
||||
showValues?: boolean;
|
||||
defaultShowValues?: boolean;
|
||||
onShowValuesChange?: (show: boolean) => void;
|
||||
};
|
||||
|
||||
export const EnvironmentVariables = ({
|
||||
showValues: controlledShowValues,
|
||||
defaultShowValues = false,
|
||||
onShowValuesChange,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: EnvironmentVariablesProps) => {
|
||||
const [internalShowValues, setInternalShowValues] =
|
||||
useState(defaultShowValues);
|
||||
const showValues = controlledShowValues ?? internalShowValues;
|
||||
|
||||
const setShowValues = useCallback(
|
||||
(show: boolean) => {
|
||||
setInternalShowValues(show);
|
||||
onShowValuesChange?.(show);
|
||||
},
|
||||
[onShowValuesChange],
|
||||
);
|
||||
|
||||
const contextValue = useMemo(
|
||||
() => ({ setShowValues, showValues }),
|
||||
[setShowValues, showValues],
|
||||
);
|
||||
|
||||
return (
|
||||
<EnvironmentVariablesContext.Provider value={contextValue}>
|
||||
<div
|
||||
className={cn("rounded-lg border bg-background", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</EnvironmentVariablesContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type EnvironmentVariablesHeaderProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const EnvironmentVariablesHeader = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: EnvironmentVariablesHeaderProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between border-b px-4 py-3",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type EnvironmentVariablesTitleProps = HTMLAttributes<HTMLHeadingElement>;
|
||||
|
||||
export const EnvironmentVariablesTitle = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: EnvironmentVariablesTitleProps) => (
|
||||
<h3 className={cn("font-medium text-sm", className)} {...props}>
|
||||
{children ?? "Environment Variables"}
|
||||
</h3>
|
||||
);
|
||||
|
||||
export type EnvironmentVariablesToggleProps = ComponentProps<typeof Switch>;
|
||||
|
||||
export const EnvironmentVariablesToggle = ({
|
||||
className,
|
||||
...props
|
||||
}: EnvironmentVariablesToggleProps) => {
|
||||
const { showValues, setShowValues } = useContext(EnvironmentVariablesContext);
|
||||
|
||||
return (
|
||||
<div className={cn("flex items-center gap-2", className)}>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{showValues ? <EyeIcon size={14} /> : <EyeOffIcon size={14} />}
|
||||
</span>
|
||||
<Switch
|
||||
aria-label="Toggle value visibility"
|
||||
checked={showValues}
|
||||
onCheckedChange={setShowValues}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export type EnvironmentVariablesContentProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const EnvironmentVariablesContent = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: EnvironmentVariablesContentProps) => (
|
||||
<div className={cn("divide-y", className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
interface EnvironmentVariableContextType {
|
||||
name: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
const EnvironmentVariableContext =
|
||||
createContext<EnvironmentVariableContextType>({
|
||||
name: "",
|
||||
value: "",
|
||||
});
|
||||
|
||||
export type EnvironmentVariableGroupProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const EnvironmentVariableGroup = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: EnvironmentVariableGroupProps) => (
|
||||
<div className={cn("flex items-center gap-2", className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type EnvironmentVariableNameProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const EnvironmentVariableName = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: EnvironmentVariableNameProps) => {
|
||||
const { name } = useContext(EnvironmentVariableContext);
|
||||
|
||||
return (
|
||||
<span className={cn("font-mono text-sm", className)} {...props}>
|
||||
{children ?? name}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
export type EnvironmentVariableValueProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const EnvironmentVariableValue = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: EnvironmentVariableValueProps) => {
|
||||
const { value } = useContext(EnvironmentVariableContext);
|
||||
const { showValues } = useContext(EnvironmentVariablesContext);
|
||||
|
||||
const displayValue = showValues
|
||||
? value
|
||||
: "•".repeat(Math.min(value.length, 20));
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"font-mono text-muted-foreground text-sm",
|
||||
!showValues && "select-none",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? displayValue}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
export type EnvironmentVariableProps = HTMLAttributes<HTMLDivElement> & {
|
||||
name: string;
|
||||
value: string;
|
||||
};
|
||||
|
||||
export const EnvironmentVariable = ({
|
||||
name,
|
||||
value,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: EnvironmentVariableProps) => {
|
||||
const envVarContextValue = useMemo(() => ({ name, value }), [name, value]);
|
||||
|
||||
return (
|
||||
<EnvironmentVariableContext.Provider value={envVarContextValue}>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-4 px-4 py-3",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? (
|
||||
<>
|
||||
<div className="flex items-center gap-2">
|
||||
<EnvironmentVariableName />
|
||||
</div>
|
||||
<EnvironmentVariableValue />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</EnvironmentVariableContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type EnvironmentVariableCopyButtonProps = ComponentProps<
|
||||
typeof Button
|
||||
> & {
|
||||
onCopy?: () => void;
|
||||
onError?: (error: Error) => void;
|
||||
timeout?: number;
|
||||
copyFormat?: "name" | "value" | "export";
|
||||
};
|
||||
|
||||
export const EnvironmentVariableCopyButton = ({
|
||||
onCopy,
|
||||
onError,
|
||||
timeout = 2000,
|
||||
copyFormat = "value",
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: EnvironmentVariableCopyButtonProps) => {
|
||||
const [isCopied, setIsCopied] = useState(false);
|
||||
const timeoutRef = useRef<number>(0);
|
||||
const { name, value } = useContext(EnvironmentVariableContext);
|
||||
|
||||
const getTextToCopy = useCallback((): string => {
|
||||
const formatMap = {
|
||||
export: () => `export ${name}="${value}"`,
|
||||
name: () => name,
|
||||
value: () => value,
|
||||
};
|
||||
return formatMap[copyFormat]();
|
||||
}, [name, value, copyFormat]);
|
||||
|
||||
const copyToClipboard = useCallback(async () => {
|
||||
if (typeof window === "undefined" || !navigator?.clipboard?.writeText) {
|
||||
onError?.(new Error("Clipboard API not available"));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(getTextToCopy());
|
||||
setIsCopied(true);
|
||||
onCopy?.();
|
||||
timeoutRef.current = window.setTimeout(() => setIsCopied(false), timeout);
|
||||
} catch (error) {
|
||||
onError?.(error as Error);
|
||||
}
|
||||
}, [getTextToCopy, onCopy, onError, timeout]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
window.clearTimeout(timeoutRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const Icon = isCopied ? CheckIcon : CopyIcon;
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn("size-6 shrink-0", className)}
|
||||
onClick={copyToClipboard}
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
{children ?? <Icon size={12} />}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export type EnvironmentVariableRequiredProps = ComponentProps<typeof Badge>;
|
||||
|
||||
export const EnvironmentVariableRequired = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: EnvironmentVariableRequiredProps) => (
|
||||
<Badge className={cn("text-xs", className)} variant="secondary" {...props}>
|
||||
{children ?? "Required"}
|
||||
</Badge>
|
||||
);
|
||||
@@ -1,307 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ChevronRightIcon,
|
||||
FileIcon,
|
||||
FolderIcon,
|
||||
FolderOpenIcon,
|
||||
} from "lucide-react";
|
||||
import type { HTMLAttributes, ReactNode } from "react";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from "@/components/ui/collapsible";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface FileTreeContextType {
|
||||
expandedPaths: Set<string>;
|
||||
togglePath: (path: string) => void;
|
||||
selectedPath?: string;
|
||||
onSelect?: (path: string) => void;
|
||||
}
|
||||
|
||||
// Default noop for context default value
|
||||
// oxlint-disable-next-line eslint(no-empty-function)
|
||||
const noop = () => {};
|
||||
|
||||
const FileTreeContext = createContext<FileTreeContextType>({
|
||||
// oxlint-disable-next-line eslint-plugin-unicorn(no-new-builtin)
|
||||
expandedPaths: new Set(),
|
||||
togglePath: noop,
|
||||
});
|
||||
|
||||
export type FileTreeProps = Omit<HTMLAttributes<HTMLDivElement>, "onSelect"> & {
|
||||
expanded?: Set<string>;
|
||||
defaultExpanded?: Set<string>;
|
||||
selectedPath?: string;
|
||||
onSelect?: (path: string) => void;
|
||||
onExpandedChange?: (expanded: Set<string>) => void;
|
||||
};
|
||||
|
||||
export const FileTree = ({
|
||||
expanded: controlledExpanded,
|
||||
defaultExpanded = new Set(),
|
||||
selectedPath,
|
||||
onSelect,
|
||||
onExpandedChange,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: FileTreeProps) => {
|
||||
const [internalExpanded, setInternalExpanded] = useState(defaultExpanded);
|
||||
const expandedPaths = controlledExpanded ?? internalExpanded;
|
||||
|
||||
const togglePath = useCallback(
|
||||
(path: string) => {
|
||||
const newExpanded = new Set(expandedPaths);
|
||||
if (newExpanded.has(path)) {
|
||||
newExpanded.delete(path);
|
||||
} else {
|
||||
newExpanded.add(path);
|
||||
}
|
||||
setInternalExpanded(newExpanded);
|
||||
onExpandedChange?.(newExpanded);
|
||||
},
|
||||
[expandedPaths, onExpandedChange],
|
||||
);
|
||||
|
||||
const contextValue = useMemo(
|
||||
() => ({ expandedPaths, onSelect, selectedPath, togglePath }),
|
||||
[expandedPaths, onSelect, selectedPath, togglePath],
|
||||
);
|
||||
|
||||
return (
|
||||
<FileTreeContext.Provider value={contextValue}>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-lg border bg-background font-mono text-sm",
|
||||
className,
|
||||
)}
|
||||
role="tree"
|
||||
{...props}
|
||||
>
|
||||
<div className="p-2">{children}</div>
|
||||
</div>
|
||||
</FileTreeContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type FileTreeIconProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const FileTreeIcon = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: FileTreeIconProps) => (
|
||||
<span className={cn("shrink-0", className)} {...props}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
|
||||
export type FileTreeNameProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const FileTreeName = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: FileTreeNameProps) => (
|
||||
<span className={cn("truncate", className)} {...props}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
|
||||
interface FileTreeFolderContextType {
|
||||
path: string;
|
||||
name: string;
|
||||
isExpanded: boolean;
|
||||
}
|
||||
|
||||
const FileTreeFolderContext = createContext<FileTreeFolderContextType>({
|
||||
isExpanded: false,
|
||||
name: "",
|
||||
path: "",
|
||||
});
|
||||
|
||||
export type FileTreeFolderProps = HTMLAttributes<HTMLDivElement> & {
|
||||
path: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export const FileTreeFolder = ({
|
||||
path,
|
||||
name,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: FileTreeFolderProps) => {
|
||||
const { expandedPaths, togglePath, selectedPath, onSelect } =
|
||||
useContext(FileTreeContext);
|
||||
const isExpanded = expandedPaths.has(path);
|
||||
const isSelected = selectedPath === path;
|
||||
|
||||
const handleOpenChange = useCallback(() => {
|
||||
togglePath(path);
|
||||
}, [togglePath, path]);
|
||||
|
||||
const handleSelect = useCallback(() => {
|
||||
onSelect?.(path);
|
||||
}, [onSelect, path]);
|
||||
|
||||
const folderContextValue = useMemo(
|
||||
() => ({ isExpanded, name, path }),
|
||||
[isExpanded, name, path],
|
||||
);
|
||||
|
||||
return (
|
||||
<FileTreeFolderContext.Provider value={folderContextValue}>
|
||||
<Collapsible onOpenChange={handleOpenChange} open={isExpanded}>
|
||||
<div
|
||||
className={cn("", className)}
|
||||
role="treeitem"
|
||||
tabIndex={0}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex w-full items-center gap-1 rounded px-2 py-1 text-left transition-colors hover:bg-muted/50",
|
||||
isSelected && "bg-muted",
|
||||
)}
|
||||
>
|
||||
<CollapsibleTrigger
|
||||
render={
|
||||
<button
|
||||
className="flex shrink-0 cursor-pointer items-center border-none bg-transparent p-0"
|
||||
type="button"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
className={cn(
|
||||
"size-4 shrink-0 text-muted-foreground transition-transform",
|
||||
isExpanded && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
</CollapsibleTrigger>
|
||||
<button
|
||||
className="flex min-w-0 flex-1 cursor-pointer items-center gap-1 border-none bg-transparent p-0 text-left"
|
||||
onClick={handleSelect}
|
||||
type="button"
|
||||
>
|
||||
<FileTreeIcon>
|
||||
{isExpanded ? (
|
||||
<FolderOpenIcon className="size-4 text-blue-500" />
|
||||
) : (
|
||||
<FolderIcon className="size-4 text-blue-500" />
|
||||
)}
|
||||
</FileTreeIcon>
|
||||
<FileTreeName>{name}</FileTreeName>
|
||||
</button>
|
||||
</div>
|
||||
<CollapsibleContent>
|
||||
<div className="ml-4 border-l pl-2">{children}</div>
|
||||
</CollapsibleContent>
|
||||
</div>
|
||||
</Collapsible>
|
||||
</FileTreeFolderContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
interface FileTreeFileContextType {
|
||||
path: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
const FileTreeFileContext = createContext<FileTreeFileContextType>({
|
||||
name: "",
|
||||
path: "",
|
||||
});
|
||||
|
||||
export type FileTreeFileProps = HTMLAttributes<HTMLDivElement> & {
|
||||
path: string;
|
||||
name: string;
|
||||
icon?: ReactNode;
|
||||
};
|
||||
|
||||
export const FileTreeFile = ({
|
||||
path,
|
||||
name,
|
||||
icon,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: FileTreeFileProps) => {
|
||||
const { selectedPath, onSelect } = useContext(FileTreeContext);
|
||||
const isSelected = selectedPath === path;
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
onSelect?.(path);
|
||||
}, [onSelect, path]);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
onSelect?.(path);
|
||||
}
|
||||
},
|
||||
[onSelect, path],
|
||||
);
|
||||
|
||||
const fileContextValue = useMemo(() => ({ name, path }), [name, path]);
|
||||
|
||||
return (
|
||||
<FileTreeFileContext.Provider value={fileContextValue}>
|
||||
<div
|
||||
className={cn(
|
||||
"flex cursor-pointer items-center gap-1 rounded px-2 py-1 transition-colors hover:bg-muted/50",
|
||||
isSelected && "bg-muted",
|
||||
className,
|
||||
)}
|
||||
onClick={handleClick}
|
||||
onKeyDown={handleKeyDown}
|
||||
role="treeitem"
|
||||
tabIndex={0}
|
||||
{...props}
|
||||
>
|
||||
{children ?? (
|
||||
<>
|
||||
{/* Spacer for alignment */}
|
||||
<span className="size-4 shrink-0" />
|
||||
<FileTreeIcon>
|
||||
{icon ?? <FileIcon className="size-4 text-muted-foreground" />}
|
||||
</FileTreeIcon>
|
||||
<FileTreeName>{name}</FileTreeName>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</FileTreeFileContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type FileTreeActionsProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
const stopPropagation = (e: React.SyntheticEvent) => e.stopPropagation();
|
||||
|
||||
export const FileTreeActions = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: FileTreeActionsProps) => (
|
||||
// biome-ignore lint/a11y/useSemanticElements: fieldset would break layout styling
|
||||
<div
|
||||
className={cn("ml-auto flex items-center gap-1", className)}
|
||||
onClick={stopPropagation}
|
||||
onKeyDown={stopPropagation}
|
||||
role="group"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
@@ -1,24 +0,0 @@
|
||||
import type { Experimental_GeneratedImage } from "ai";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ImageProps = Experimental_GeneratedImage & {
|
||||
className?: string;
|
||||
alt?: string;
|
||||
};
|
||||
|
||||
export const Image = ({
|
||||
base64,
|
||||
uint8Array: _uint8Array,
|
||||
mediaType,
|
||||
...props
|
||||
}: ImageProps) => (
|
||||
<img
|
||||
{...props}
|
||||
alt={props.alt}
|
||||
className={cn(
|
||||
"h-auto max-w-full overflow-hidden rounded-md",
|
||||
props.className,
|
||||
)}
|
||||
src={`data:${mediaType};base64,${base64}`}
|
||||
/>
|
||||
);
|
||||
@@ -1,298 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react";
|
||||
import type { ComponentProps } from "react";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import type { CarouselApi } from "@/components/ui/carousel";
|
||||
import {
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
} from "@/components/ui/carousel";
|
||||
import {
|
||||
HoverCard,
|
||||
HoverCardContent,
|
||||
HoverCardTrigger,
|
||||
} from "@/components/ui/hover-card";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type InlineCitationProps = ComponentProps<"span">;
|
||||
|
||||
export const InlineCitation = ({
|
||||
className,
|
||||
...props
|
||||
}: InlineCitationProps) => (
|
||||
<span
|
||||
className={cn("group inline items-center gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type InlineCitationTextProps = ComponentProps<"span">;
|
||||
|
||||
export const InlineCitationText = ({
|
||||
className,
|
||||
...props
|
||||
}: InlineCitationTextProps) => (
|
||||
<span
|
||||
className={cn("transition-colors group-hover:bg-accent", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type InlineCitationCardProps = ComponentProps<typeof HoverCard>;
|
||||
|
||||
export const InlineCitationCard = (props: InlineCitationCardProps) => (
|
||||
<HoverCard closeDelay={0} openDelay={0} {...props} />
|
||||
);
|
||||
|
||||
export type InlineCitationCardTriggerProps = ComponentProps<typeof Badge> & {
|
||||
sources: string[];
|
||||
};
|
||||
|
||||
export const InlineCitationCardTrigger = ({
|
||||
sources,
|
||||
className,
|
||||
...props
|
||||
}: InlineCitationCardTriggerProps) => (
|
||||
<HoverCardTrigger
|
||||
render={
|
||||
<Badge
|
||||
className={cn("ml-1 rounded-full", className)}
|
||||
variant="secondary"
|
||||
{...props}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{sources[0] ? (
|
||||
<>
|
||||
{new URL(sources[0]).hostname}{" "}
|
||||
{sources.length > 1 && `+${sources.length - 1}`}
|
||||
</>
|
||||
) : (
|
||||
"unknown"
|
||||
)}
|
||||
</HoverCardTrigger>
|
||||
);
|
||||
|
||||
export type InlineCitationCardBodyProps = ComponentProps<"div">;
|
||||
|
||||
export const InlineCitationCardBody = ({
|
||||
className,
|
||||
...props
|
||||
}: InlineCitationCardBodyProps) => (
|
||||
<HoverCardContent className={cn("relative w-80 p-0", className)} {...props} />
|
||||
);
|
||||
|
||||
const CarouselApiContext = createContext<CarouselApi | undefined>(undefined);
|
||||
|
||||
const useCarouselApi = () => {
|
||||
const context = useContext(CarouselApiContext);
|
||||
return context;
|
||||
};
|
||||
|
||||
export type InlineCitationCarouselProps = ComponentProps<typeof Carousel>;
|
||||
|
||||
export const InlineCitationCarousel = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: InlineCitationCarouselProps) => {
|
||||
const [api, setApi] = useState<CarouselApi>();
|
||||
|
||||
return (
|
||||
<CarouselApiContext.Provider value={api}>
|
||||
<Carousel className={cn("w-full", className)} setApi={setApi} {...props}>
|
||||
{children}
|
||||
</Carousel>
|
||||
</CarouselApiContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type InlineCitationCarouselContentProps = ComponentProps<"div">;
|
||||
|
||||
export const InlineCitationCarouselContent = (
|
||||
props: InlineCitationCarouselContentProps,
|
||||
) => <CarouselContent {...props} />;
|
||||
|
||||
export type InlineCitationCarouselItemProps = ComponentProps<"div">;
|
||||
|
||||
export const InlineCitationCarouselItem = ({
|
||||
className,
|
||||
...props
|
||||
}: InlineCitationCarouselItemProps) => (
|
||||
<CarouselItem
|
||||
className={cn("w-full space-y-2 p-4 pl-8", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type InlineCitationCarouselHeaderProps = ComponentProps<"div">;
|
||||
|
||||
export const InlineCitationCarouselHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: InlineCitationCarouselHeaderProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center justify-between gap-2 rounded-t-md bg-secondary p-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type InlineCitationCarouselIndexProps = ComponentProps<"div">;
|
||||
|
||||
export const InlineCitationCarouselIndex = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: InlineCitationCarouselIndexProps) => {
|
||||
const api = useCarouselApi();
|
||||
const [current, setCurrent] = useState(0);
|
||||
const [count, setCount] = useState(0);
|
||||
|
||||
const syncState = useCallback(() => {
|
||||
if (!api) {
|
||||
return;
|
||||
}
|
||||
setCount(api.scrollSnapList().length);
|
||||
setCurrent(api.selectedScrollSnap() + 1);
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) {
|
||||
return;
|
||||
}
|
||||
|
||||
syncState();
|
||||
|
||||
api.on("select", syncState);
|
||||
|
||||
return () => {
|
||||
api.off("select", syncState);
|
||||
};
|
||||
}, [api, syncState]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-1 items-center justify-end px-3 py-1 text-muted-foreground text-xs",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children ?? `${current}/${count}`}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export type InlineCitationCarouselPrevProps = ComponentProps<"button">;
|
||||
|
||||
export const InlineCitationCarouselPrev = ({
|
||||
className,
|
||||
...props
|
||||
}: InlineCitationCarouselPrevProps) => {
|
||||
const api = useCarouselApi();
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
if (api) {
|
||||
api.scrollPrev();
|
||||
}
|
||||
}, [api]);
|
||||
|
||||
return (
|
||||
<button
|
||||
aria-label="Previous"
|
||||
className={cn("shrink-0", className)}
|
||||
onClick={handleClick}
|
||||
type="button"
|
||||
{...props}
|
||||
>
|
||||
<ArrowLeftIcon className="size-4 text-muted-foreground" />
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
export type InlineCitationCarouselNextProps = ComponentProps<"button">;
|
||||
|
||||
export const InlineCitationCarouselNext = ({
|
||||
className,
|
||||
...props
|
||||
}: InlineCitationCarouselNextProps) => {
|
||||
const api = useCarouselApi();
|
||||
|
||||
const handleClick = useCallback(() => {
|
||||
if (api) {
|
||||
api.scrollNext();
|
||||
}
|
||||
}, [api]);
|
||||
|
||||
return (
|
||||
<button
|
||||
aria-label="Next"
|
||||
className={cn("shrink-0", className)}
|
||||
onClick={handleClick}
|
||||
type="button"
|
||||
{...props}
|
||||
>
|
||||
<ArrowRightIcon className="size-4 text-muted-foreground" />
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
export type InlineCitationSourceProps = ComponentProps<"div"> & {
|
||||
title?: string;
|
||||
url?: string;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
export const InlineCitationSource = ({
|
||||
title,
|
||||
url,
|
||||
description,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: InlineCitationSourceProps) => (
|
||||
<div className={cn("space-y-1", className)} {...props}>
|
||||
{title && (
|
||||
<h4 className="truncate font-medium text-sm leading-tight">{title}</h4>
|
||||
)}
|
||||
{url && (
|
||||
<p className="truncate break-all text-muted-foreground text-xs">{url}</p>
|
||||
)}
|
||||
{description && (
|
||||
<p className="line-clamp-3 text-muted-foreground text-sm leading-relaxed">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type InlineCitationQuoteProps = ComponentProps<"blockquote">;
|
||||
|
||||
export const InlineCitationQuote = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: InlineCitationQuoteProps) => (
|
||||
<blockquote
|
||||
className={cn(
|
||||
"border-muted border-l-2 pl-3 text-muted-foreground text-sm italic",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</blockquote>
|
||||
);
|
||||
@@ -1,301 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { AlertCircle } from "lucide-react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import {
|
||||
createContext,
|
||||
memo,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import type { TProps as JsxParserProps } from "react-jsx-parser";
|
||||
import JsxParser from "react-jsx-parser";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface JSXPreviewContextValue {
|
||||
jsx: string;
|
||||
processedJsx: string;
|
||||
isStreaming: boolean;
|
||||
error: Error | null;
|
||||
setError: (error: Error | null) => void;
|
||||
setLastGoodJsx: (jsx: string) => void;
|
||||
components: JsxParserProps["components"];
|
||||
bindings: JsxParserProps["bindings"];
|
||||
onErrorProp?: (error: Error) => void;
|
||||
}
|
||||
|
||||
const JSXPreviewContext = createContext<JSXPreviewContextValue | null>(null);
|
||||
|
||||
const TAG_REGEX = /<\/?([a-zA-Z][a-zA-Z0-9]*)\s*([^>]*?)(\/)?>/;
|
||||
|
||||
export const useJSXPreview = () => {
|
||||
const context = useContext(JSXPreviewContext);
|
||||
if (!context) {
|
||||
throw new Error("JSXPreview components must be used within JSXPreview");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
const matchJsxTag = (code: string) => {
|
||||
if (code.trim() === "") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const match = code.match(TAG_REGEX);
|
||||
|
||||
if (!match || match.index === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [fullMatch, tagName, attributes, selfClosing] = match;
|
||||
|
||||
let type: "self-closing" | "closing" | "opening";
|
||||
if (selfClosing) {
|
||||
type = "self-closing";
|
||||
} else if (fullMatch.startsWith("</")) {
|
||||
type = "closing";
|
||||
} else {
|
||||
type = "opening";
|
||||
}
|
||||
|
||||
return {
|
||||
attributes: attributes.trim(),
|
||||
endIndex: match.index + fullMatch.length,
|
||||
startIndex: match.index,
|
||||
tag: fullMatch,
|
||||
tagName,
|
||||
type,
|
||||
};
|
||||
};
|
||||
|
||||
const stripIncompleteTag = (text: string) => {
|
||||
// Find the last '<' that isn't part of a complete tag
|
||||
const lastOpen = text.lastIndexOf("<");
|
||||
if (lastOpen === -1) {
|
||||
return text;
|
||||
}
|
||||
|
||||
const afterOpen = text.slice(lastOpen);
|
||||
// If there's no closing '>' after the last '<', it's an incomplete tag
|
||||
if (!afterOpen.includes(">")) {
|
||||
return text.slice(0, lastOpen);
|
||||
}
|
||||
|
||||
return text;
|
||||
};
|
||||
|
||||
const completeJsxTag = (code: string) => {
|
||||
const stack: string[] = [];
|
||||
let result = "";
|
||||
let currentPosition = 0;
|
||||
|
||||
while (currentPosition < code.length) {
|
||||
const match = matchJsxTag(code.slice(currentPosition));
|
||||
if (!match) {
|
||||
// No more tags found, strip any trailing incomplete tag
|
||||
result += stripIncompleteTag(code.slice(currentPosition));
|
||||
break;
|
||||
}
|
||||
const { tagName, type, endIndex } = match;
|
||||
|
||||
// Include any text content before this tag
|
||||
result += code.slice(currentPosition, currentPosition + endIndex);
|
||||
|
||||
if (type === "opening") {
|
||||
stack.push(tagName);
|
||||
} else if (type === "closing") {
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
currentPosition += endIndex;
|
||||
}
|
||||
|
||||
return (
|
||||
result +
|
||||
stack
|
||||
.toReversed()
|
||||
.map((tag) => `</${tag}>`)
|
||||
.join("")
|
||||
);
|
||||
};
|
||||
|
||||
export type JSXPreviewProps = ComponentProps<"div"> & {
|
||||
jsx: string;
|
||||
isStreaming?: boolean;
|
||||
components?: JsxParserProps["components"];
|
||||
bindings?: JsxParserProps["bindings"];
|
||||
onError?: (error: Error) => void;
|
||||
};
|
||||
|
||||
export const JSXPreview = memo(
|
||||
({
|
||||
jsx,
|
||||
isStreaming = false,
|
||||
components,
|
||||
bindings,
|
||||
onError,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: JSXPreviewProps) => {
|
||||
const [prevJsx, setPrevJsx] = useState(jsx);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const [_lastGoodJsx, setLastGoodJsx] = useState("");
|
||||
|
||||
// Clear error when jsx changes (derived state pattern)
|
||||
if (jsx !== prevJsx) {
|
||||
setPrevJsx(jsx);
|
||||
setError(null);
|
||||
}
|
||||
|
||||
const processedJsx = useMemo(
|
||||
() => (isStreaming ? completeJsxTag(jsx) : jsx),
|
||||
[jsx, isStreaming],
|
||||
);
|
||||
|
||||
const contextValue = useMemo(
|
||||
() => ({
|
||||
bindings,
|
||||
components,
|
||||
error,
|
||||
isStreaming,
|
||||
jsx,
|
||||
onErrorProp: onError,
|
||||
processedJsx,
|
||||
setError,
|
||||
setLastGoodJsx,
|
||||
}),
|
||||
[bindings, components, error, isStreaming, jsx, onError, processedJsx],
|
||||
);
|
||||
|
||||
return (
|
||||
<JSXPreviewContext.Provider value={contextValue}>
|
||||
<div className={cn("relative", className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
</JSXPreviewContext.Provider>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
JSXPreview.displayName = "JSXPreview";
|
||||
|
||||
export type JSXPreviewContentProps = Omit<ComponentProps<"div">, "children">;
|
||||
|
||||
export const JSXPreviewContent = memo(
|
||||
({ className, ...props }: JSXPreviewContentProps) => {
|
||||
const {
|
||||
processedJsx,
|
||||
isStreaming,
|
||||
components,
|
||||
bindings,
|
||||
setError,
|
||||
setLastGoodJsx,
|
||||
onErrorProp,
|
||||
} = useJSXPreview();
|
||||
const errorReportedRef = useRef<string | null>(null);
|
||||
const lastGoodJsxRef = useRef("");
|
||||
const [hadError, setHadError] = useState(false);
|
||||
|
||||
// Reset error tracking when jsx changes
|
||||
useEffect(() => {
|
||||
errorReportedRef.current = null;
|
||||
setHadError(false);
|
||||
}, []);
|
||||
|
||||
const handleError = useCallback(
|
||||
(err: Error) => {
|
||||
// Prevent duplicate error reports for the same jsx
|
||||
if (errorReportedRef.current === processedJsx) {
|
||||
return;
|
||||
}
|
||||
errorReportedRef.current = processedJsx;
|
||||
|
||||
// During streaming, suppress errors and fall back to last good JSX
|
||||
if (isStreaming) {
|
||||
setHadError(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(err);
|
||||
onErrorProp?.(err);
|
||||
},
|
||||
[processedJsx, isStreaming, onErrorProp, setError],
|
||||
);
|
||||
|
||||
// Track the last JSX that rendered without error
|
||||
useEffect(() => {
|
||||
if (!errorReportedRef.current) {
|
||||
lastGoodJsxRef.current = processedJsx;
|
||||
setLastGoodJsx(processedJsx);
|
||||
}
|
||||
}, [processedJsx, setLastGoodJsx]);
|
||||
|
||||
// During streaming, if the current JSX errored, re-render with last good version
|
||||
const displayJsx =
|
||||
isStreaming && hadError ? lastGoodJsxRef.current : processedJsx;
|
||||
|
||||
return (
|
||||
<div className={cn("jsx-preview-content", className)} {...props}>
|
||||
<JsxParser
|
||||
bindings={bindings}
|
||||
components={components}
|
||||
jsx={displayJsx}
|
||||
onError={handleError}
|
||||
renderInWrapper={false}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
JSXPreviewContent.displayName = "JSXPreviewContent";
|
||||
|
||||
export type JSXPreviewErrorProps = ComponentProps<"div"> & {
|
||||
children?: ReactNode | ((error: Error) => ReactNode);
|
||||
};
|
||||
|
||||
const renderChildren = (
|
||||
children: ReactNode | ((error: Error) => ReactNode),
|
||||
error: Error,
|
||||
): ReactNode => {
|
||||
if (typeof children === "function") {
|
||||
return children(error);
|
||||
}
|
||||
return children;
|
||||
};
|
||||
|
||||
export const JSXPreviewError = memo(
|
||||
({ className, children, ...props }: JSXPreviewErrorProps) => {
|
||||
const { error } = useJSXPreview();
|
||||
|
||||
if (!error) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-2 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-destructive text-sm",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children ? (
|
||||
renderChildren(children, error)
|
||||
) : (
|
||||
<>
|
||||
<AlertCircle className="size-4 shrink-0" />
|
||||
<span>{error.message}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
JSXPreviewError.displayName = "JSXPreviewError";
|
||||
@@ -1,357 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { cjk } from "@streamdown/cjk";
|
||||
import { code } from "@streamdown/code";
|
||||
import { math } from "@streamdown/math";
|
||||
import { mermaid } from "@streamdown/mermaid";
|
||||
import type { UIMessage } from "ai";
|
||||
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
|
||||
import type { ComponentProps, HTMLAttributes, ReactElement } from "react";
|
||||
import {
|
||||
createContext,
|
||||
memo,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import { Streamdown } from "streamdown";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ButtonGroup, ButtonGroupText } from "@/components/ui/button-group";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type MessageProps = HTMLAttributes<HTMLDivElement> & {
|
||||
from: UIMessage["role"];
|
||||
};
|
||||
|
||||
export const Message = ({ className, from, ...props }: MessageProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"group flex w-full flex-col gap-2",
|
||||
from === "user" ? "is-user ml-auto justify-end" : "is-assistant",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type MessageContentProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const MessageContent = ({
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: MessageContentProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"is-user:dark flex w-full flex-col gap-2 overflow-hidden text-sm",
|
||||
"group-[.is-user]:ml-auto group-[.is-user]:rounded-lg group-[.is-user]:bg-secondary group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-foreground",
|
||||
"group-[.is-assistant]:text-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type MessageActionsProps = ComponentProps<"div">;
|
||||
|
||||
export const MessageActions = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: MessageActionsProps) => (
|
||||
<div className={cn("flex items-center gap-1", className)} {...props}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
export type MessageActionProps = ComponentProps<typeof Button> & {
|
||||
tooltip?: string;
|
||||
label?: string;
|
||||
};
|
||||
|
||||
export const MessageAction = ({
|
||||
tooltip,
|
||||
children,
|
||||
label,
|
||||
variant = "ghost",
|
||||
size = "icon-sm",
|
||||
...props
|
||||
}: MessageActionProps) => {
|
||||
const button = (
|
||||
<Button size={size} type="button" variant={variant} {...props}>
|
||||
{children}
|
||||
<span className="sr-only">{label || tooltip}</span>
|
||||
</Button>
|
||||
);
|
||||
|
||||
if (tooltip) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger>{button}</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{tooltip}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
return button;
|
||||
};
|
||||
|
||||
interface MessageBranchContextType {
|
||||
currentBranch: number;
|
||||
totalBranches: number;
|
||||
goToPrevious: () => void;
|
||||
goToNext: () => void;
|
||||
branches: ReactElement[];
|
||||
setBranches: (branches: ReactElement[]) => void;
|
||||
}
|
||||
|
||||
const MessageBranchContext = createContext<MessageBranchContextType | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const useMessageBranch = () => {
|
||||
const context = useContext(MessageBranchContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
"MessageBranch components must be used within MessageBranch",
|
||||
);
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
export type MessageBranchProps = HTMLAttributes<HTMLDivElement> & {
|
||||
defaultBranch?: number;
|
||||
onBranchChange?: (branchIndex: number) => void;
|
||||
};
|
||||
|
||||
export const MessageBranch = ({
|
||||
defaultBranch = 0,
|
||||
onBranchChange,
|
||||
className,
|
||||
...props
|
||||
}: MessageBranchProps) => {
|
||||
const [currentBranch, setCurrentBranch] = useState(defaultBranch);
|
||||
const [branches, setBranches] = useState<ReactElement[]>([]);
|
||||
|
||||
const handleBranchChange = useCallback(
|
||||
(newBranch: number) => {
|
||||
setCurrentBranch(newBranch);
|
||||
onBranchChange?.(newBranch);
|
||||
},
|
||||
[onBranchChange],
|
||||
);
|
||||
|
||||
const goToPrevious = useCallback(() => {
|
||||
const newBranch =
|
||||
currentBranch > 0 ? currentBranch - 1 : branches.length - 1;
|
||||
handleBranchChange(newBranch);
|
||||
}, [currentBranch, branches.length, handleBranchChange]);
|
||||
|
||||
const goToNext = useCallback(() => {
|
||||
const newBranch =
|
||||
currentBranch < branches.length - 1 ? currentBranch + 1 : 0;
|
||||
handleBranchChange(newBranch);
|
||||
}, [currentBranch, branches.length, handleBranchChange]);
|
||||
|
||||
const contextValue = useMemo<MessageBranchContextType>(
|
||||
() => ({
|
||||
branches,
|
||||
currentBranch,
|
||||
goToNext,
|
||||
goToPrevious,
|
||||
setBranches,
|
||||
totalBranches: branches.length,
|
||||
}),
|
||||
[branches, currentBranch, goToNext, goToPrevious],
|
||||
);
|
||||
|
||||
return (
|
||||
<MessageBranchContext.Provider value={contextValue}>
|
||||
<div
|
||||
className={cn("grid w-full gap-2 [&>div]:pb-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
</MessageBranchContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type MessageBranchContentProps = HTMLAttributes<HTMLDivElement>;
|
||||
|
||||
export const MessageBranchContent = ({
|
||||
children,
|
||||
...props
|
||||
}: MessageBranchContentProps) => {
|
||||
const { currentBranch, setBranches, branches } = useMessageBranch();
|
||||
const childrenArray = useMemo(
|
||||
() => (Array.isArray(children) ? children : [children]),
|
||||
[children],
|
||||
);
|
||||
|
||||
// Use useEffect to update branches when they change
|
||||
useEffect(() => {
|
||||
if (branches.length !== childrenArray.length) {
|
||||
setBranches(childrenArray);
|
||||
}
|
||||
}, [childrenArray, branches, setBranches]);
|
||||
|
||||
return childrenArray.map((branch, index) => (
|
||||
<div
|
||||
className={cn(
|
||||
"grid gap-2 overflow-hidden [&>div]:pb-0",
|
||||
index === currentBranch ? "block" : "hidden",
|
||||
)}
|
||||
key={branch.key}
|
||||
{...props}
|
||||
>
|
||||
{branch}
|
||||
</div>
|
||||
));
|
||||
};
|
||||
|
||||
export type MessageBranchSelectorProps = ComponentProps<typeof ButtonGroup>;
|
||||
|
||||
export const MessageBranchSelector = ({
|
||||
className,
|
||||
...props
|
||||
}: MessageBranchSelectorProps) => {
|
||||
const { totalBranches } = useMessageBranch();
|
||||
|
||||
// Don't render if there's only one branch
|
||||
if (totalBranches <= 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<ButtonGroup
|
||||
className={cn(
|
||||
"[&>*:not(:first-child)]:rounded-l-md [&>*:not(:last-child)]:rounded-r-md",
|
||||
className,
|
||||
)}
|
||||
orientation="horizontal"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export type MessageBranchPreviousProps = ComponentProps<typeof Button>;
|
||||
|
||||
export const MessageBranchPrevious = ({
|
||||
children,
|
||||
...props
|
||||
}: MessageBranchPreviousProps) => {
|
||||
const { goToPrevious, totalBranches } = useMessageBranch();
|
||||
|
||||
return (
|
||||
<Button
|
||||
aria-label="Previous branch"
|
||||
disabled={totalBranches <= 1}
|
||||
onClick={goToPrevious}
|
||||
size="icon-sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
{children ?? <ChevronLeftIcon size={14} />}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export type MessageBranchNextProps = ComponentProps<typeof Button>;
|
||||
|
||||
export const MessageBranchNext = ({
|
||||
children,
|
||||
...props
|
||||
}: MessageBranchNextProps) => {
|
||||
const { goToNext, totalBranches } = useMessageBranch();
|
||||
|
||||
return (
|
||||
<Button
|
||||
aria-label="Next branch"
|
||||
disabled={totalBranches <= 1}
|
||||
onClick={goToNext}
|
||||
size="icon-sm"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
{children ?? <ChevronRightIcon size={14} />}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export type MessageBranchPageProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const MessageBranchPage = ({
|
||||
className,
|
||||
...props
|
||||
}: MessageBranchPageProps) => {
|
||||
const { currentBranch, totalBranches } = useMessageBranch();
|
||||
|
||||
return (
|
||||
<ButtonGroupText
|
||||
className={cn(
|
||||
"border-none bg-transparent text-muted-foreground shadow-none",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{currentBranch + 1} of {totalBranches}
|
||||
</ButtonGroupText>
|
||||
);
|
||||
};
|
||||
|
||||
export type MessageResponseProps = ComponentProps<typeof Streamdown>;
|
||||
|
||||
const streamdownPlugins = { cjk, code, math, mermaid };
|
||||
|
||||
export const MessageResponse = memo(
|
||||
({ className, ...props }: MessageResponseProps) => (
|
||||
<Streamdown
|
||||
className={cn(
|
||||
"size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",
|
||||
className,
|
||||
)}
|
||||
plugins={streamdownPlugins}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
(prevProps, nextProps) =>
|
||||
prevProps.children === nextProps.children &&
|
||||
nextProps.isAnimating === prevProps.isAnimating,
|
||||
);
|
||||
|
||||
MessageResponse.displayName = "MessageResponse";
|
||||
|
||||
export type MessageToolbarProps = ComponentProps<"div">;
|
||||
|
||||
export const MessageToolbar = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: MessageToolbarProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"mt-4 flex w-full items-center justify-between gap-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
@@ -1,373 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useControllableState } from "@radix-ui/react-use-controllable-state";
|
||||
import { ChevronsUpDownIcon } from "lucide-react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const deviceIdRegex = /\(([\da-fA-F]{4}:[\da-fA-F]{4})\)$/;
|
||||
|
||||
interface MicSelectorContextType {
|
||||
data: MediaDeviceInfo[];
|
||||
value: string | undefined;
|
||||
onValueChange?: (value: string) => void;
|
||||
open: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
width: number;
|
||||
setWidth?: (width: number) => void;
|
||||
}
|
||||
|
||||
const MicSelectorContext = createContext<MicSelectorContextType>({
|
||||
data: [],
|
||||
onOpenChange: undefined,
|
||||
onValueChange: undefined,
|
||||
open: false,
|
||||
setWidth: undefined,
|
||||
value: undefined,
|
||||
width: 200,
|
||||
});
|
||||
|
||||
export const useAudioDevices = () => {
|
||||
const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [hasPermission, setHasPermission] = useState(false);
|
||||
|
||||
const loadDevicesWithoutPermission = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const deviceList = await navigator.mediaDevices.enumerateDevices();
|
||||
const audioInputs = deviceList.filter(
|
||||
(device) => device.kind === "audioinput",
|
||||
);
|
||||
|
||||
setDevices(audioInputs);
|
||||
} catch (caughtError) {
|
||||
const message =
|
||||
caughtError instanceof Error
|
||||
? caughtError.message
|
||||
: "Failed to get audio devices";
|
||||
|
||||
setError(message);
|
||||
console.error("Error getting audio devices:", message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadDevicesWithPermission = useCallback(async () => {
|
||||
if (loading) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const tempStream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: true,
|
||||
});
|
||||
|
||||
for (const track of tempStream.getTracks()) {
|
||||
track.stop();
|
||||
}
|
||||
|
||||
const deviceList = await navigator.mediaDevices.enumerateDevices();
|
||||
const audioInputs = deviceList.filter(
|
||||
(device) => device.kind === "audioinput",
|
||||
);
|
||||
|
||||
setDevices(audioInputs);
|
||||
setHasPermission(true);
|
||||
} catch (caughtError) {
|
||||
const message =
|
||||
caughtError instanceof Error
|
||||
? caughtError.message
|
||||
: "Failed to get audio devices";
|
||||
|
||||
setError(message);
|
||||
console.error("Error getting audio devices:", message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [loading]);
|
||||
|
||||
useEffect(() => {
|
||||
loadDevicesWithoutPermission();
|
||||
}, [loadDevicesWithoutPermission]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleDeviceChange = () => {
|
||||
if (hasPermission) {
|
||||
loadDevicesWithPermission();
|
||||
} else {
|
||||
loadDevicesWithoutPermission();
|
||||
}
|
||||
};
|
||||
|
||||
navigator.mediaDevices.addEventListener("devicechange", handleDeviceChange);
|
||||
|
||||
return () => {
|
||||
navigator.mediaDevices.removeEventListener(
|
||||
"devicechange",
|
||||
handleDeviceChange,
|
||||
);
|
||||
};
|
||||
}, [hasPermission, loadDevicesWithPermission, loadDevicesWithoutPermission]);
|
||||
|
||||
return {
|
||||
devices,
|
||||
error,
|
||||
hasPermission,
|
||||
loadDevices: loadDevicesWithPermission,
|
||||
loading,
|
||||
};
|
||||
};
|
||||
|
||||
export type MicSelectorProps = ComponentProps<typeof Popover> & {
|
||||
defaultValue?: string;
|
||||
value?: string | undefined;
|
||||
onValueChange?: (value: string | undefined) => void;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
};
|
||||
|
||||
export const MicSelector = ({
|
||||
defaultValue,
|
||||
value: controlledValue,
|
||||
onValueChange: controlledOnValueChange,
|
||||
defaultOpen = false,
|
||||
open: controlledOpen,
|
||||
onOpenChange: controlledOnOpenChange,
|
||||
...props
|
||||
}: MicSelectorProps) => {
|
||||
const [value, onValueChange] = useControllableState<string | undefined>({
|
||||
defaultProp: defaultValue,
|
||||
onChange: controlledOnValueChange,
|
||||
prop: controlledValue,
|
||||
});
|
||||
const [open, onOpenChange] = useControllableState({
|
||||
defaultProp: defaultOpen,
|
||||
onChange: controlledOnOpenChange,
|
||||
prop: controlledOpen,
|
||||
});
|
||||
const [width, setWidth] = useState(200);
|
||||
const { devices, loading, hasPermission, loadDevices } = useAudioDevices();
|
||||
|
||||
useEffect(() => {
|
||||
if (open && !hasPermission && !loading) {
|
||||
loadDevices();
|
||||
}
|
||||
}, [open, hasPermission, loading, loadDevices]);
|
||||
|
||||
const contextValue = useMemo(
|
||||
() => ({
|
||||
data: devices,
|
||||
onOpenChange,
|
||||
onValueChange,
|
||||
open,
|
||||
setWidth,
|
||||
value,
|
||||
width,
|
||||
}),
|
||||
[devices, onOpenChange, onValueChange, open, value, width],
|
||||
);
|
||||
|
||||
return (
|
||||
<MicSelectorContext.Provider value={contextValue}>
|
||||
<Popover {...props} onOpenChange={onOpenChange} open={open} />
|
||||
</MicSelectorContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type MicSelectorTriggerProps = ComponentProps<typeof Button>;
|
||||
|
||||
export const MicSelectorTrigger = ({
|
||||
children,
|
||||
...props
|
||||
}: MicSelectorTriggerProps) => {
|
||||
const { setWidth } = useContext(MicSelectorContext);
|
||||
const ref = useRef<HTMLButtonElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Create a ResizeObserver to detect width changes
|
||||
const resizeObserver = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
const newWidth = (entry.target as HTMLElement).offsetWidth;
|
||||
if (newWidth) {
|
||||
setWidth?.(newWidth);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (ref.current) {
|
||||
resizeObserver.observe(ref.current);
|
||||
}
|
||||
|
||||
// Clean up the observer when component unmounts
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [setWidth]);
|
||||
|
||||
return (
|
||||
<PopoverTrigger render={<Button variant="outline" {...props} ref={ref} />}>
|
||||
{children}
|
||||
<ChevronsUpDownIcon
|
||||
className="shrink-0 text-muted-foreground"
|
||||
size={16}
|
||||
/>
|
||||
</PopoverTrigger>
|
||||
);
|
||||
};
|
||||
|
||||
export type MicSelectorContentProps = ComponentProps<typeof Command> & {
|
||||
popoverOptions?: ComponentProps<typeof PopoverContent>;
|
||||
};
|
||||
|
||||
export const MicSelectorContent = ({
|
||||
className,
|
||||
popoverOptions,
|
||||
...props
|
||||
}: MicSelectorContentProps) => {
|
||||
const { width, onValueChange, value } = useContext(MicSelectorContext);
|
||||
|
||||
return (
|
||||
<PopoverContent
|
||||
className={cn("p-0", className)}
|
||||
style={{ width }}
|
||||
{...popoverOptions}
|
||||
>
|
||||
<Command onValueChange={onValueChange} value={value} {...props} />
|
||||
</PopoverContent>
|
||||
);
|
||||
};
|
||||
|
||||
export type MicSelectorInputProps = ComponentProps<typeof CommandInput> & {
|
||||
value?: string;
|
||||
defaultValue?: string;
|
||||
onValueChange?: (value: string) => void;
|
||||
};
|
||||
|
||||
export const MicSelectorInput = ({ ...props }: MicSelectorInputProps) => (
|
||||
<CommandInput placeholder="Search microphones..." {...props} />
|
||||
);
|
||||
|
||||
export type MicSelectorListProps = Omit<
|
||||
ComponentProps<typeof CommandList>,
|
||||
"children"
|
||||
> & {
|
||||
children: (devices: MediaDeviceInfo[]) => ReactNode;
|
||||
};
|
||||
|
||||
export const MicSelectorList = ({
|
||||
children,
|
||||
...props
|
||||
}: MicSelectorListProps) => {
|
||||
const { data } = useContext(MicSelectorContext);
|
||||
|
||||
return <CommandList {...props}>{children(data)}</CommandList>;
|
||||
};
|
||||
|
||||
export type MicSelectorEmptyProps = ComponentProps<typeof CommandEmpty>;
|
||||
|
||||
export const MicSelectorEmpty = ({
|
||||
children = "No microphone found.",
|
||||
...props
|
||||
}: MicSelectorEmptyProps) => <CommandEmpty {...props}>{children}</CommandEmpty>;
|
||||
|
||||
export type MicSelectorItemProps = ComponentProps<typeof CommandItem>;
|
||||
|
||||
export const MicSelectorItem = (props: MicSelectorItemProps) => {
|
||||
const { onValueChange, onOpenChange } = useContext(MicSelectorContext);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(currentValue: string) => {
|
||||
onValueChange?.(currentValue);
|
||||
onOpenChange?.(false);
|
||||
},
|
||||
[onValueChange, onOpenChange],
|
||||
);
|
||||
|
||||
return <CommandItem onSelect={handleSelect} {...props} />;
|
||||
};
|
||||
|
||||
export type MicSelectorLabelProps = ComponentProps<"span"> & {
|
||||
device: MediaDeviceInfo;
|
||||
};
|
||||
|
||||
export const MicSelectorLabel = ({
|
||||
device,
|
||||
className,
|
||||
...props
|
||||
}: MicSelectorLabelProps) => {
|
||||
const matches = device.label.match(deviceIdRegex);
|
||||
|
||||
if (!matches) {
|
||||
return (
|
||||
<span className={className} {...props}>
|
||||
{device.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const [, deviceId] = matches;
|
||||
const name = device.label.replace(deviceIdRegex, "");
|
||||
|
||||
return (
|
||||
<span className={className} {...props}>
|
||||
<span>{name}</span>
|
||||
<span className="text-muted-foreground"> ({deviceId})</span>
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
export type MicSelectorValueProps = ComponentProps<"span">;
|
||||
|
||||
export const MicSelectorValue = ({
|
||||
className,
|
||||
...props
|
||||
}: MicSelectorValueProps) => {
|
||||
const { data, value } = useContext(MicSelectorContext);
|
||||
const currentDevice = data.find((d) => d.deviceId === value);
|
||||
|
||||
if (!currentDevice) {
|
||||
return (
|
||||
<span className={cn("flex-1 text-left", className)} {...props}>
|
||||
Select microphone...
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<MicSelectorLabel
|
||||
className={cn("flex-1 text-left", className)}
|
||||
device={currentDevice}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,213 +0,0 @@
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
CommandSeparator,
|
||||
CommandShortcut,
|
||||
} from "@/components/ui/command";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ModelSelectorProps = ComponentProps<typeof Dialog>;
|
||||
|
||||
export const ModelSelector = (props: ModelSelectorProps) => (
|
||||
<Dialog {...props} />
|
||||
);
|
||||
|
||||
export type ModelSelectorTriggerProps = ComponentProps<typeof DialogTrigger>;
|
||||
|
||||
export const ModelSelectorTrigger = (props: ModelSelectorTriggerProps) => (
|
||||
<DialogTrigger {...props} />
|
||||
);
|
||||
|
||||
export type ModelSelectorContentProps = ComponentProps<typeof DialogContent> & {
|
||||
title?: ReactNode;
|
||||
};
|
||||
|
||||
export const ModelSelectorContent = ({
|
||||
className,
|
||||
children,
|
||||
title = "Model Selector",
|
||||
...props
|
||||
}: ModelSelectorContentProps) => (
|
||||
<DialogContent
|
||||
aria-describedby={undefined}
|
||||
className={cn(
|
||||
"outline! border-none! p-0 outline-border! outline-solid!",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<DialogTitle className="sr-only">{title}</DialogTitle>
|
||||
<Command className="**:data-[slot=command-input-wrapper]:h-auto">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
);
|
||||
|
||||
export type ModelSelectorDialogProps = ComponentProps<typeof CommandDialog>;
|
||||
|
||||
export const ModelSelectorDialog = (props: ModelSelectorDialogProps) => (
|
||||
<CommandDialog {...props} />
|
||||
);
|
||||
|
||||
export type ModelSelectorInputProps = ComponentProps<typeof CommandInput>;
|
||||
|
||||
export const ModelSelectorInput = ({
|
||||
className,
|
||||
...props
|
||||
}: ModelSelectorInputProps) => (
|
||||
<CommandInput className={cn("h-auto py-3.5", className)} {...props} />
|
||||
);
|
||||
|
||||
export type ModelSelectorListProps = ComponentProps<typeof CommandList>;
|
||||
|
||||
export const ModelSelectorList = (props: ModelSelectorListProps) => (
|
||||
<CommandList {...props} />
|
||||
);
|
||||
|
||||
export type ModelSelectorEmptyProps = ComponentProps<typeof CommandEmpty>;
|
||||
|
||||
export const ModelSelectorEmpty = (props: ModelSelectorEmptyProps) => (
|
||||
<CommandEmpty {...props} />
|
||||
);
|
||||
|
||||
export type ModelSelectorGroupProps = ComponentProps<typeof CommandGroup>;
|
||||
|
||||
export const ModelSelectorGroup = (props: ModelSelectorGroupProps) => (
|
||||
<CommandGroup {...props} />
|
||||
);
|
||||
|
||||
export type ModelSelectorItemProps = ComponentProps<typeof CommandItem>;
|
||||
|
||||
export const ModelSelectorItem = (props: ModelSelectorItemProps) => (
|
||||
<CommandItem {...props} />
|
||||
);
|
||||
|
||||
export type ModelSelectorShortcutProps = ComponentProps<typeof CommandShortcut>;
|
||||
|
||||
export const ModelSelectorShortcut = (props: ModelSelectorShortcutProps) => (
|
||||
<CommandShortcut {...props} />
|
||||
);
|
||||
|
||||
export type ModelSelectorSeparatorProps = ComponentProps<
|
||||
typeof CommandSeparator
|
||||
>;
|
||||
|
||||
export const ModelSelectorSeparator = (props: ModelSelectorSeparatorProps) => (
|
||||
<CommandSeparator {...props} />
|
||||
);
|
||||
|
||||
export type ModelSelectorLogoProps = Omit<
|
||||
ComponentProps<"img">,
|
||||
"src" | "alt"
|
||||
> & {
|
||||
provider:
|
||||
| "moonshotai-cn"
|
||||
| "lucidquery"
|
||||
| "moonshotai"
|
||||
| "zai-coding-plan"
|
||||
| "alibaba"
|
||||
| "xai"
|
||||
| "vultr"
|
||||
| "nvidia"
|
||||
| "upstage"
|
||||
| "groq"
|
||||
| "github-copilot"
|
||||
| "mistral"
|
||||
| "vercel"
|
||||
| "nebius"
|
||||
| "deepseek"
|
||||
| "alibaba-cn"
|
||||
| "google-vertex-anthropic"
|
||||
| "venice"
|
||||
| "chutes"
|
||||
| "cortecs"
|
||||
| "github-models"
|
||||
| "togetherai"
|
||||
| "azure"
|
||||
| "baseten"
|
||||
| "huggingface"
|
||||
| "opencode"
|
||||
| "fastrouter"
|
||||
| "google"
|
||||
| "google-vertex"
|
||||
| "cloudflare-workers-ai"
|
||||
| "inception"
|
||||
| "wandb"
|
||||
| "openai"
|
||||
| "zhipuai-coding-plan"
|
||||
| "perplexity"
|
||||
| "openrouter"
|
||||
| "zenmux"
|
||||
| "v0"
|
||||
| "iflowcn"
|
||||
| "synthetic"
|
||||
| "deepinfra"
|
||||
| "zhipuai"
|
||||
| "submodel"
|
||||
| "zai"
|
||||
| "inference"
|
||||
| "requesty"
|
||||
| "morph"
|
||||
| "lmstudio"
|
||||
| "anthropic"
|
||||
| "aihubmix"
|
||||
| "fireworks-ai"
|
||||
| "modelscope"
|
||||
| "llama"
|
||||
| "scaleway"
|
||||
| "amazon-bedrock"
|
||||
| "cerebras"
|
||||
// oxlint-disable-next-line typescript-eslint(ban-types) -- intentional pattern for autocomplete-friendly string union
|
||||
| (string & {});
|
||||
};
|
||||
|
||||
export const ModelSelectorLogo = ({
|
||||
provider,
|
||||
className,
|
||||
...props
|
||||
}: ModelSelectorLogoProps) => (
|
||||
<img
|
||||
{...props}
|
||||
alt={`${provider} logo`}
|
||||
className={cn("size-3 dark:invert", className)}
|
||||
height={12}
|
||||
src={`https://models.dev/logos/${provider}.svg`}
|
||||
width={12}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ModelSelectorLogoGroupProps = ComponentProps<"div">;
|
||||
|
||||
export const ModelSelectorLogoGroup = ({
|
||||
className,
|
||||
...props
|
||||
}: ModelSelectorLogoGroupProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex shrink-0 items-center -space-x-1 [&>img]:rounded-full [&>img]:bg-background [&>img]:p-px [&>img]:ring-1 dark:[&>img]:bg-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ModelSelectorNameProps = ComponentProps<"span">;
|
||||
|
||||
export const ModelSelectorName = ({
|
||||
className,
|
||||
...props
|
||||
}: ModelSelectorNameProps) => (
|
||||
<span className={cn("flex-1 truncate text-left", className)} {...props} />
|
||||
);
|
||||
@@ -1,71 +0,0 @@
|
||||
import { Handle, Position } from "@xyflow/react";
|
||||
import type { ComponentProps } from "react";
|
||||
import {
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type NodeProps = ComponentProps<typeof Card> & {
|
||||
handles: {
|
||||
target: boolean;
|
||||
source: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
export const Node = ({ handles, className, ...props }: NodeProps) => (
|
||||
<Card
|
||||
className={cn(
|
||||
"node-container relative size-full h-auto w-sm gap-0 rounded-md p-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{handles.target && <Handle position={Position.Left} type="target" />}
|
||||
{handles.source && <Handle position={Position.Right} type="source" />}
|
||||
{props.children}
|
||||
</Card>
|
||||
);
|
||||
|
||||
export type NodeHeaderProps = ComponentProps<typeof CardHeader>;
|
||||
|
||||
export const NodeHeader = ({ className, ...props }: NodeHeaderProps) => (
|
||||
<CardHeader
|
||||
className={cn("gap-0.5 rounded-t-md border-b bg-secondary p-3!", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type NodeTitleProps = ComponentProps<typeof CardTitle>;
|
||||
|
||||
export const NodeTitle = (props: NodeTitleProps) => <CardTitle {...props} />;
|
||||
|
||||
export type NodeDescriptionProps = ComponentProps<typeof CardDescription>;
|
||||
|
||||
export const NodeDescription = (props: NodeDescriptionProps) => (
|
||||
<CardDescription {...props} />
|
||||
);
|
||||
|
||||
export type NodeActionProps = ComponentProps<typeof CardAction>;
|
||||
|
||||
export const NodeAction = (props: NodeActionProps) => <CardAction {...props} />;
|
||||
|
||||
export type NodeContentProps = ComponentProps<typeof CardContent>;
|
||||
|
||||
export const NodeContent = ({ className, ...props }: NodeContentProps) => (
|
||||
<CardContent className={cn("p-3", className)} {...props} />
|
||||
);
|
||||
|
||||
export type NodeFooterProps = ComponentProps<typeof CardFooter>;
|
||||
|
||||
export const NodeFooter = ({ className, ...props }: NodeFooterProps) => (
|
||||
<CardFooter
|
||||
className={cn("rounded-b-md border-t bg-secondary p-3!", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
@@ -1,394 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ExternalLinkIcon,
|
||||
MessageCircleIcon,
|
||||
} from "lucide-react";
|
||||
import type { ComponentProps } from "react";
|
||||
import { createContext, useContext, useMemo } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const providers = {
|
||||
chatgpt: {
|
||||
createUrl: (prompt: string) =>
|
||||
`https://chatgpt.com/?${new URLSearchParams({
|
||||
hints: "search",
|
||||
prompt,
|
||||
})}`,
|
||||
icon: (
|
||||
<svg
|
||||
fill="currentColor"
|
||||
role="img"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<title>OpenAI</title>
|
||||
<path d="M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z" />
|
||||
</svg>
|
||||
),
|
||||
title: "Open in ChatGPT",
|
||||
},
|
||||
claude: {
|
||||
createUrl: (q: string) =>
|
||||
`https://claude.ai/new?${new URLSearchParams({
|
||||
q,
|
||||
})}`,
|
||||
icon: (
|
||||
<svg
|
||||
fill="currentColor"
|
||||
role="img"
|
||||
viewBox="0 0 12 12"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<title>Claude</title>
|
||||
<path
|
||||
clipRule="evenodd"
|
||||
d="M2.3545 7.9775L4.7145 6.654L4.7545 6.539L4.7145 6.475H4.6L4.205 6.451L2.856 6.4145L1.6865 6.366L0.5535 6.305L0.268 6.2445L0 5.892L0.0275 5.716L0.2675 5.5555L0.6105 5.5855L1.3705 5.637L2.5095 5.716L3.3355 5.7645L4.56 5.892H4.7545L4.782 5.8135L4.715 5.7645L4.6635 5.716L3.4845 4.918L2.2085 4.074L1.5405 3.588L1.1785 3.3425L0.9965 3.1115L0.9175 2.6075L1.2455 2.2465L1.686 2.2765L1.7985 2.307L2.245 2.65L3.199 3.388L4.4445 4.3045L4.627 4.4565L4.6995 4.405L4.709 4.3685L4.627 4.2315L3.9495 3.0085L3.2265 1.7635L2.9045 1.2475L2.8195 0.938C2.78711 0.819128 2.76965 0.696687 2.7675 0.5735L3.1415 0.067L3.348 0L3.846 0.067L4.056 0.249L4.366 0.956L4.867 2.0705L5.6445 3.5855L5.8725 4.0345L5.994 4.4505L6.0395 4.578H6.1185V4.505L6.1825 3.652L6.301 2.6045L6.416 1.257L6.456 0.877L6.644 0.422L7.0175 0.176L7.3095 0.316L7.5495 0.6585L7.516 0.8805L7.373 1.806L7.0935 3.2575L6.9115 4.2285H7.0175L7.139 4.1075L7.6315 3.4545L8.4575 2.4225L8.8225 2.0125L9.2475 1.5605L9.521 1.345H10.0375L10.4175 1.9095L10.2475 2.4925L9.7155 3.166L9.275 3.737L8.643 4.587L8.248 5.267L8.2845 5.322L8.3785 5.312L9.8065 5.009L10.578 4.869L11.4985 4.7115L11.915 4.9055L11.9605 5.103L11.7965 5.5065L10.812 5.7495L9.6575 5.9805L7.938 6.387L7.917 6.402L7.9415 6.4325L8.716 6.5055L9.047 6.5235H9.858L11.368 6.636L11.763 6.897L12 7.216L11.9605 7.4585L11.353 7.7685L10.533 7.574L8.6185 7.119L7.9625 6.9545H7.8715V7.0095L8.418 7.5435L9.421 8.4485L10.6755 9.6135L10.739 9.9025L10.578 10.13L10.408 10.1055L9.3055 9.277L8.88 8.9035L7.917 8.0935H7.853V8.1785L8.075 8.503L9.2475 10.2635L9.3085 10.8035L9.2235 10.98L8.9195 11.0865L8.5855 11.0255L7.8985 10.063L7.191 8.9795L6.6195 8.008L6.5495 8.048L6.2125 11.675L6.0545 11.86L5.69 12L5.3865 11.7695L5.2255 11.396L5.3865 10.658L5.581 9.696L5.7385 8.931L5.8815 7.981L5.9665 7.665L5.9605 7.644L5.8905 7.653L5.1735 8.6365L4.0835 10.109L3.2205 11.0315L3.0135 11.1135L2.655 10.9285L2.6885 10.5975L2.889 10.303L4.083 8.785L4.803 7.844L5.268 7.301L5.265 7.222H5.2375L2.066 9.28L1.501 9.353L1.2575 9.125L1.288 8.752L1.4035 8.6305L2.3575 7.9745L2.3545 7.9775Z"
|
||||
fillRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
title: "Open in Claude",
|
||||
},
|
||||
cursor: {
|
||||
createUrl: (text: string) => {
|
||||
const url = new URL("https://cursor.com/link/prompt");
|
||||
url.searchParams.set("text", text);
|
||||
return url.toString();
|
||||
},
|
||||
icon: (
|
||||
<svg
|
||||
version="1.1"
|
||||
viewBox="0 0 466.73 532.09"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<title>Cursor</title>
|
||||
<path
|
||||
d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
title: "Open in Cursor",
|
||||
},
|
||||
github: {
|
||||
createUrl: (url: string) => url,
|
||||
icon: (
|
||||
<svg fill="currentColor" role="img" viewBox="0 0 24 24">
|
||||
<title>GitHub</title>
|
||||
<path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12" />
|
||||
</svg>
|
||||
),
|
||||
title: "Open in GitHub",
|
||||
},
|
||||
scira: {
|
||||
createUrl: (q: string) =>
|
||||
`https://scira.ai/?${new URLSearchParams({
|
||||
q,
|
||||
})}`,
|
||||
icon: (
|
||||
<svg
|
||||
fill="none"
|
||||
height="934"
|
||||
viewBox="0 0 910 934"
|
||||
width="910"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<title>Scira AI</title>
|
||||
<path
|
||||
d="M647.664 197.775C569.13 189.049 525.5 145.419 516.774 66.8849C508.048 145.419 464.418 189.049 385.884 197.775C464.418 206.501 508.048 250.131 516.774 328.665C525.5 250.131 569.13 206.501 647.664 197.775Z"
|
||||
fill="currentColor"
|
||||
stroke="currentColor"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="8"
|
||||
/>
|
||||
<path
|
||||
d="M516.774 304.217C510.299 275.491 498.208 252.087 480.335 234.214C462.462 216.341 439.058 204.251 410.333 197.775C439.059 191.3 462.462 179.209 480.335 161.336C498.208 143.463 510.299 120.06 516.774 91.334C523.25 120.059 535.34 143.463 553.213 161.336C571.086 179.209 594.49 191.3 623.216 197.775C594.49 204.251 571.086 216.341 553.213 234.214C535.34 252.087 523.25 275.491 516.774 304.217Z"
|
||||
fill="currentColor"
|
||||
stroke="currentColor"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="8"
|
||||
/>
|
||||
<path
|
||||
d="M857.5 508.116C763.259 497.644 710.903 445.288 700.432 351.047C689.961 445.288 637.605 497.644 543.364 508.116C637.605 518.587 689.961 570.943 700.432 665.184C710.903 570.943 763.259 518.587 857.5 508.116Z"
|
||||
stroke="currentColor"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="20"
|
||||
/>
|
||||
<path
|
||||
d="M700.432 615.957C691.848 589.05 678.575 566.357 660.383 548.165C642.191 529.973 619.499 516.7 592.593 508.116C619.499 499.533 642.191 486.258 660.383 468.066C678.575 449.874 691.848 427.181 700.432 400.274C709.015 427.181 722.289 449.874 740.481 468.066C758.673 486.258 781.365 499.533 808.271 508.116C781.365 516.7 758.673 529.973 740.481 548.165C722.289 566.357 709.015 589.05 700.432 615.957Z"
|
||||
stroke="currentColor"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="20"
|
||||
/>
|
||||
<path
|
||||
d="M889.949 121.237C831.049 114.692 798.326 81.9698 791.782 23.0692C785.237 81.9698 752.515 114.692 693.614 121.237C752.515 127.781 785.237 160.504 791.782 219.404C798.326 160.504 831.049 127.781 889.949 121.237Z"
|
||||
fill="currentColor"
|
||||
stroke="currentColor"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="8"
|
||||
/>
|
||||
<path
|
||||
d="M791.782 196.795C786.697 176.937 777.869 160.567 765.16 147.858C752.452 135.15 736.082 126.322 716.226 121.237C736.082 116.152 752.452 107.324 765.16 94.6152C777.869 81.9065 786.697 65.5368 791.782 45.6797C796.867 65.5367 805.695 81.9066 818.403 94.6152C831.112 107.324 847.481 116.152 867.338 121.237C847.481 126.322 831.112 135.15 818.403 147.858C805.694 160.567 796.867 176.937 791.782 196.795Z"
|
||||
fill="currentColor"
|
||||
stroke="currentColor"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="8"
|
||||
/>
|
||||
<path
|
||||
d="M760.632 764.337C720.719 814.616 669.835 855.1 611.872 882.692C553.91 910.285 490.404 924.255 426.213 923.533C362.022 922.812 298.846 907.419 241.518 878.531C184.19 849.643 134.228 808.026 95.4548 756.863C56.6815 705.7 30.1238 646.346 17.8129 583.343C5.50207 520.339 7.76433 455.354 24.4266 393.359C41.089 331.364 71.7099 274.001 113.947 225.658C156.184 177.315 208.919 139.273 268.117 114.442"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="30"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
title: "Open in Scira",
|
||||
},
|
||||
t3: {
|
||||
createUrl: (q: string) =>
|
||||
`https://t3.chat/new?${new URLSearchParams({
|
||||
q,
|
||||
})}`,
|
||||
icon: <MessageCircleIcon />,
|
||||
title: "Open in T3 Chat",
|
||||
},
|
||||
v0: {
|
||||
createUrl: (q: string) =>
|
||||
`https://v0.app?${new URLSearchParams({
|
||||
q,
|
||||
})}`,
|
||||
icon: (
|
||||
<svg
|
||||
fill="currentColor"
|
||||
viewBox="0 0 147 70"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<title>v0</title>
|
||||
<path d="M56 50.2031V14H70V60.1562C70 65.5928 65.5928 70 60.1562 70C57.5605 70 54.9982 68.9992 53.1562 67.1573L0 14H19.7969L56 50.2031Z" />
|
||||
<path d="M147 56H133V23.9531L100.953 56H133V70H96.6875C85.8144 70 77 61.1856 77 50.3125V14H91V46.1562L123.156 14H91V0H127.312C138.186 0 147 8.81439 147 19.6875V56Z" />
|
||||
</svg>
|
||||
),
|
||||
title: "Open in v0",
|
||||
},
|
||||
};
|
||||
|
||||
const OpenInContext = createContext<{ query: string } | undefined>(undefined);
|
||||
|
||||
const useOpenInContext = () => {
|
||||
const context = useContext(OpenInContext);
|
||||
if (!context) {
|
||||
throw new Error("OpenIn components must be used within an OpenIn provider");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export type OpenInProps = ComponentProps<typeof DropdownMenu> & {
|
||||
query: string;
|
||||
};
|
||||
|
||||
export const OpenIn = ({ query, ...props }: OpenInProps) => {
|
||||
const contextValue = useMemo(() => ({ query }), [query]);
|
||||
|
||||
return (
|
||||
<OpenInContext.Provider value={contextValue}>
|
||||
<DropdownMenu {...props} />
|
||||
</OpenInContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export type OpenInContentProps = ComponentProps<typeof DropdownMenuContent>;
|
||||
|
||||
export const OpenInContent = ({ className, ...props }: OpenInContentProps) => (
|
||||
<DropdownMenuContent
|
||||
align="start"
|
||||
className={cn("w-[240px]", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type OpenInItemProps = ComponentProps<typeof DropdownMenuItem>;
|
||||
|
||||
export const OpenInItem = (props: OpenInItemProps) => (
|
||||
<DropdownMenuItem {...props} />
|
||||
);
|
||||
|
||||
export type OpenInLabelProps = ComponentProps<typeof DropdownMenuLabel>;
|
||||
|
||||
export const OpenInLabel = (props: OpenInLabelProps) => (
|
||||
<DropdownMenuLabel {...props} />
|
||||
);
|
||||
|
||||
export type OpenInSeparatorProps = ComponentProps<typeof DropdownMenuSeparator>;
|
||||
|
||||
export const OpenInSeparator = (props: OpenInSeparatorProps) => (
|
||||
<DropdownMenuSeparator {...props} />
|
||||
);
|
||||
|
||||
export type OpenInTriggerProps = ComponentProps<typeof DropdownMenuTrigger>;
|
||||
|
||||
export const OpenInTrigger = ({ children, ...props }: OpenInTriggerProps) => (
|
||||
<DropdownMenuTrigger {...props}>
|
||||
{children ?? (
|
||||
<Button type="button" variant="outline">
|
||||
Open in chat
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
</DropdownMenuTrigger>
|
||||
);
|
||||
|
||||
export type OpenInChatGPTProps = ComponentProps<typeof DropdownMenuItem>;
|
||||
|
||||
export const OpenInChatGPT = (props: OpenInChatGPTProps) => {
|
||||
const { query } = useOpenInContext();
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
{...props}
|
||||
render={
|
||||
// biome-ignore lint/a11y/useAnchorContent: content provided by DropdownMenuItem children
|
||||
<a
|
||||
className="flex items-center gap-2"
|
||||
href={providers.chatgpt.createUrl(query)}
|
||||
rel="noopener"
|
||||
target="_blank"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="shrink-0">{providers.chatgpt.icon}</span>
|
||||
<span className="flex-1">{providers.chatgpt.title}</span>
|
||||
<ExternalLinkIcon className="size-4 shrink-0" />
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
};
|
||||
|
||||
export type OpenInClaudeProps = ComponentProps<typeof DropdownMenuItem>;
|
||||
|
||||
export const OpenInClaude = (props: OpenInClaudeProps) => {
|
||||
const { query } = useOpenInContext();
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
{...props}
|
||||
render={
|
||||
// biome-ignore lint/a11y/useAnchorContent: content provided by DropdownMenuItem children
|
||||
<a
|
||||
className="flex items-center gap-2"
|
||||
href={providers.claude.createUrl(query)}
|
||||
rel="noopener"
|
||||
target="_blank"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="shrink-0">{providers.claude.icon}</span>
|
||||
<span className="flex-1">{providers.claude.title}</span>
|
||||
<ExternalLinkIcon className="size-4 shrink-0" />
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
};
|
||||
|
||||
export type OpenInT3Props = ComponentProps<typeof DropdownMenuItem>;
|
||||
|
||||
export const OpenInT3 = (props: OpenInT3Props) => {
|
||||
const { query } = useOpenInContext();
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
{...props}
|
||||
render={
|
||||
// biome-ignore lint/a11y/useAnchorContent: content provided by DropdownMenuItem children
|
||||
<a
|
||||
className="flex items-center gap-2"
|
||||
href={providers.t3.createUrl(query)}
|
||||
rel="noopener"
|
||||
target="_blank"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="shrink-0">{providers.t3.icon}</span>
|
||||
<span className="flex-1">{providers.t3.title}</span>
|
||||
<ExternalLinkIcon className="size-4 shrink-0" />
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
};
|
||||
|
||||
export type OpenInSciraProps = ComponentProps<typeof DropdownMenuItem>;
|
||||
|
||||
export const OpenInScira = (props: OpenInSciraProps) => {
|
||||
const { query } = useOpenInContext();
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
{...props}
|
||||
render={
|
||||
// biome-ignore lint/a11y/useAnchorContent: content provided by DropdownMenuItem children
|
||||
<a
|
||||
className="flex items-center gap-2"
|
||||
href={providers.scira.createUrl(query)}
|
||||
rel="noopener"
|
||||
target="_blank"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="shrink-0">{providers.scira.icon}</span>
|
||||
<span className="flex-1">{providers.scira.title}</span>
|
||||
<ExternalLinkIcon className="size-4 shrink-0" />
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
};
|
||||
|
||||
export type OpenInv0Props = ComponentProps<typeof DropdownMenuItem>;
|
||||
|
||||
export const OpenInv0 = (props: OpenInv0Props) => {
|
||||
const { query } = useOpenInContext();
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
{...props}
|
||||
render={
|
||||
// biome-ignore lint/a11y/useAnchorContent: content provided by DropdownMenuItem children
|
||||
<a
|
||||
className="flex items-center gap-2"
|
||||
href={providers.v0.createUrl(query)}
|
||||
rel="noopener"
|
||||
target="_blank"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="shrink-0">{providers.v0.icon}</span>
|
||||
<span className="flex-1">{providers.v0.title}</span>
|
||||
<ExternalLinkIcon className="size-4 shrink-0" />
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
};
|
||||
|
||||
export type OpenInCursorProps = ComponentProps<typeof DropdownMenuItem>;
|
||||
|
||||
export const OpenInCursor = (props: OpenInCursorProps) => {
|
||||
const { query } = useOpenInContext();
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
{...props}
|
||||
render={
|
||||
// biome-ignore lint/a11y/useAnchorContent: content provided by DropdownMenuItem children
|
||||
<a
|
||||
className="flex items-center gap-2"
|
||||
href={providers.cursor.createUrl(query)}
|
||||
rel="noopener"
|
||||
target="_blank"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="shrink-0">{providers.cursor.icon}</span>
|
||||
<span className="flex-1">{providers.cursor.title}</span>
|
||||
<ExternalLinkIcon className="size-4 shrink-0" />
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user