Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9964d8e6c0 | ||
|
|
df33143396 | ||
|
|
571aeaaea2 | ||
|
|
edfea03917 | ||
|
|
81c88cc742 | ||
|
|
99b9390d80 | ||
|
|
23c30521d8 | ||
|
|
e681d610de | ||
|
|
a1fdeded3e | ||
|
|
2051312d12 | ||
|
|
20cb7a76af | ||
|
|
a493aec174 | ||
|
|
3ce3ac8e61 | ||
|
|
91ad64feda | ||
|
|
60b55f9d92 | ||
|
|
3c6c2bf13b | ||
|
|
d4f9375548 | ||
|
|
28b39f547e | ||
|
|
7520f5efa8 | ||
|
|
eb4cdf4b20 | ||
|
|
9f6fc1c3c5 | ||
|
|
dfede9ae6e | ||
|
|
fc45c0c944 | ||
|
|
9d869f784c | ||
|
|
bd244f73af | ||
|
|
dd34556e9c | ||
|
|
f7dd48e60d | ||
|
|
93c779cf48 | ||
|
|
360c04c542 | ||
|
|
529fd57e75 | ||
|
|
faea3777e1 | ||
|
|
a4664e2344 | ||
|
|
cdc1d8a94d | ||
|
|
fdd6d6600f | ||
|
|
9f44cfd595 | ||
|
|
70229b150c | ||
|
|
050ff943a6 | ||
|
|
88b58fd6a0 | ||
|
|
5d67e13df5 | ||
|
|
57d1a60efc | ||
|
|
add81b9739 | ||
|
|
81bdb8e269 | ||
|
|
a563fdd287 | ||
|
|
7c93bf5993 | ||
|
|
6a5a4247c6 | ||
|
|
a39136a2a0 | ||
|
|
9f5b59f336 | ||
|
|
01c125b058 | ||
|
|
d41aa2bc72 | ||
|
|
f45deb37f0 | ||
|
|
e89972a396 | ||
|
|
c3c647a21a | ||
|
|
b79167ce66 | ||
|
|
7ac0a2bc65 | ||
|
|
cb032cff2b | ||
|
|
867a69a751 | ||
|
|
20b8efcc50 | ||
|
|
a86d42149f | ||
|
|
82a36acfe3 | ||
|
|
0793c3f2a3 | ||
|
|
5c860b0d69 | ||
|
|
05bb127a8e | ||
|
|
1bbd84008f | ||
|
|
fdfd4d69d3 | ||
|
|
7f659cce36 | ||
|
|
48fcaa83be | ||
|
|
70c16c4c95 | ||
|
|
c1e1ef6eb5 | ||
|
|
bb155db8b2 | ||
|
|
7c91f668d1 | ||
|
|
1af103d29e | ||
|
|
8a3e581edc | ||
|
|
749e7838a4 | ||
|
|
73b46c2bf9 | ||
|
|
8bd250fb15 | ||
|
|
b1ab641905 | ||
|
|
76e256ed64 | ||
|
|
4f955f2127 | ||
|
|
bbeb579d3a | ||
|
|
f707fb3f8d | ||
|
|
6b98acb7be | ||
|
|
2487b18f62 | ||
|
|
533f64fe26 | ||
|
|
b5c85d3806 | ||
|
|
bcf952bc8a | ||
|
|
a6dc75a44c | ||
|
|
416daca9c6 | ||
|
|
636fe0fb64 | ||
|
|
95e0957d64 | ||
|
|
2eefdae6a9 | ||
|
|
d62746ceb7 |
@@ -0,0 +1,14 @@
|
|||||||
|
name: discord
|
||||||
|
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types: [published] # fires only when a release is published
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
notify:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Send nicely-formatted embed to Discord
|
||||||
|
uses: SethCohen/github-releases-to-discord@v1
|
||||||
|
with:
|
||||||
|
webhook_url: ${{ secrets.DISCORD_WEBHOOK }}
|
||||||
@@ -17,8 +17,7 @@ jobs:
|
|||||||
fetch-depth: 1
|
fetch-depth: 1
|
||||||
|
|
||||||
- name: Run opencode
|
- name: Run opencode
|
||||||
uses: sst/opencode/sdks/github@dev
|
uses: sst/opencode/sdks/github@github-v1
|
||||||
#uses: ./github-actions
|
|
||||||
env:
|
env:
|
||||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
name: publish-github-action
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- run: git fetch --force --tags
|
||||||
|
|
||||||
|
- uses: oven-sh/setup-bun@v2
|
||||||
|
with:
|
||||||
|
bun-version: 1.2.17
|
||||||
|
|
||||||
|
- name: Publish
|
||||||
|
run: |
|
||||||
|
git config --global user.email "opencode@sst.dev"
|
||||||
|
git config --global user.name "opencode"
|
||||||
|
./scripts/publish-github-action.ts
|
||||||
@@ -30,7 +30,8 @@ brew install sst/tap/opencode # macOS
|
|||||||
paru -S opencode-bin # Arch Linux
|
paru -S opencode-bin # Arch Linux
|
||||||
```
|
```
|
||||||
|
|
||||||
> **Note:** Remove versions older than 0.1.x before installing
|
> [!TIP]
|
||||||
|
> Remove versions older than 0.1.x before installing.
|
||||||
|
|
||||||
### Documentation
|
### Documentation
|
||||||
|
|
||||||
@@ -38,24 +39,25 @@ For more info on how to configure opencode [**head over to our docs**](https://o
|
|||||||
|
|
||||||
### Contributing
|
### Contributing
|
||||||
|
|
||||||
WE DO NOT ACCEPT PRs FOR CORE FEATURES
|
|
||||||
|
|
||||||
opencode is an opinionated tool so any fundamental feature needs to go through a
|
opencode is an opinionated tool so any fundamental feature needs to go through a
|
||||||
design process with the core team.
|
design process with the core team.
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> We do not accept PRs for core features.
|
||||||
|
|
||||||
However we still merge a ton of PRs - you can contribute:
|
However we still merge a ton of PRs - you can contribute:
|
||||||
|
|
||||||
- bug fixes
|
- Bug fixes
|
||||||
- improvements to LLM performance
|
- Improvements to LLM performance
|
||||||
- support for new providers
|
- Support for new providers
|
||||||
- fixes for env specific quirks
|
- Fixes for env specific quirks
|
||||||
- missing standard behavior
|
- Missing standard behavior
|
||||||
- documentation
|
- Documentation
|
||||||
|
|
||||||
Take a look at the git history to see what kind of PRs we end up merging.
|
Take a look at the git history to see what kind of PRs we end up merging.
|
||||||
|
|
||||||
> **Note**: If you do not follow the above guidelines we might close your PR
|
> [!NOTE]
|
||||||
> that you worked really hard on.
|
> If you do not follow the above guidelines we might close your PR.
|
||||||
|
|
||||||
To run opencode locally you need.
|
To run opencode locally you need.
|
||||||
|
|
||||||
|
|||||||
@@ -1,18 +1,21 @@
|
|||||||
# Download Stats
|
# Download Stats
|
||||||
|
|
||||||
| Date | GitHub Downloads | npm Downloads | Total |
|
| Date | GitHub Downloads | npm Downloads | Total |
|
||||||
| ---------- | ---------------- | --------------- | ----------------- |
|
| ---------- | ---------------- | ---------------- | ----------------- |
|
||||||
| 2025-06-29 | 18,789 (+0) | 39,420 (+0) | 58,209 (+0) |
|
| 2025-06-29 | 18,789 (+0) | 39,420 (+0) | 58,209 (+0) |
|
||||||
| 2025-06-30 | 20,127 (+1,338) | 41,059 (+1,639) | 61,186 (+2,977) |
|
| 2025-06-30 | 20,127 (+1,338) | 41,059 (+1,639) | 61,186 (+2,977) |
|
||||||
| 2025-07-01 | 22,108 (+1,981) | 43,745 (+2,686) | 65,853 (+4,667) |
|
| 2025-07-01 | 22,108 (+1,981) | 43,745 (+2,686) | 65,853 (+4,667) |
|
||||||
| 2025-07-02 | 24,814 (+2,706) | 46,168 (+2,423) | 70,982 (+5,129) |
|
| 2025-07-02 | 24,814 (+2,706) | 46,168 (+2,423) | 70,982 (+5,129) |
|
||||||
| 2025-07-03 | 27,834 (+3,020) | 49,955 (+3,787) | 77,789 (+6,807) |
|
| 2025-07-03 | 27,834 (+3,020) | 49,955 (+3,787) | 77,789 (+6,807) |
|
||||||
| 2025-07-04 | 30,608 (+2,774) | 54,758 (+4,803) | 85,366 (+7,577) |
|
| 2025-07-04 | 30,608 (+2,774) | 54,758 (+4,803) | 85,366 (+7,577) |
|
||||||
| 2025-07-05 | 32,524 (+1,916) | 58,371 (+3,613) | 90,895 (+5,529) |
|
| 2025-07-05 | 32,524 (+1,916) | 58,371 (+3,613) | 90,895 (+5,529) |
|
||||||
| 2025-07-06 | 33,766 (+1,242) | 59,694 (+1,323) | 93,460 (+2,565) |
|
| 2025-07-06 | 33,766 (+1,242) | 59,694 (+1,323) | 93,460 (+2,565) |
|
||||||
| 2025-07-08 | 38,052 (+4,286) | 64,468 (+4,774) | 102,520 (+9,060) |
|
| 2025-07-08 | 38,052 (+4,286) | 64,468 (+4,774) | 102,520 (+9,060) |
|
||||||
| 2025-07-10 | 43,796 (+5,744) | 71,402 (+6,934) | 115,198 (+12,678) |
|
| 2025-07-10 | 43,796 (+5,744) | 71,402 (+6,934) | 115,198 (+12,678) |
|
||||||
| 2025-07-11 | 46,982 (+3,186) | 77,462 (+6,060) | 124,444 (+9,246) |
|
| 2025-07-11 | 46,982 (+3,186) | 77,462 (+6,060) | 124,444 (+9,246) |
|
||||||
| 2025-07-12 | 49,302 (+2,320) | 82,177 (+4,715) | 131,479 (+7,035) |
|
| 2025-07-12 | 49,302 (+2,320) | 82,177 (+4,715) | 131,479 (+7,035) |
|
||||||
| 2025-07-13 | 50,803 (+1,501) | 86,394 (+4,217) | 137,197 (+5,718) |
|
| 2025-07-13 | 50,803 (+1,501) | 86,394 (+4,217) | 137,197 (+5,718) |
|
||||||
| 2025-07-14 | 53,283 (+2,480) | 87,860 (+1,466) | 141,143 (+3,946) |
|
| 2025-07-14 | 53,283 (+2,480) | 87,860 (+1,466) | 141,143 (+3,946) |
|
||||||
|
| 2025-07-15 | 57,590 (+4,307) | 91,036 (+3,176) | 148,626 (+7,483) |
|
||||||
|
| 2025-07-16 | 62,313 (+4,723) | 95,258 (+4,222) | 157,571 (+8,945) |
|
||||||
|
| 2025-07-17 | 66,684 (+4,371) | 100,048 (+4,790) | 166,732 (+9,161) |
|
||||||
|
|||||||
+2
-4
@@ -18,7 +18,7 @@
|
|||||||
"typescript": "5.8.2",
|
"typescript": "5.8.2",
|
||||||
"@types/node": "22.13.9",
|
"@types/node": "22.13.9",
|
||||||
"zod": "3.25.49",
|
"zod": "3.25.49",
|
||||||
"ai": "5.0.0-beta.15"
|
"ai": "5.0.0-beta.21"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -39,7 +39,5 @@
|
|||||||
"protobufjs",
|
"protobufjs",
|
||||||
"sharp"
|
"sharp"
|
||||||
],
|
],
|
||||||
"patchedDependencies": {
|
"patchedDependencies": {}
|
||||||
"ai@4.3.16": "patches/ai@4.3.16.patch"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -232,6 +232,9 @@ export default {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Used by the GitHub action to get GitHub installation access token given the OIDC token
|
||||||
|
*/
|
||||||
if (request.method === "POST" && method === "exchange_github_app_token") {
|
if (request.method === "POST" && method === "exchange_github_app_token") {
|
||||||
const EXPECTED_AUDIENCE = "opencode-github-action"
|
const EXPECTED_AUDIENCE = "opencode-github-action"
|
||||||
const GITHUB_ISSUER = "https://token.actions.githubusercontent.com"
|
const GITHUB_ISSUER = "https://token.actions.githubusercontent.com"
|
||||||
@@ -285,6 +288,38 @@ export default {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Used by the opencode CLI to check if the GitHub app is installed
|
||||||
|
*/
|
||||||
|
if (request.method === "GET" && method === "get_github_app_installation") {
|
||||||
|
const owner = url.searchParams.get("owner")
|
||||||
|
const repo = url.searchParams.get("repo")
|
||||||
|
|
||||||
|
const auth = createAppAuth({
|
||||||
|
appId: Resource.GITHUB_APP_ID.value,
|
||||||
|
privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
|
||||||
|
})
|
||||||
|
const appAuth = await auth({ type: "app" })
|
||||||
|
|
||||||
|
// Lookup installation
|
||||||
|
const octokit = new Octokit({ auth: appAuth.token })
|
||||||
|
let installation
|
||||||
|
try {
|
||||||
|
const ret = await octokit.apps.getRepoInstallation({ owner, repo })
|
||||||
|
installation = ret.data
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof Error && err.message.includes("Not Found")) {
|
||||||
|
// not installed
|
||||||
|
} else {
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response(JSON.stringify({ installation }), {
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return new Response("Not Found", { status: 404 })
|
return new Response("Not Found", { status: 404 })
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,15 +17,18 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ai-sdk/amazon-bedrock": "2.2.10",
|
"@ai-sdk/amazon-bedrock": "2.2.10",
|
||||||
"@ai-sdk/anthropic": "1.2.12",
|
"@ai-sdk/anthropic": "1.2.12",
|
||||||
|
"@standard-schema/spec": "1.0.0",
|
||||||
"@tsconfig/bun": "1.0.7",
|
"@tsconfig/bun": "1.0.7",
|
||||||
"@types/bun": "latest",
|
"@types/bun": "latest",
|
||||||
"@types/turndown": "5.0.5",
|
"@types/turndown": "5.0.5",
|
||||||
"@types/yargs": "17.0.33",
|
"@types/yargs": "17.0.33",
|
||||||
"typescript": "catalog:",
|
"typescript": "catalog:",
|
||||||
|
"vscode-languageserver-types": "3.17.5",
|
||||||
"zod-to-json-schema": "3.24.5"
|
"zod-to-json-schema": "3.24.5"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@clack/prompts": "0.11.0",
|
"@clack/prompts": "0.11.0",
|
||||||
|
"@hono/zod-validator": "0.4.2",
|
||||||
"@modelcontextprotocol/sdk": "1.15.1",
|
"@modelcontextprotocol/sdk": "1.15.1",
|
||||||
"@openauthjs/openauth": "0.4.3",
|
"@openauthjs/openauth": "0.4.3",
|
||||||
"ai": "catalog:",
|
"ai": "catalog:",
|
||||||
@@ -40,6 +43,7 @@
|
|||||||
"vscode-jsonrpc": "8.2.1",
|
"vscode-jsonrpc": "8.2.1",
|
||||||
"xdg-basedir": "5.1.0",
|
"xdg-basedir": "5.1.0",
|
||||||
"yargs": "18.0.0",
|
"yargs": "18.0.0",
|
||||||
"zod": "catalog:"
|
"zod": "catalog:",
|
||||||
|
"zod-openapi": "4.1.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,20 +66,18 @@ export namespace BunProc {
|
|||||||
return result
|
return result
|
||||||
})
|
})
|
||||||
if (parsed.dependencies[pkg] === version) return mod
|
if (parsed.dependencies[pkg] === version) return mod
|
||||||
await BunProc.run(
|
|
||||||
[
|
// Build command arguments
|
||||||
"add",
|
const args = ["add", "--force", "--exact", "--cwd", Global.Path.cache, pkg + "@" + version]
|
||||||
"--force",
|
|
||||||
"--exact",
|
// Let Bun handle registry resolution:
|
||||||
"--cwd",
|
// - If .npmrc files exist, Bun will use them automatically
|
||||||
Global.Path.cache,
|
// - If no .npmrc files exist, Bun will default to https://registry.npmjs.org
|
||||||
"--registry=https://registry.npmjs.org",
|
log.info("installing package using Bun's default registry resolution", { pkg, version })
|
||||||
pkg + "@" + version,
|
|
||||||
],
|
await BunProc.run(args, {
|
||||||
{
|
cwd: Global.Path.cache,
|
||||||
cwd: Global.Path.cache,
|
}).catch((e) => {
|
||||||
},
|
|
||||||
).catch((e) => {
|
|
||||||
throw new InstallFailedError(
|
throw new InstallFailedError(
|
||||||
{ pkg, version },
|
{ pkg, version },
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -120,7 +120,7 @@ export const AuthLoginCommand = cmd({
|
|||||||
|
|
||||||
if (provider === "amazon-bedrock") {
|
if (provider === "amazon-bedrock") {
|
||||||
prompts.log.info(
|
prompts.log.info(
|
||||||
"Amazon bedrock can be configured with standard AWS environment variables like AWS_PROFILE or AWS_ACCESS_KEY_ID",
|
"Amazon bedrock can be configured with standard AWS environment variables like AWS_BEARER_TOKEN_BEDROCK, AWS_PROFILE or AWS_ACCESS_KEY_ID",
|
||||||
)
|
)
|
||||||
prompts.outro("Done")
|
prompts.outro("Done")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
import { $ } from "bun"
|
||||||
|
import path from "path"
|
||||||
|
import { exec } from "child_process"
|
||||||
|
import * as prompts from "@clack/prompts"
|
||||||
|
import { map, pipe, sortBy, values } from "remeda"
|
||||||
|
import { UI } from "../ui"
|
||||||
|
import { cmd } from "./cmd"
|
||||||
|
import { ModelsDev } from "../../provider/models"
|
||||||
|
import { App } from "../../app/app"
|
||||||
|
|
||||||
|
const WORKFLOW_FILE = ".github/workflows/opencode.yml"
|
||||||
|
|
||||||
|
export const InstallGithubCommand = cmd({
|
||||||
|
command: "install-github",
|
||||||
|
describe: "install the GitHub agent",
|
||||||
|
async handler() {
|
||||||
|
await App.provide({ cwd: process.cwd() }, async () => {
|
||||||
|
UI.empty()
|
||||||
|
prompts.intro("Install GitHub agent")
|
||||||
|
const app = await getAppInfo()
|
||||||
|
await installGitHubApp()
|
||||||
|
|
||||||
|
const providers = await ModelsDev.get()
|
||||||
|
const provider = await promptProvider()
|
||||||
|
const model = await promptModel()
|
||||||
|
//const key = await promptKey()
|
||||||
|
|
||||||
|
await addWorkflowFiles()
|
||||||
|
printNextSteps()
|
||||||
|
|
||||||
|
function printNextSteps() {
|
||||||
|
let step2
|
||||||
|
if (provider === "amazon-bedrock") {
|
||||||
|
step2 =
|
||||||
|
"Configure OIDC in AWS - https://docs.github.com/en/actions/how-tos/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services"
|
||||||
|
} else {
|
||||||
|
const url = `https://github.com/organizations/${app.owner}/settings/secrets/actions`
|
||||||
|
const env = providers[provider].env
|
||||||
|
const envStr =
|
||||||
|
env.length === 1
|
||||||
|
? `\`${env[0]}\` secret`
|
||||||
|
: `\`${[env.slice(0, -1).join("\`, \`"), ...env.slice(-1)].join("\` and \`")}\` secrets`
|
||||||
|
step2 = `Add ${envStr} for ${providers[provider].name} - ${url}`
|
||||||
|
}
|
||||||
|
|
||||||
|
prompts.outro(
|
||||||
|
[
|
||||||
|
"Next steps:",
|
||||||
|
` 1. Commit "${WORKFLOW_FILE}" file and push`,
|
||||||
|
` 2. ${step2}`,
|
||||||
|
" 3. Learn how to use the GitHub agent - https://docs.opencode.ai/docs/github/getting-started",
|
||||||
|
].join("\n"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getAppInfo() {
|
||||||
|
const app = App.info()
|
||||||
|
if (!app.git) {
|
||||||
|
prompts.log.error(`Could not find git repository. Please run this command from a git repository.`)
|
||||||
|
throw new UI.CancelledError()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get repo info
|
||||||
|
const info = await $`git remote get-url origin`.quiet().nothrow().text()
|
||||||
|
// match https or git pattern
|
||||||
|
// ie. https://github.com/sst/opencode.git
|
||||||
|
// ie. git@github.com:sst/opencode.git
|
||||||
|
const parsed = info.match(/git@github\.com:(.*)\.git/) ?? info.match(/github\.com\/(.*)\.git/)
|
||||||
|
if (!parsed) {
|
||||||
|
prompts.log.error(`Could not find git repository. Please run this command from a git repository.`)
|
||||||
|
throw new UI.CancelledError()
|
||||||
|
}
|
||||||
|
const [owner, repo] = parsed[1].split("/")
|
||||||
|
return { owner, repo, root: app.path.root }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function promptProvider() {
|
||||||
|
const priority: Record<string, number> = {
|
||||||
|
anthropic: 0,
|
||||||
|
"github-copilot": 1,
|
||||||
|
openai: 2,
|
||||||
|
google: 3,
|
||||||
|
}
|
||||||
|
let provider = await prompts.select({
|
||||||
|
message: "Select provider",
|
||||||
|
maxItems: 8,
|
||||||
|
options: [
|
||||||
|
...pipe(
|
||||||
|
providers,
|
||||||
|
values(),
|
||||||
|
sortBy(
|
||||||
|
(x) => priority[x.id] ?? 99,
|
||||||
|
(x) => x.name ?? x.id,
|
||||||
|
),
|
||||||
|
map((x) => ({
|
||||||
|
label: x.name,
|
||||||
|
value: x.id,
|
||||||
|
hint: priority[x.id] === 0 ? "recommended" : undefined,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
{
|
||||||
|
value: "other",
|
||||||
|
label: "Other",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
|
||||||
|
if (prompts.isCancel(provider)) throw new UI.CancelledError()
|
||||||
|
if (provider === "other") {
|
||||||
|
provider = await prompts.text({
|
||||||
|
message: "Enter provider id",
|
||||||
|
validate: (x) => (x.match(/^[a-z-]+$/) ? undefined : "a-z and hyphens only"),
|
||||||
|
})
|
||||||
|
if (prompts.isCancel(provider)) throw new UI.CancelledError()
|
||||||
|
provider = provider.replace(/^@ai-sdk\//, "")
|
||||||
|
if (prompts.isCancel(provider)) throw new UI.CancelledError()
|
||||||
|
prompts.log.warn(
|
||||||
|
`This only stores a credential for ${provider} - you will need configure it in opencode.json, check the docs for examples.`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return provider
|
||||||
|
}
|
||||||
|
|
||||||
|
async function promptModel() {
|
||||||
|
const providerData = providers[provider]!
|
||||||
|
|
||||||
|
const model = await prompts.select({
|
||||||
|
message: "Select model",
|
||||||
|
maxItems: 8,
|
||||||
|
options: pipe(
|
||||||
|
providerData.models,
|
||||||
|
values(),
|
||||||
|
sortBy((x) => x.name ?? x.id),
|
||||||
|
map((x) => ({
|
||||||
|
label: x.name ?? x.id,
|
||||||
|
value: x.id,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (prompts.isCancel(model)) throw new UI.CancelledError()
|
||||||
|
return model
|
||||||
|
}
|
||||||
|
|
||||||
|
async function installGitHubApp() {
|
||||||
|
const s = prompts.spinner()
|
||||||
|
s.start("Installing GitHub app")
|
||||||
|
|
||||||
|
// Get installation
|
||||||
|
const installation = await getInstallation()
|
||||||
|
if (installation) return s.stop("GitHub app already installed")
|
||||||
|
|
||||||
|
// Open browser
|
||||||
|
const url = "https://github.com/apps/opencode-agent"
|
||||||
|
const command =
|
||||||
|
process.platform === "darwin"
|
||||||
|
? `open "${url}"`
|
||||||
|
: process.platform === "win32"
|
||||||
|
? `start "${url}"`
|
||||||
|
: `xdg-open "${url}"`
|
||||||
|
|
||||||
|
exec(command, (error) => {
|
||||||
|
if (error) {
|
||||||
|
prompts.log.warn(`Could not open browser. Please visit: ${url}`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Wait for installation
|
||||||
|
s.message("Waiting for GitHub app to be installed")
|
||||||
|
const MAX_RETRIES = 60
|
||||||
|
let retries = 0
|
||||||
|
do {
|
||||||
|
const installation = await getInstallation()
|
||||||
|
if (installation) break
|
||||||
|
|
||||||
|
if (retries > MAX_RETRIES) {
|
||||||
|
s.stop(
|
||||||
|
`Failed to detect GitHub app installation. Make sure to install the app for the \`${app.owner}/${app.repo}\` repository.`,
|
||||||
|
)
|
||||||
|
throw new UI.CancelledError()
|
||||||
|
}
|
||||||
|
|
||||||
|
retries++
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1000))
|
||||||
|
} while (true)
|
||||||
|
|
||||||
|
s.stop("Installed GitHub app")
|
||||||
|
|
||||||
|
async function getInstallation() {
|
||||||
|
return await fetch(`https://api.opencode.ai/get_github_app_installation?owner=${app.owner}&repo=${app.repo}`)
|
||||||
|
.then((res) => res.json())
|
||||||
|
.then((data) => data.installation)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addWorkflowFiles() {
|
||||||
|
const envStr =
|
||||||
|
provider === "amazon-bedrock"
|
||||||
|
? ""
|
||||||
|
: `\n env:${providers[provider].env.map((e) => `\n ${e}: \${{ secrets.${e} }}`).join("")}`
|
||||||
|
|
||||||
|
await Bun.write(
|
||||||
|
path.join(app.root, WORKFLOW_FILE),
|
||||||
|
`
|
||||||
|
name: opencode
|
||||||
|
|
||||||
|
on:
|
||||||
|
issue_comment:
|
||||||
|
types: [created]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
opencode:
|
||||||
|
if: startsWith(github.event.comment.body, 'hey opencode')
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 1
|
||||||
|
|
||||||
|
- name: Run opencode
|
||||||
|
uses: sst/opencode/sdks/github@github-v1${envStr}
|
||||||
|
with:
|
||||||
|
model: ${provider}/${model}
|
||||||
|
`.trim(),
|
||||||
|
)
|
||||||
|
|
||||||
|
prompts.log.success(`Added workflow file: "${WORKFLOW_FILE}"`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -124,7 +124,9 @@ export const RunCommand = cmd({
|
|||||||
|
|
||||||
if (part.type === "tool" && part.state.status === "completed") {
|
if (part.type === "tool" && part.state.status === "completed") {
|
||||||
const [tool, color] = TOOL[part.tool] ?? [part.tool, UI.Style.TEXT_INFO_BOLD]
|
const [tool, color] = TOOL[part.tool] ?? [part.tool, UI.Style.TEXT_INFO_BOLD]
|
||||||
printEvent(color, tool, part.state.title || "Unknown")
|
const title =
|
||||||
|
part.state.title || Object.keys(part.state.input).length > 0 ? JSON.stringify(part.state.input) : "Unknown"
|
||||||
|
printEvent(color, tool, title)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (part.type === "text") {
|
if (part.type === "text") {
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ export namespace Config {
|
|||||||
const os = await import("os")
|
const os = await import("os")
|
||||||
result.username = os.userInfo().username
|
result.username = os.userInfo().username
|
||||||
}
|
}
|
||||||
|
if (!result.layout) {
|
||||||
|
result.layout = "auto"
|
||||||
|
}
|
||||||
|
|
||||||
log.info("loaded", result)
|
log.info("loaded", result)
|
||||||
|
|
||||||
@@ -57,6 +60,7 @@ export namespace Config {
|
|||||||
type: z.literal("remote").describe("Type of MCP server connection"),
|
type: z.literal("remote").describe("Type of MCP server connection"),
|
||||||
url: z.string().describe("URL of the remote MCP server"),
|
url: z.string().describe("URL of the remote MCP server"),
|
||||||
enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
|
enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
|
||||||
|
headers: z.record(z.string(), z.string()).optional().describe("Headers to send with the request"),
|
||||||
})
|
})
|
||||||
.strict()
|
.strict()
|
||||||
.openapi({
|
.openapi({
|
||||||
@@ -81,8 +85,10 @@ export namespace Config {
|
|||||||
.object({
|
.object({
|
||||||
leader: z.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),
|
leader: z.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),
|
||||||
app_help: z.string().optional().default("<leader>h").describe("Show help dialog"),
|
app_help: z.string().optional().default("<leader>h").describe("Show help dialog"),
|
||||||
switch_mode: z.string().optional().default("tab").describe("Switch mode"),
|
switch_mode: z.string().optional().default("tab").describe("Next mode"),
|
||||||
|
switch_mode_reverse: z.string().optional().default("shift+tab").describe("Previous Mode"),
|
||||||
editor_open: z.string().optional().default("<leader>e").describe("Open external editor"),
|
editor_open: z.string().optional().default("<leader>e").describe("Open external editor"),
|
||||||
|
session_export: z.string().optional().default("<leader>x").describe("Export session to editor"),
|
||||||
session_new: z.string().optional().default("<leader>n").describe("Create a new session"),
|
session_new: z.string().optional().default("<leader>n").describe("Create a new session"),
|
||||||
session_list: z.string().optional().default("<leader>l").describe("List all sessions"),
|
session_list: z.string().optional().default("<leader>l").describe("List all sessions"),
|
||||||
session_share: z.string().optional().default("<leader>s").describe("Share current session"),
|
session_share: z.string().optional().default("<leader>s").describe("Share current session"),
|
||||||
@@ -123,15 +129,22 @@ export namespace Config {
|
|||||||
ref: "KeybindsConfig",
|
ref: "KeybindsConfig",
|
||||||
})
|
})
|
||||||
|
|
||||||
|
export const Layout = z.enum(["auto", "stretch"]).openapi({
|
||||||
|
ref: "LayoutConfig",
|
||||||
|
})
|
||||||
|
export type Layout = z.infer<typeof Layout>
|
||||||
|
|
||||||
export const Info = z
|
export const Info = z
|
||||||
.object({
|
.object({
|
||||||
$schema: z.string().optional().describe("JSON schema reference for configuration validation"),
|
$schema: z.string().optional().describe("JSON schema reference for configuration validation"),
|
||||||
theme: z.string().optional().describe("Theme name to use for the interface"),
|
theme: z.string().optional().describe("Theme name to use for the interface"),
|
||||||
keybinds: Keybinds.optional().describe("Custom keybind configurations"),
|
keybinds: Keybinds.optional().describe("Custom keybind configurations"),
|
||||||
share: z
|
share: z
|
||||||
.enum(["auto", "disabled"])
|
.enum(["manual", "auto", "disabled"])
|
||||||
.optional()
|
.optional()
|
||||||
.describe("Control sharing behavior: 'auto' enables automatic sharing, 'disabled' disables all sharing"),
|
.describe(
|
||||||
|
"Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing",
|
||||||
|
),
|
||||||
autoshare: z
|
autoshare: z
|
||||||
.boolean()
|
.boolean()
|
||||||
.optional()
|
.optional()
|
||||||
@@ -149,7 +162,8 @@ export namespace Config {
|
|||||||
plan: Mode.optional(),
|
plan: Mode.optional(),
|
||||||
})
|
})
|
||||||
.catchall(Mode)
|
.catchall(Mode)
|
||||||
.optional(),
|
.optional()
|
||||||
|
.describe("Modes configuration, see https://opencode.ai/docs/modes"),
|
||||||
log_level: Log.Level.optional().describe("Minimum log level to write to log files"),
|
log_level: Log.Level.optional().describe("Minimum log level to write to log files"),
|
||||||
provider: z
|
provider: z
|
||||||
.record(
|
.record(
|
||||||
@@ -162,6 +176,7 @@ export namespace Config {
|
|||||||
.describe("Custom provider configurations and model overrides"),
|
.describe("Custom provider configurations and model overrides"),
|
||||||
mcp: z.record(z.string(), Mcp).optional().describe("MCP (Model Context Protocol) server configurations"),
|
mcp: z.record(z.string(), Mcp).optional().describe("MCP (Model Context Protocol) server configurations"),
|
||||||
instructions: z.array(z.string()).optional().describe("Additional instruction files or patterns to include"),
|
instructions: z.array(z.string()).optional().describe("Additional instruction files or patterns to include"),
|
||||||
|
layout: Layout.optional().describe("Layout to use for the TUI"),
|
||||||
experimental: z
|
experimental: z
|
||||||
.object({
|
.object({
|
||||||
hook: z
|
hook: z
|
||||||
|
|||||||
@@ -105,7 +105,29 @@ export const ruff: Info = {
|
|||||||
command: ["ruff", "format", "$FILE"],
|
command: ["ruff", "format", "$FILE"],
|
||||||
extensions: [".py", ".pyi"],
|
extensions: [".py", ".pyi"],
|
||||||
async enabled() {
|
async enabled() {
|
||||||
return Bun.which("ruff") !== null
|
if (!Bun.which("ruff")) return false
|
||||||
|
const app = App.info()
|
||||||
|
const configs = ["pyproject.toml", "ruff.toml", ".ruff.toml"]
|
||||||
|
for (const config of configs) {
|
||||||
|
const found = await Filesystem.findUp(config, app.path.cwd, app.path.root)
|
||||||
|
if (found.length > 0) {
|
||||||
|
if (config === "pyproject.toml") {
|
||||||
|
const content = await Bun.file(found[0]).text()
|
||||||
|
if (content.includes("[tool.ruff]")) return true
|
||||||
|
} else {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const deps = ["requirements.txt", "pyproject.toml", "Pipfile"]
|
||||||
|
for (const dep of deps) {
|
||||||
|
const found = await Filesystem.findUp(dep, app.path.cwd, app.path.root)
|
||||||
|
if (found.length > 0) {
|
||||||
|
const content = await Bun.file(found[0]).text()
|
||||||
|
if (content.includes("ruff")) return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { TuiCommand } from "./cli/cmd/tui"
|
|||||||
import { DebugCommand } from "./cli/cmd/debug"
|
import { DebugCommand } from "./cli/cmd/debug"
|
||||||
import { StatsCommand } from "./cli/cmd/stats"
|
import { StatsCommand } from "./cli/cmd/stats"
|
||||||
import { McpCommand } from "./cli/cmd/mcp"
|
import { McpCommand } from "./cli/cmd/mcp"
|
||||||
|
import { InstallGithubCommand } from "./cli/cmd/install-github"
|
||||||
|
|
||||||
const cancel = new AbortController()
|
const cancel = new AbortController()
|
||||||
|
|
||||||
@@ -76,6 +77,7 @@ const cli = yargs(hideBin(process.argv))
|
|||||||
.command(ServeCommand)
|
.command(ServeCommand)
|
||||||
.command(ModelsCommand)
|
.command(ModelsCommand)
|
||||||
.command(StatsCommand)
|
.command(StatsCommand)
|
||||||
|
.command(InstallGithubCommand)
|
||||||
.fail((msg) => {
|
.fail((msg) => {
|
||||||
if (msg.startsWith("Unknown argument") || msg.startsWith("Not enough non-option arguments")) {
|
if (msg.startsWith("Unknown argument") || msg.startsWith("Not enough non-option arguments")) {
|
||||||
cli.showHelp("log")
|
cli.showHelp("log")
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ export namespace MCP {
|
|||||||
transport: {
|
transport: {
|
||||||
type: "sse",
|
type: "sse",
|
||||||
url: mcp.url,
|
url: mcp.url,
|
||||||
|
headers: mcp.headers,
|
||||||
},
|
},
|
||||||
}).catch(() => {})
|
}).catch(() => {})
|
||||||
if (!client) {
|
if (!client) {
|
||||||
|
|||||||
@@ -139,7 +139,8 @@ export namespace Provider {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"amazon-bedrock": async () => {
|
"amazon-bedrock": async () => {
|
||||||
if (!process.env["AWS_PROFILE"] && !process.env["AWS_ACCESS_KEY_ID"]) return { autoload: false }
|
if (!process.env["AWS_PROFILE"] && !process.env["AWS_ACCESS_KEY_ID"] && !process.env["AWS_BEARER_TOKEN_BEDROCK"])
|
||||||
|
return { autoload: false }
|
||||||
|
|
||||||
const region = process.env["AWS_REGION"] ?? "us-east-1"
|
const region = process.env["AWS_REGION"] ?? "us-east-1"
|
||||||
|
|
||||||
@@ -271,14 +272,20 @@ export namespace Provider {
|
|||||||
reasoning: model.reasoning ?? existing?.reasoning ?? false,
|
reasoning: model.reasoning ?? existing?.reasoning ?? false,
|
||||||
temperature: model.temperature ?? existing?.temperature ?? false,
|
temperature: model.temperature ?? existing?.temperature ?? false,
|
||||||
tool_call: model.tool_call ?? existing?.tool_call ?? true,
|
tool_call: model.tool_call ?? existing?.tool_call ?? true,
|
||||||
cost: {
|
cost:
|
||||||
...existing?.cost,
|
!model.cost && !existing?.cost
|
||||||
...model.cost,
|
? {
|
||||||
input: 0,
|
input: 0,
|
||||||
output: 0,
|
output: 0,
|
||||||
cache_read: 0,
|
cache_read: 0,
|
||||||
cache_write: 0,
|
cache_write: 0,
|
||||||
},
|
}
|
||||||
|
: {
|
||||||
|
cache_read: 0,
|
||||||
|
cache_write: 0,
|
||||||
|
...existing?.cost,
|
||||||
|
...model.cost,
|
||||||
|
},
|
||||||
options: {
|
options: {
|
||||||
...existing?.options,
|
...existing?.options,
|
||||||
...model.options,
|
...model.options,
|
||||||
@@ -408,6 +415,17 @@ export namespace Provider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getSmallModel(providerID: string) {
|
||||||
|
const provider = await state().then((state) => state.providers[providerID])
|
||||||
|
if (!provider) return
|
||||||
|
const priority = ["3-5-haiku", "3.5-haiku", "gemini-2.5-flash"]
|
||||||
|
for (const item of priority) {
|
||||||
|
for (const model of Object.keys(provider.info.models)) {
|
||||||
|
if (model.includes(item)) return getModel(providerID, model)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const priority = ["gemini-2.5-pro-preview", "codex-mini", "claude-sonnet-4"]
|
const priority = ["gemini-2.5-pro-preview", "codex-mini", "claude-sonnet-4"]
|
||||||
export function sort(models: ModelsDev.Model[]) {
|
export function sort(models: ModelsDev.Model[]) {
|
||||||
return sortBy(
|
return sortBy(
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
|
|
||||||
import PROMPT_INITIALIZE from "../session/prompt/initialize.txt"
|
import PROMPT_INITIALIZE from "../session/prompt/initialize.txt"
|
||||||
import PROMPT_PLAN from "../session/prompt/plan.txt"
|
import PROMPT_PLAN from "../session/prompt/plan.txt"
|
||||||
|
import PROMPT_ANTHROPIC_SPOOF from "../session/prompt/anthropic_spoof.txt"
|
||||||
|
|
||||||
import { App } from "../app/app"
|
import { App } from "../app/app"
|
||||||
import { Bus } from "../bus"
|
import { Bus } from "../bus"
|
||||||
@@ -504,9 +505,10 @@ export namespace Session {
|
|||||||
})
|
})
|
||||||
|
|
||||||
if (msgs.length === 0 && !session.parentID) {
|
if (msgs.length === 0 && !session.parentID) {
|
||||||
|
const small = (await Provider.getSmallModel(input.providerID)) ?? model
|
||||||
generateText({
|
generateText({
|
||||||
maxOutputTokens: input.providerID === "google" ? 1024 : 20,
|
maxOutputTokens: input.providerID === "google" ? 1024 : 20,
|
||||||
providerOptions: model.info.options,
|
providerOptions: small.info.options,
|
||||||
messages: [
|
messages: [
|
||||||
...SystemPrompt.title(input.providerID).map(
|
...SystemPrompt.title(input.providerID).map(
|
||||||
(x): ModelMessage => ({
|
(x): ModelMessage => ({
|
||||||
@@ -528,7 +530,7 @@ export namespace Session {
|
|||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
],
|
],
|
||||||
model: model.language,
|
model: small.language,
|
||||||
})
|
})
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
if (result.text)
|
if (result.text)
|
||||||
@@ -545,7 +547,8 @@ export namespace Session {
|
|||||||
msgs.push({ info: userMsg, parts: userParts })
|
msgs.push({ info: userMsg, parts: userParts })
|
||||||
|
|
||||||
const mode = await Mode.get(input.mode ?? "build")
|
const mode = await Mode.get(input.mode ?? "build")
|
||||||
let system = mode.prompt ? [mode.prompt] : SystemPrompt.provider(input.providerID, input.modelID)
|
let system = input.providerID === "anthropic" ? [PROMPT_ANTHROPIC_SPOOF.trim()] : []
|
||||||
|
system.push(...(mode.prompt ? [mode.prompt] : SystemPrompt.provider(input.modelID)))
|
||||||
system.push(...(await SystemPrompt.environment()))
|
system.push(...(await SystemPrompt.environment()))
|
||||||
system.push(...(await SystemPrompt.custom()))
|
system.push(...(await SystemPrompt.custom()))
|
||||||
// max 2 system prompt messages for caching purposes
|
// max 2 system prompt messages for caching purposes
|
||||||
@@ -1012,6 +1015,7 @@ export namespace Session {
|
|||||||
|
|
||||||
const processor = createProcessor(next, model.info)
|
const processor = createProcessor(next, model.info)
|
||||||
const stream = streamText({
|
const stream = streamText({
|
||||||
|
maxRetries: 10,
|
||||||
abortSignal: abort.signal,
|
abortSignal: abort.signal,
|
||||||
model: model.language,
|
model: model.language,
|
||||||
messages: [
|
messages: [
|
||||||
|
|||||||
@@ -88,7 +88,10 @@ export namespace MessageV2 {
|
|||||||
export const SnapshotPart = PartBase.extend({
|
export const SnapshotPart = PartBase.extend({
|
||||||
type: z.literal("snapshot"),
|
type: z.literal("snapshot"),
|
||||||
snapshot: z.string(),
|
snapshot: z.string(),
|
||||||
|
}).openapi({
|
||||||
|
ref: "SnapshotPart",
|
||||||
})
|
})
|
||||||
|
export type SnapshotPart = z.infer<typeof SnapshotPart>
|
||||||
|
|
||||||
export const TextPart = PartBase.extend({
|
export const TextPart = PartBase.extend({
|
||||||
type: z.literal("text"),
|
type: z.literal("text"),
|
||||||
|
|||||||
@@ -30,7 +30,6 @@ export namespace Mode {
|
|||||||
write: false,
|
write: false,
|
||||||
edit: false,
|
edit: false,
|
||||||
patch: false,
|
patch: false,
|
||||||
bash: false,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,95 +1,117 @@
|
|||||||
You are an agent known as opencode - please keep going until the user’s query is completely resolved, before ending your turn and yielding back to the user.
|
You are opencode, an autonomous agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user.
|
||||||
|
|
||||||
Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough.
|
Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough.
|
||||||
|
|
||||||
You MUST iterate and keep going until the problem is solved.
|
You MUST iterate and keep going until the problem is solved.
|
||||||
|
|
||||||
I want you to fully solve this autonomously before coming back to me.
|
You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me.
|
||||||
|
|
||||||
Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.
|
Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Use the TodoWrite and TodoRead tools to track and manage steps. Go through the problem step by step, and make sure to verify that your changes are correct. Once each step is finished mark it as completed with the TodoWrite tool. NEVER end your turn without having truly and completely solved the problem, use the TodoRead tool to make sure all steps are complete, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn. If a step is impossible to complete, mark it as cancelled using the TodoWrite tool.
|
||||||
|
|
||||||
Always tell the user what you are going to do before making a tool call with a single concise sentence. This will help them understand what you are doing and why.
|
THE PROBLEM CAN NOT BE SOLVED WITHOUT EXTENSIVE INTERNET RESEARCH.
|
||||||
|
|
||||||
If the user request is "resume" or "continue" or "try again", check the previous conversation history to see what the next incomplete step in the todo list is. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all items are checked off. Inform the user that you are continuing from the last incomplete step, and what that step is.
|
You must use the webfetch tool to recursively gather all information from URLs provided to you by the user, as well as any links you find in the content of those pages.
|
||||||
|
|
||||||
Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.
|
Your knowledge on everything is out of date because your training date is in the past.
|
||||||
|
|
||||||
You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
|
You CANNOT successfully complete this task without using Bing to verify your understanding of third party packages and dependencies is up to date. You must use the webfetch tool to search bing for how to properly use libraries, packages, frameworks, dependencies, etc. every single time you install or implement one. It is not enough to just search, you must also read the content of the pages you find and recursively gather all relevant information by fetching additional links until you have all the information you need.
|
||||||
|
|
||||||
|
If the user request is "resume" or "continue" or "try again",use the TodoRead tool to find the next pending step. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all steps are marked as complete or cancelled. Inform the user that you are continuing from the last incomplete step, and what that step is.
|
||||||
|
|
||||||
|
Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Use the sequential thinking tool if available. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, update the plan and iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; run the build, and verify that the changes you made actually build; make sure you handle all edge cases, and run existing tests if they are provided.
|
||||||
|
|
||||||
|
You MUST plan extensively before each tool call, and reflect extensively on the outcomes of the previous tool calls. DO NOT do this entire process by making tool calls only, as this can impair your ability to solve the problem and think insightfully.
|
||||||
|
|
||||||
|
You MUST keep working until the problem is completely solved, and all steps in the todo list are complete. Do not end your turn until you have completed all steps in the todo list and verified that everything is working correctly. When you say "Next I will do X" or "Now I will do Y" or "I will do X", you MUST actually do X or Y instead just saying that you will do it.
|
||||||
|
|
||||||
|
You MUST use the ToolRead tool to verify that all steps are complete or cancelled before ending your turn. If any steps are incomplete, you MUST continue working on them until they are all complete.
|
||||||
|
|
||||||
|
You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input.
|
||||||
|
|
||||||
# Workflow
|
# Workflow
|
||||||
|
1. Fetch any URL's provided by the user using the `webfetch` tool.
|
||||||
1. Understand the problem deeply. Carefully read the issue and think critically about what is required.
|
2. Understand the problem deeply. Carefully read the issue and think critically about what is required. Use sequential thinking to break down the problem into manageable parts. Consider the following:
|
||||||
2. Investigate the codebase. Explore relevant files, search for key functions, and gather context.
|
- What is the expected behavior?
|
||||||
3. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps. Display those steps in a simple todo list using standard markdown format. Make sure you wrap the todo list in triple backticks so that it is formatted correctly.
|
- What are the edge cases?
|
||||||
4. Implement the fix incrementally. Make small, testable code changes.
|
- What are the potential pitfalls?
|
||||||
5. Debug as needed. Use debugging techniques to isolate and resolve issues.
|
- How does this fit into the larger context of the codebase?
|
||||||
6. Test frequently. Run tests after each change to verify correctness.
|
- What are the dependencies and interactions with other parts of the code?
|
||||||
7. Iterate until the root cause is fixed and all tests pass.
|
3. Investigate the codebase. Explore relevant files, search for key functions, and gather context.
|
||||||
8. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete.
|
4. Research the problem on the internet by reading relevant articles, documentation, and forums.
|
||||||
|
5. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps. Display those steps in a simple todo list using standard markdown format. Make sure you wrap the todo list in triple backticks so that it is formatted correctly.
|
||||||
|
6. Implement the fix incrementally. Make small, testable code changes.
|
||||||
|
7. Debug as needed. Use debugging techniques to isolate and resolve issues.
|
||||||
|
8. Test frequently. Run tests after each change to verify correctness.
|
||||||
|
9. Iterate until the root cause is fixed and all tests pass.
|
||||||
|
10. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete.
|
||||||
|
|
||||||
Refer to the detailed sections below for more information on each step.
|
Refer to the detailed sections below for more information on each step.
|
||||||
|
|
||||||
## 1. Deeply Understand the Problem
|
## 1. Fetch Provided URLs
|
||||||
Carefully read the issue and think hard about a plan to solve it before coding.
|
- If the user provides a URL, use the `webfetch` tool to retrieve the content of the provided URL.
|
||||||
|
- After fetching, review the content returned by the fetch tool.
|
||||||
|
- If you find any additional URLs or links that are relevant, use the `webfetch` tool again to retrieve those links.
|
||||||
|
- Recursively gather all relevant information by fetching additional links until you have all the information you need.
|
||||||
|
|
||||||
## 2. Codebase Investigation
|
## 2. Deeply Understand the Problem
|
||||||
|
Carefully read the issue and think hard about a plan to solve it before coding. Use the sequential thinking tool if available.
|
||||||
|
|
||||||
|
## 3. Codebase Investigation
|
||||||
- Explore relevant files and directories.
|
- Explore relevant files and directories.
|
||||||
- Search for key functions, classes, or variables related to the issue.
|
- Search for key functions, classes, or variables related to the issue.
|
||||||
- Read and understand relevant code snippets.
|
- Read and understand relevant code snippets.
|
||||||
- Identify the root cause of the problem.
|
- Identify the root cause of the problem.
|
||||||
- Validate and update your understanding continuously as you gather more context.
|
- Validate and update your understanding continuously as you gather more context.
|
||||||
|
|
||||||
## 3. Fetch Provided URLs
|
## 4. Internet Research
|
||||||
- If the user provides a URL, use the `functions.fetch_webpage` tool to retrieve the content of the provided URL.
|
- Use the `webfetch` tool to search bing by fetching the URL `https://www.bing.com/search?q=your+search+query`.
|
||||||
- After fetching, review the content returned by the fetch tool.
|
- After fetching, review the content returned by the fetch tool.
|
||||||
- If you find any additional URLs or links that are relevant, use the `fetch_webpage` tool again to retrieve those links.
|
- If you find any additional URLs or links that are relevant, use the `webfetch` tool again to retrieve those links.
|
||||||
- Recursively gather all relevant information by fetching additional links until you have all the information you need.
|
- Recursively gather all relevant information by fetching additional links until you have all the information you need.
|
||||||
|
|
||||||
## 4. Develop a Detailed Plan
|
## 5. Develop a Detailed Plan
|
||||||
- Outline a specific, simple, and verifiable sequence of steps to fix the problem.
|
- Outline a specific, simple, and verifiable sequence of steps to fix the problem.
|
||||||
- Create a todo list in markdown format to track your progress.
|
- Add steps using the TodoWrite tool.
|
||||||
- Each time you complete a step, check it off using `[x]` syntax.
|
- Each time you complete a step, mark it as complete using the TodoWrite tool.
|
||||||
- Each time you check off a step, display the updated todo list to the user.
|
- Each time you check off a step, use the TodoRead tool and display the updated todo list to the user in markdown format.
|
||||||
- Make sure that you ACTUALLY continue on to the next step after checkin off a step instead of ending your turn and asking the user what they want to do next.
|
- You MUST continue on to the next step after checking off a step instead of ending your turn and asking the user what they want to do next.
|
||||||
|
- You may only end your turn when all steps in the todo list are marked as complete or cancelled.
|
||||||
|
|
||||||
## 5. Making Code Changes
|
## 6. Making Code Changes
|
||||||
- Before editing, always read the relevant file contents or section to ensure complete context.
|
- Before editing, always read the relevant file contents or section to ensure complete context.
|
||||||
- Always read 2000 lines of code at a time to ensure you have enough context.
|
- Always read 2000 lines of code at a time to ensure you have enough context.
|
||||||
- If a patch is not applied correctly, attempt to reapply it.
|
|
||||||
- Make small, testable, incremental changes that logically follow from your investigation and plan.
|
- Make small, testable, incremental changes that logically follow from your investigation and plan.
|
||||||
|
- When using the edit tool, include 3-5 lines of unchanged code before and after the string you want to replace, to make it unambiguous which part of the file should be edited.
|
||||||
|
- If a patch or edit is not applied correctly, attempt to reapply it.
|
||||||
|
- Always validate that your changes build and pass tests after each change.
|
||||||
|
- If the build fails or test fail, debug why before proceeding, update the plan as needed.
|
||||||
|
|
||||||
## 6. Debugging
|
## 7. Debugging
|
||||||
- Make code changes only if you have high confidence they can solve the problem
|
- Use the `lsp_diagnostics` tool to check for any problems in the code.
|
||||||
- When debugging, try to determine the root cause rather than addressing symptoms
|
- Make code changes only if you have high confidence they can solve the problem.
|
||||||
- Debug for as long as needed to identify the root cause and identify a fix
|
- When debugging, try to determine the root cause rather than addressing symptoms.
|
||||||
- Use the #problems tool to check for any problems in the code
|
- Debug for as long as needed to identify the root cause and identify a fix.
|
||||||
- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening
|
- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening.
|
||||||
- To test hypotheses, you can also add test statements or functions
|
- To test hypotheses, you can also add test statements or functions.
|
||||||
- Revisit your assumptions if unexpected behavior occurs.
|
- Revisit your assumptions if unexpected behavior occurs.
|
||||||
|
|
||||||
# Fetch Webpage
|
|
||||||
Use the `webfetch` tool when the user provides a URL. Follow these steps exactly.
|
|
||||||
|
|
||||||
1. Use the `webfetch` tool to retrieve the content of the provided URL.
|
|
||||||
2. After fetching, review the content returned by the fetch tool.
|
|
||||||
3. If you find any additional URLs or links that are relevant, use the `webfetch` tool again to retrieve those links.
|
|
||||||
4. Go back to step 2 and repeat until you have all the information you need.
|
|
||||||
|
|
||||||
IMPORTANT: Recursively fetching links is crucial. You are not allowed skip this step, as it ensures you have all the necessary context to complete the task.
|
|
||||||
|
|
||||||
# How to create a Todo List
|
# How to create a Todo List
|
||||||
Use the following format to create a todo list:
|
Use the following format to show the todo list:
|
||||||
```markdown
|
```markdown
|
||||||
- [ ] Step 1: Description of the first step
|
- [ ] Step 1: Description of the first step
|
||||||
- [ ] Step 2: Description of the second step
|
- [ ] Step 2: Description of the second step
|
||||||
- [ ] Step 3: Description of the third step
|
- [ ] Step 3: Description of the third step
|
||||||
```
|
```
|
||||||
|
|
||||||
Do not ever use HTML tags or any other formatting for the todo list, as it will not be rendered correctly. Always use the markdown format shown above.
|
Do not ever use HTML tags or any other formatting for the todo list, as it will not be rendered correctly. Always use the markdown format shown above.
|
||||||
|
|
||||||
# Creating Files
|
# Communication Guidelines
|
||||||
Each time you are going to create a file, use a single concise sentence inform the user of what you are creating and why.
|
Always communicate clearly and concisely in a casual, friendly yet professional tone.
|
||||||
|
|
||||||
# Reading Files
|
<examples>
|
||||||
- Read 2000 lines of code at a time to ensure that you have enough context.
|
"Let me fetch the URL you provided to gather more information."
|
||||||
- Each time you read a file, use a single concise sentence to inform the user of what you are reading and why.
|
"Ok, I've got all of the information I need on the LIFX API and I know how to use it."
|
||||||
|
"Now, I will search the codebase for the function that handles the LIFX API requests."
|
||||||
|
"I need to update several files here - stand by"
|
||||||
|
"OK! Now let's run the tests to make sure everything is working correctly."
|
||||||
|
"Whelp - I see we have some problems. Let's fix those up."
|
||||||
|
</examples>
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
You are opencode, an interactive CLI agent specializing in software engineering tasks. Your primary goal is to help users safely and efficiently, adhering strictly to the following instructions and utilizing your available tools.
|
||||||
|
|
||||||
|
# Core Mandates
|
||||||
|
|
||||||
|
- **Conventions:** Rigorously adhere to existing project conventions when reading or modifying code. Analyze surrounding code, tests, and configuration first.
|
||||||
|
- **Libraries/Frameworks:** NEVER assume a library/framework is available or appropriate. Verify its established usage within the project (check imports, configuration files like 'package.json', 'Cargo.toml', 'requirements.txt', 'build.gradle', etc., or observe neighboring files) before employing it.
|
||||||
|
- **Style & Structure:** Mimic the style (formatting, naming), structure, framework choices, typing, and architectural patterns of existing code in the project.
|
||||||
|
- **Idiomatic Changes:** When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically.
|
||||||
|
- **Comments:** Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add high-value comments if necessary for clarity or if requested by the user. Do not edit comments that are separate from the code you are changing. *NEVER* talk to the user or describe your changes through comments.
|
||||||
|
- **Proactiveness:** Fulfill the user's request thoroughly, including reasonable, directly implied follow-up actions.
|
||||||
|
- **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it.
|
||||||
|
- **Explaining Changes:** After completing a code modification or file operation *do not* provide summaries unless asked.
|
||||||
|
- **Path Construction:** Before using any file system tool (e.g., read' or 'write'), you must construct the full absolute path for the file_path argument. Always combine the absolute path of the project's root directory with the file's path relative to the root. For example, if the project root is /path/to/project/ and the file is foo/bar/baz.txt, the final path you must use is /path/to/project/foo/bar/baz.txt. If the user provides a relative path, you must resolve it against the root directory to create an absolute path.
|
||||||
|
- **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes.
|
||||||
|
|
||||||
|
# Primary Workflows
|
||||||
|
|
||||||
|
## Software Engineering Tasks
|
||||||
|
When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this sequence:
|
||||||
|
1. **Understand:** Think about the user's request and the relevant codebase context. Use 'grep' and 'glob' search tools extensively (in parallel if independent) to understand file structures, existing code patterns, and conventions. Use 'read' to understand context and validate any assumptions you may have.
|
||||||
|
2. **Plan:** Build a coherent and grounded (based on the understanding in step 1) plan for how you intend to resolve the user's task. Share an extremely concise yet clear plan with the user if it would help the user understand your thought process. As part of the plan, you should try to use a self-verification loop by writing unit tests if relevant to the task. Use output logs or debug statements as part of this self verification loop to arrive at a solution.
|
||||||
|
3. **Implement:** Use the available tools (e.g., 'edit', 'write' 'bash' ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core Mandates').
|
||||||
|
4. **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands.
|
||||||
|
5. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to.
|
||||||
|
|
||||||
|
## New Applications
|
||||||
|
|
||||||
|
**Goal:** Autonomously implement and deliver a visually appealing, substantially complete, and functional prototype. Utilize all tools at your disposal to implement the application. Some tools you may especially find useful are 'write', 'edit' and 'bash'.
|
||||||
|
|
||||||
|
1. **Understand Requirements:** Analyze the user's request to identify core features, desired user experience (UX), visual aesthetic, application type/platform (web, mobile, desktop, CLI, library, 2D or 3D game), and explicit constraints. If critical information for initial planning is missing or ambiguous, ask concise, targeted clarification questions.
|
||||||
|
2. **Propose Plan:** Formulate an internal development plan. Present a clear, concise, high-level summary to the user. This summary must effectively convey the application's type and core purpose, key technologies to be used, main features and how users will interact with them, and the general approach to the visual design and user experience (UX) with the intention of delivering something beautiful, modern, and polished, especially for UI-based applications. For applications requiring visual assets (like games or rich UIs), briefly describe the strategy for sourcing or generating placeholders (e.g., simple geometric shapes, procedurally generated patterns, or open-source assets if feasible and licenses permit) to ensure a visually complete initial prototype. Ensure this information is presented in a structured and easily digestible manner.
|
||||||
|
3. **User Approval:** Obtain user approval for the proposed plan.
|
||||||
|
4. **Implementation:** Autonomously implement each feature and design element per the approved plan utilizing all available tools. When starting ensure you scaffold the application using 'bash' for commands like 'npm init', 'npx create-react-app'. Aim for full scope completion. Proactively create or source necessary placeholder assets (e.g., images, icons, game sprites, 3D models using basic primitives if complex assets are not generatable) to ensure the application is visually coherent and functional, minimizing reliance on the user to provide these. If the model can generate simple assets (e.g., a uniformly colored square sprite, a simple 3D cube), it should do so. Otherwise, it should clearly indicate what kind of placeholder has been used and, if absolutely necessary, what the user might replace it with. Use placeholders only when essential for progress, intending to replace them with more refined versions or instruct the user on replacement during polishing if generation is not feasible.
|
||||||
|
5. **Verify:** Review work against the original request, the approved plan. Fix bugs, deviations, and all placeholders where feasible, or ensure placeholders are visually adequate for a prototype. Ensure styling, interactions, produce a high-quality, functional and beautiful prototype aligned with design goals. Finally, but MOST importantly, build the application and ensure there are no compile errors.
|
||||||
|
6. **Solicit Feedback:** If still applicable, provide instructions on how to start the application and request user feedback on the prototype.
|
||||||
|
|
||||||
|
# Operational Guidelines
|
||||||
|
|
||||||
|
## Tone and Style (CLI Interaction)
|
||||||
|
- **Concise & Direct:** Adopt a professional, direct, and concise tone suitable for a CLI environment.
|
||||||
|
- **Minimal Output:** Aim for fewer than 3 lines of text output (excluding tool use/code generation) per response whenever practical. Focus strictly on the user's query.
|
||||||
|
- **Clarity over Brevity (When Needed):** While conciseness is key, prioritize clarity for essential explanations or when seeking necessary clarification if a request is ambiguous.
|
||||||
|
- **No Chitchat:** Avoid conversational filler, preambles ("Okay, I will now..."), or postambles ("I have finished the changes..."). Get straight to the action or answer.
|
||||||
|
- **Formatting:** Use GitHub-flavored Markdown. Responses will be rendered in monospace.
|
||||||
|
- **Tools vs. Text:** Use tools for actions, text output *only* for communication. Do not add explanatory comments within tool calls or code blocks unless specifically part of the required code/command itself.
|
||||||
|
- **Handling Inability:** If unable/unwilling to fulfill a request, state so briefly (1-2 sentences) without excessive justification. Offer alternatives if appropriate.
|
||||||
|
|
||||||
|
## Security and Safety Rules
|
||||||
|
- **Explain Critical Commands:** Before executing commands with 'bash' that modify the file system, codebase, or system state, you *must* provide a brief explanation of the command's purpose and potential impact. Prioritize user understanding and safety. You should not ask permission to use the tool; the user will be presented with a confirmation dialogue upon use (you do not need to tell them this).
|
||||||
|
- **Security First:** Always apply security best practices. Never introduce code that exposes, logs, or commits secrets, API keys, or other sensitive information.
|
||||||
|
|
||||||
|
## Tool Usage
|
||||||
|
- **File Paths:** Always use absolute paths when referring to files with tools like 'read' or 'write'. Relative paths are not supported. You must provide an absolute path.
|
||||||
|
- **Parallelism:** Execute multiple independent tool calls in parallel when feasible (i.e. searching the codebase).
|
||||||
|
- **Command Execution:** Use the 'bash' tool for running shell commands, remembering the safety rule to explain modifying commands first.
|
||||||
|
- **Background Processes:** Use background processes (via \`&\`) for commands that are unlikely to stop on their own, e.g. \`node server.js &\`. If unsure, ask the user.
|
||||||
|
- **Interactive Commands:** Try to avoid shell commands that are likely to require user interaction (e.g. \`git rebase -i\`). Use non-interactive versions of commands (e.g. \`npm init -y\` instead of \`npm init\`) when available, and otherwise remind the user that interactive shell commands are not supported and may cause hangs until canceled by the user.
|
||||||
|
- **Respect User Confirmations:** Most tool calls (also denoted as 'function calls') will first require confirmation from the user, where they will either approve or cancel the function call. If a user cancels a function call, respect their choice and do _not_ try to make the function call again. It is okay to request the tool call again _only_ if the user requests that same tool call on a subsequent prompt. When a user cancels a function call, assume best intentions from the user and consider inquiring if they prefer any alternative paths forward.
|
||||||
|
|
||||||
|
## Interaction Details
|
||||||
|
- **Help Command:** The user can use '/help' to display help information.
|
||||||
|
- **Feedback:** To report a bug or provide feedback, please use the /bug command.
|
||||||
|
|
||||||
|
# Examples (Illustrating Tone and Workflow)
|
||||||
|
<example>
|
||||||
|
user: 1 + 2
|
||||||
|
model: 3
|
||||||
|
</example>
|
||||||
|
|
||||||
|
<example>
|
||||||
|
user: is 13 a prime number?
|
||||||
|
model: true
|
||||||
|
</example>
|
||||||
|
|
||||||
|
<example>
|
||||||
|
user: list files here.
|
||||||
|
model: [tool_call: ls for path '/path/to/project']
|
||||||
|
</example>
|
||||||
|
|
||||||
|
<example>
|
||||||
|
user: start the server implemented in server.js
|
||||||
|
model: [tool_call: bash for 'node server.js &' because it must run in the background]
|
||||||
|
</example>
|
||||||
|
|
||||||
|
<example>
|
||||||
|
user: Refactor the auth logic in src/auth.py to use the requests library instead of urllib.
|
||||||
|
model: Okay, I can refactor 'src/auth.py'.
|
||||||
|
First, I'll analyze the code and check for a test safety net before planning any changes.
|
||||||
|
[tool_call: glob for path 'tests/test_auth.py']
|
||||||
|
[tool_call: read for absolute_path '/path/to/tests/test_auth.py']
|
||||||
|
(After analysis)
|
||||||
|
Great, 'tests/test_auth.py' exists and covers the core authentication logic. With this safety net in place, I can safely plan the refactoring.
|
||||||
|
I'll also confirm 'requests' is a dependency.
|
||||||
|
[tool_call: read for absolute_path '/path/to/requirements.txt']
|
||||||
|
(After analysis)
|
||||||
|
Looks good, 'requests' is available.
|
||||||
|
|
||||||
|
Here's the plan:
|
||||||
|
1. Replace the 'urllib' calls with 'requests'.
|
||||||
|
2. Add proper 'try...except' error handling for the new network calls.
|
||||||
|
3. Remove the old 'urllib' import.
|
||||||
|
4. Run the project's linter and tests to verify the changes.
|
||||||
|
|
||||||
|
Should I proceed?
|
||||||
|
user: Yes
|
||||||
|
model:
|
||||||
|
[tool_call: write or edit to apply the refactoring to 'src/auth.py']
|
||||||
|
Refactoring complete. Running verification...
|
||||||
|
[tool_call: bash for 'ruff check src/auth.py && pytest']
|
||||||
|
(After verification passes)
|
||||||
|
All checks passed. This is a stable checkpoint.
|
||||||
|
|
||||||
|
<example>
|
||||||
|
user: Delete the temp directory.
|
||||||
|
model: I can run \`rm -rf /path/to/project/temp\`. This will permanently delete the directory and all its contents.
|
||||||
|
</example>
|
||||||
|
|
||||||
|
<example>
|
||||||
|
user: Write tests for someFile.ts
|
||||||
|
model:
|
||||||
|
Okay, I can write those tests. First, I'll read \`someFile.ts\` to understand its functionality.
|
||||||
|
[tool_call: read for absolute_path '/path/to/someFile.ts' or use glob to find \`someFile.ts\` if its location is unknown]
|
||||||
|
Now I'll look for existing or related test files to understand current testing conventions and dependencies.
|
||||||
|
[tool_call: glob for paths ['**/*.test.ts', 'src/**/*.spec.ts'] assuming someFile.ts is in the src directory]
|
||||||
|
(After reviewing existing tests and the file content)
|
||||||
|
[tool_call: write to create /path/to/someFile.test.ts with the test code]
|
||||||
|
I've written the tests. Now I'll run the project's test command to verify them.
|
||||||
|
[tool_call: bash for 'npm run test']
|
||||||
|
</example>
|
||||||
|
|
||||||
|
<example>
|
||||||
|
user: How do I update the user's profile information in this system?
|
||||||
|
model:
|
||||||
|
I'm not immediately sure how user profile information is updated. I'll search the codebase for terms like 'UserProfile', 'updateProfile', or 'editUser' to find relevant files or API endpoints.
|
||||||
|
[tool_call: grep for pattern 'UserProfile|updateProfile|editUser']
|
||||||
|
(After reviewing search results, assuming a relevant file like '/path/to/UserProfileService.java' was found)
|
||||||
|
Okay, \`/path/to/UserProfileService.java\` seems like the most relevant file. I'll read its content to understand how updates are handled.
|
||||||
|
[tool_call: read for absolute_path '/path/to/UserProfileService.java']
|
||||||
|
(After reading the file)
|
||||||
|
It appears the \`updateUserProfile\` method in \`UserProfileService.java\` is responsible for this. It expects a user ID and a \`UserProfileDTO\` object...
|
||||||
|
</example>
|
||||||
|
|
||||||
|
<example>
|
||||||
|
user: Where are all the 'app.config' files in this project? I need to check their settings.
|
||||||
|
model:
|
||||||
|
[tool_call: glob for pattern '**/app.config']
|
||||||
|
(Assuming GlobTool returns a list of paths like ['/path/to/moduleA/app.config', '/path/to/moduleB/app.config'])
|
||||||
|
I found the following 'app.config' files:
|
||||||
|
- /path/to/moduleA/app.config
|
||||||
|
- /path/to/moduleB/app.config
|
||||||
|
To help you check their settings, I can read their contents. Which one would you like to start with, or should I read all of them?
|
||||||
|
</example>
|
||||||
|
|
||||||
|
# Final Reminder
|
||||||
|
Your core function is efficient and safe assistance. Balance extreme conciseness with the crucial need for clarity, especially regarding safety and potential system modifications. Always prioritize user control and project conventions. Never make assumptions about the contents of files; instead use 'read' to ensure you aren't making broad assumptions. Finally, you are an agent - please keep going until the user's query is completely resolved.
|
||||||
@@ -1,14 +1,29 @@
|
|||||||
<task>
|
<task>
|
||||||
Generate a conversation thread title based on the first user message.
|
Generate a conversation thread title from the user message.
|
||||||
</task>
|
</task>
|
||||||
|
|
||||||
<requirements>
|
<context>
|
||||||
- Maximum 50 characters
|
You are generating titles for a coding assistant conversation.
|
||||||
- Single line only - NO newlines or line breaks
|
</context>
|
||||||
- Create a descriptive thread name that captures the topic
|
|
||||||
- No quotes, colons, or special formatting
|
<rules>
|
||||||
- Do not include explanatory text like "Title:" or similar prefixes
|
- Max 50 chars, single line
|
||||||
</requirements>
|
- Focus on the specific action or question
|
||||||
|
- Keep technical terms, numbers, and filenames exactly as written
|
||||||
|
- Preserve HTTP status codes (401, 404, 500, etc) as numbers
|
||||||
|
- For file references, include the filename
|
||||||
|
- Avoid filler words: the, this, my, a, an, properly
|
||||||
|
- NEVER assume their tech stack or domain
|
||||||
|
- Use -ing verbs consistently for actions
|
||||||
|
- Write like a chat thread title, not a blog post
|
||||||
|
</rules>
|
||||||
|
|
||||||
|
<examples>
|
||||||
|
"debug 500 errors in production" → "Debugging production 500 errors"
|
||||||
|
"refactor user service" → "Refactoring user service"
|
||||||
|
"why is app.js failing" → "Analyzing app.js failure"
|
||||||
|
"implement rate limiting" → "Implementing rate limiting"
|
||||||
|
</examples>
|
||||||
|
|
||||||
<format>
|
<format>
|
||||||
Return only the thread title text on a single line with no newlines, explanations, or additional formatting.
|
Return only the thread title text on a single line with no newlines, explanations, or additional formatting.
|
||||||
|
|||||||
@@ -8,14 +8,15 @@ import os from "os"
|
|||||||
|
|
||||||
import PROMPT_ANTHROPIC from "./prompt/anthropic.txt"
|
import PROMPT_ANTHROPIC from "./prompt/anthropic.txt"
|
||||||
import PROMPT_BEAST from "./prompt/beast.txt"
|
import PROMPT_BEAST from "./prompt/beast.txt"
|
||||||
|
import PROMPT_GEMINI from "./prompt/gemini.txt"
|
||||||
import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt"
|
import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt"
|
||||||
import PROMPT_SUMMARIZE from "./prompt/summarize.txt"
|
import PROMPT_SUMMARIZE from "./prompt/summarize.txt"
|
||||||
import PROMPT_TITLE from "./prompt/title.txt"
|
import PROMPT_TITLE from "./prompt/title.txt"
|
||||||
|
|
||||||
export namespace SystemPrompt {
|
export namespace SystemPrompt {
|
||||||
export function provider(providerID: string, modelID: string) {
|
export function provider(modelID: string) {
|
||||||
if (providerID === "anthropic") return [PROMPT_ANTHROPIC_SPOOF.trim(), PROMPT_ANTHROPIC]
|
if (modelID.includes("gpt-") || modelID.includes("o1") || modelID.includes("o3")) return [PROMPT_BEAST]
|
||||||
if (modelID.includes("gpt-")) return [PROMPT_BEAST]
|
if (modelID.includes("gemini-")) return [PROMPT_GEMINI]
|
||||||
return [PROMPT_ANTHROPIC]
|
return [PROMPT_ANTHROPIC]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ export namespace Snapshot {
|
|||||||
limit: 1000,
|
limit: 1000,
|
||||||
})
|
})
|
||||||
log.info("found files", { count: files.length })
|
log.info("found files", { count: files.length })
|
||||||
if (files.length > 1000) return
|
if (files.length >= 1000) return
|
||||||
}
|
}
|
||||||
|
|
||||||
const git = gitdir(sessionID)
|
const git = gitdir(sessionID)
|
||||||
@@ -38,10 +38,11 @@ export namespace Snapshot {
|
|||||||
await $`git --git-dir ${git} add .`.quiet().cwd(app.path.cwd).nothrow()
|
await $`git --git-dir ${git} add .`.quiet().cwd(app.path.cwd).nothrow()
|
||||||
log.info("added files")
|
log.info("added files")
|
||||||
|
|
||||||
const result = await $`git --git-dir ${git} commit -m "snapshot" --author="opencode <mail@opencode.ai>"`
|
const result =
|
||||||
.quiet()
|
await $`git --git-dir ${git} commit -m "snapshot" --no-gpg-sign --author="opencode <mail@opencode.ai>"`
|
||||||
.cwd(app.path.cwd)
|
.quiet()
|
||||||
.nothrow()
|
.cwd(app.path.cwd)
|
||||||
|
.nothrow()
|
||||||
|
|
||||||
const match = result.stdout.toString().match(/\[.+ ([a-f0-9]+)\]/)
|
const match = result.stdout.toString().match(/\[.+ ([a-f0-9]+)\]/)
|
||||||
if (!match) return
|
if (!match) return
|
||||||
|
|||||||
@@ -86,7 +86,10 @@ export const EditTool = Tool.define({
|
|||||||
output += `\nThis file has errors, please fix\n<file_diagnostics>\n${issues.map(LSP.Diagnostic.pretty).join("\n")}\n</file_diagnostics>\n`
|
output += `\nThis file has errors, please fix\n<file_diagnostics>\n${issues.map(LSP.Diagnostic.pretty).join("\n")}\n</file_diagnostics>\n`
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
output += `\n<project_diagnostics>\n${file}\n${issues.map(LSP.Diagnostic.pretty).join("\n")}\n</project_diagnostics>\n`
|
output += `\n<project_diagnostics>\n${file}\n${issues
|
||||||
|
.filter((item) => item.severity === 1)
|
||||||
|
.map(LSP.Diagnostic.pretty)
|
||||||
|
.join("\n")}\n</project_diagnostics>\n`
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -55,12 +55,11 @@ export const GrepTool = Tool.define({
|
|||||||
for (const line of lines) {
|
for (const line of lines) {
|
||||||
if (!line) continue
|
if (!line) continue
|
||||||
|
|
||||||
const parts = line.split(":", 3)
|
const [filePath, lineNumStr, ...lineTextParts] = line.split(":")
|
||||||
if (parts.length < 3) continue
|
if (!filePath || !lineNumStr || lineTextParts.length === 0) continue
|
||||||
|
|
||||||
const filePath = parts[0]
|
const lineNum = parseInt(lineNumStr, 10)
|
||||||
const lineNum = parseInt(parts[1], 10)
|
const lineText = lineTextParts.join(":")
|
||||||
const lineText = parts[2]
|
|
||||||
|
|
||||||
const file = Bun.file(filePath)
|
const file = Bun.file(filePath)
|
||||||
const stats = await file.stat().catch(() => null)
|
const stats = await file.stat().catch(() => null)
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { FileTime } from "../file/time"
|
|||||||
import DESCRIPTION from "./read.txt"
|
import DESCRIPTION from "./read.txt"
|
||||||
import { App } from "../app/app"
|
import { App } from "../app/app"
|
||||||
|
|
||||||
const MAX_READ_SIZE = 250 * 1024
|
|
||||||
const DEFAULT_READ_LIMIT = 2000
|
const DEFAULT_READ_LIMIT = 2000
|
||||||
const MAX_LINE_LENGTH = 2000
|
const MAX_LINE_LENGTH = 2000
|
||||||
|
|
||||||
@@ -45,10 +44,7 @@ export const ReadTool = Tool.define({
|
|||||||
|
|
||||||
throw new Error(`File not found: ${filePath}`)
|
throw new Error(`File not found: ${filePath}`)
|
||||||
}
|
}
|
||||||
const stats = await file.stat()
|
|
||||||
|
|
||||||
if (stats.size > MAX_READ_SIZE)
|
|
||||||
throw new Error(`File is too large (${stats.size} bytes). Maximum size is ${MAX_READ_SIZE} bytes`)
|
|
||||||
const limit = params.limit ?? DEFAULT_READ_LIMIT
|
const limit = params.limit ?? DEFAULT_READ_LIMIT
|
||||||
const offset = params.offset || 0
|
const offset = params.offset || 0
|
||||||
const isImage = isImageFile(filePath)
|
const isImage = isImageFile(filePath)
|
||||||
|
|||||||
@@ -105,7 +105,7 @@ export namespace Log {
|
|||||||
...extra,
|
...extra,
|
||||||
})
|
})
|
||||||
.filter(([_, value]) => value !== undefined && value !== null)
|
.filter(([_, value]) => value !== undefined && value !== null)
|
||||||
.map(([key, value]) => `${key}=${value}`)
|
.map(([key, value]) => `${key}=${typeof value === "object" ? JSON.stringify(value) : value}`)
|
||||||
.join(" ")
|
.join(" ")
|
||||||
const next = new Date()
|
const next = new Date()
|
||||||
const diff = next.getTime() - last
|
const diff = next.getTime() - last
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { describe, expect, test } from "bun:test"
|
||||||
|
import fs from "fs/promises"
|
||||||
|
import path from "path"
|
||||||
|
|
||||||
|
describe("BunProc registry configuration", () => {
|
||||||
|
test("should not contain hardcoded registry parameters", async () => {
|
||||||
|
// Read the bun/index.ts file
|
||||||
|
const bunIndexPath = path.join(__dirname, "../src/bun/index.ts")
|
||||||
|
const content = await fs.readFile(bunIndexPath, "utf-8")
|
||||||
|
|
||||||
|
// Verify that no hardcoded registry is present
|
||||||
|
expect(content).not.toContain("--registry=")
|
||||||
|
expect(content).not.toContain("hasNpmRcConfig")
|
||||||
|
expect(content).not.toContain("NpmRc")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("should use Bun's default registry resolution", async () => {
|
||||||
|
// Read the bun/index.ts file
|
||||||
|
const bunIndexPath = path.join(__dirname, "../src/bun/index.ts")
|
||||||
|
const content = await fs.readFile(bunIndexPath, "utf-8")
|
||||||
|
|
||||||
|
// Verify that it uses Bun's default resolution
|
||||||
|
expect(content).toContain("Bun's default registry resolution")
|
||||||
|
expect(content).toContain("Bun will use them automatically")
|
||||||
|
expect(content).toContain("No need to pass --registry flag")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("should have correct command structure without registry", async () => {
|
||||||
|
// Read the bun/index.ts file
|
||||||
|
const bunIndexPath = path.join(__dirname, "../src/bun/index.ts")
|
||||||
|
const content = await fs.readFile(bunIndexPath, "utf-8")
|
||||||
|
|
||||||
|
// Extract the install function
|
||||||
|
const installFunctionMatch = content.match(/export async function install[\s\S]*?^ }/m)
|
||||||
|
expect(installFunctionMatch).toBeTruthy()
|
||||||
|
|
||||||
|
if (installFunctionMatch) {
|
||||||
|
const installFunction = installFunctionMatch[0]
|
||||||
|
|
||||||
|
// Verify expected arguments are present
|
||||||
|
expect(installFunction).toContain('"add"')
|
||||||
|
expect(installFunction).toContain('"--force"')
|
||||||
|
expect(installFunction).toContain('"--exact"')
|
||||||
|
expect(installFunction).toContain('"--cwd"')
|
||||||
|
expect(installFunction).toContain('Global.Path.cache')
|
||||||
|
expect(installFunction).toContain('pkg + "@" + version')
|
||||||
|
|
||||||
|
// Verify no registry argument is added
|
||||||
|
expect(installFunction).not.toContain('"--registry"')
|
||||||
|
expect(installFunction).not.toContain('args.push("--registry')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -1 +1,2 @@
|
|||||||
opencode-test
|
opencode-test
|
||||||
|
cmd/opencode/opencode
|
||||||
|
|||||||
@@ -31,42 +31,20 @@ type win32InputState struct {
|
|||||||
|
|
||||||
// Reader represents an input event reader. It reads input events and parses
|
// Reader represents an input event reader. It reads input events and parses
|
||||||
// escape sequences from the terminal input buffer and translates them into
|
// escape sequences from the terminal input buffer and translates them into
|
||||||
// human-readable events.
|
// human‑readable events.
|
||||||
type Reader struct {
|
type Reader struct {
|
||||||
rd cancelreader.CancelReader
|
rd cancelreader.CancelReader
|
||||||
table map[string]Key // table is a lookup table for key sequences.
|
table map[string]Key // table is a lookup table for key sequences.
|
||||||
|
term string // $TERM
|
||||||
term string // term is the terminal name $TERM.
|
paste []byte // bracketed paste buffer; nil when disabled
|
||||||
|
buf [256]byte // read buffer
|
||||||
// paste is the bracketed paste mode buffer.
|
partialSeq []byte // holds incomplete escape sequences
|
||||||
// When nil, bracketed paste mode is disabled.
|
keyState win32InputState
|
||||||
paste []byte
|
parser Parser
|
||||||
|
logger Logger
|
||||||
buf [256]byte // do we need a larger buffer?
|
|
||||||
|
|
||||||
// partialSeq holds incomplete escape sequences that need more data
|
|
||||||
partialSeq []byte
|
|
||||||
|
|
||||||
// keyState keeps track of the current Windows Console API key events state.
|
|
||||||
// It is used to decode ANSI escape sequences and utf16 sequences.
|
|
||||||
keyState win32InputState
|
|
||||||
|
|
||||||
parser Parser
|
|
||||||
logger Logger
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewReader returns a new input event reader. The reader reads input events
|
// NewReader returns a new input event reader.
|
||||||
// from the terminal and parses escape sequences into human-readable events. It
|
|
||||||
// supports reading Terminfo databases. See [Parser] for more information.
|
|
||||||
//
|
|
||||||
// Example:
|
|
||||||
//
|
|
||||||
// r, _ := input.NewReader(os.Stdin, os.Getenv("TERM"), 0)
|
|
||||||
// defer r.Close()
|
|
||||||
// events, _ := r.ReadEvents()
|
|
||||||
// for _, ev := range events {
|
|
||||||
// log.Printf("%v", ev)
|
|
||||||
// }
|
|
||||||
func NewReader(r io.Reader, termType string, flags int) (*Reader, error) {
|
func NewReader(r io.Reader, termType string, flags int) (*Reader, error) {
|
||||||
d := new(Reader)
|
d := new(Reader)
|
||||||
cr, err := newCancelreader(r, flags)
|
cr, err := newCancelreader(r, flags)
|
||||||
@@ -82,46 +60,38 @@ func NewReader(r io.Reader, termType string, flags int) (*Reader, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetLogger sets a logger for the reader.
|
// SetLogger sets a logger for the reader.
|
||||||
func (d *Reader) SetLogger(l Logger) {
|
func (d *Reader) SetLogger(l Logger) { d.logger = l }
|
||||||
d.logger = l
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read implements [io.Reader].
|
// Read implements io.Reader.
|
||||||
func (d *Reader) Read(p []byte) (int, error) {
|
func (d *Reader) Read(p []byte) (int, error) { return d.rd.Read(p) }
|
||||||
return d.rd.Read(p) //nolint:wrapcheck
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cancel cancels the underlying reader.
|
// Cancel cancels the underlying reader.
|
||||||
func (d *Reader) Cancel() bool {
|
func (d *Reader) Cancel() bool { return d.rd.Cancel() }
|
||||||
return d.rd.Cancel()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close closes the underlying reader.
|
// Close closes the underlying reader.
|
||||||
func (d *Reader) Close() error {
|
func (d *Reader) Close() error { return d.rd.Close() }
|
||||||
return d.rd.Close() //nolint:wrapcheck
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Reader) readEvents() ([]Event, error) {
|
func (d *Reader) readEvents() ([]Event, error) {
|
||||||
nb, err := d.rd.Read(d.buf[:])
|
nb, err := d.rd.Read(d.buf[:])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err //nolint:wrapcheck
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var events []Event
|
var events []Event
|
||||||
|
|
||||||
// Combine any partial sequence from previous read with new data
|
// Combine any partial sequence from previous read with new data.
|
||||||
var buf []byte
|
var buf []byte
|
||||||
if len(d.partialSeq) > 0 {
|
if len(d.partialSeq) > 0 {
|
||||||
buf = make([]byte, len(d.partialSeq)+nb)
|
buf = make([]byte, len(d.partialSeq)+nb)
|
||||||
copy(buf, d.partialSeq)
|
copy(buf, d.partialSeq)
|
||||||
copy(buf[len(d.partialSeq):], d.buf[:nb])
|
copy(buf[len(d.partialSeq):], d.buf[:nb])
|
||||||
d.partialSeq = nil // clear the partial sequence
|
d.partialSeq = nil
|
||||||
} else {
|
} else {
|
||||||
buf = d.buf[:nb]
|
buf = d.buf[:nb]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lookup table first
|
// Fast path: direct lookup for simple escape sequences.
|
||||||
if bytes.HasPrefix(buf, []byte{'\x1b'}) {
|
if bytes.HasPrefix(buf, []byte{0x1b}) {
|
||||||
if k, ok := d.table[string(buf)]; ok {
|
if k, ok := d.table[string(buf)]; ok {
|
||||||
if d.logger != nil {
|
if d.logger != nil {
|
||||||
d.logger.Printf("input: %q", buf)
|
d.logger.Printf("input: %q", buf)
|
||||||
@@ -133,24 +103,23 @@ func (d *Reader) readEvents() ([]Event, error) {
|
|||||||
|
|
||||||
var i int
|
var i int
|
||||||
for i < len(buf) {
|
for i < len(buf) {
|
||||||
nb, ev := d.parser.parseSequence(buf[i:])
|
consumed, ev := d.parser.parseSequence(buf[i:])
|
||||||
if d.logger != nil && nb > 0 {
|
if d.logger != nil && consumed > 0 {
|
||||||
d.logger.Printf("input: %q", buf[i:i+nb])
|
d.logger.Printf("input: %q", buf[i:i+consumed])
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle incomplete sequences - when parseSequence returns (0, nil)
|
// Incomplete sequence – store remainder and exit.
|
||||||
// it means we need more data to complete the sequence
|
if consumed == 0 && ev == nil {
|
||||||
if nb == 0 && ev == nil {
|
rem := len(buf) - i
|
||||||
// Store the remaining data for the next read
|
if rem > 0 {
|
||||||
remaining := len(buf) - i
|
d.partialSeq = make([]byte, rem)
|
||||||
if remaining > 0 {
|
|
||||||
d.partialSeq = make([]byte, remaining)
|
|
||||||
copy(d.partialSeq, buf[i:])
|
copy(d.partialSeq, buf[i:])
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle bracketed-paste
|
// Handle bracketed paste specially so we don’t emit a paste event for
|
||||||
|
// every byte.
|
||||||
if d.paste != nil {
|
if d.paste != nil {
|
||||||
if _, ok := ev.(PasteEndEvent); !ok {
|
if _, ok := ev.(PasteEndEvent); !ok {
|
||||||
d.paste = append(d.paste, buf[i])
|
d.paste = append(d.paste, buf[i])
|
||||||
@@ -160,15 +129,9 @@ func (d *Reader) readEvents() ([]Event, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch ev.(type) {
|
switch ev.(type) {
|
||||||
// case UnknownEvent:
|
|
||||||
// // If the sequence is not recognized by the parser, try looking it up.
|
|
||||||
// if k, ok := d.table[string(buf[i:i+nb])]; ok {
|
|
||||||
// ev = KeyPressEvent(k)
|
|
||||||
// }
|
|
||||||
case PasteStartEvent:
|
case PasteStartEvent:
|
||||||
d.paste = []byte{}
|
d.paste = []byte{}
|
||||||
case PasteEndEvent:
|
case PasteEndEvent:
|
||||||
// Decode the captured data into runes.
|
|
||||||
var paste []rune
|
var paste []rune
|
||||||
for len(d.paste) > 0 {
|
for len(d.paste) > 0 {
|
||||||
r, w := utf8.DecodeRune(d.paste)
|
r, w := utf8.DecodeRune(d.paste)
|
||||||
@@ -177,7 +140,7 @@ func (d *Reader) readEvents() ([]Event, error) {
|
|||||||
}
|
}
|
||||||
d.paste = d.paste[w:]
|
d.paste = d.paste[w:]
|
||||||
}
|
}
|
||||||
d.paste = nil // reset the buffer
|
d.paste = nil
|
||||||
events = append(events, PasteEvent(paste))
|
events = append(events, PasteEvent(paste))
|
||||||
case nil:
|
case nil:
|
||||||
i++
|
i++
|
||||||
@@ -189,8 +152,41 @@ func (d *Reader) readEvents() ([]Event, error) {
|
|||||||
} else {
|
} else {
|
||||||
events = append(events, ev)
|
events = append(events, ev)
|
||||||
}
|
}
|
||||||
i += nb
|
i += consumed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Collapse bursts of wheel/motion events into a single event each.
|
||||||
|
events = coalesceMouseEvents(events)
|
||||||
return events, nil
|
return events, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// coalesceMouseEvents reduces the volume of MouseWheelEvent and MouseMotionEvent
|
||||||
|
// objects that arrive in rapid succession by keeping only the most recent
|
||||||
|
// event in each contiguous run.
|
||||||
|
func coalesceMouseEvents(in []Event) []Event {
|
||||||
|
if len(in) < 2 {
|
||||||
|
return in
|
||||||
|
}
|
||||||
|
|
||||||
|
out := make([]Event, 0, len(in))
|
||||||
|
for _, ev := range in {
|
||||||
|
switch ev.(type) {
|
||||||
|
case MouseWheelEvent:
|
||||||
|
if len(out) > 0 {
|
||||||
|
if _, ok := out[len(out)-1].(MouseWheelEvent); ok {
|
||||||
|
out[len(out)-1] = ev // replace previous wheel event
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case MouseMotionEvent:
|
||||||
|
if len(out) > 0 {
|
||||||
|
if _, ok := out[len(out)-1].(MouseMotionEvent); ok {
|
||||||
|
out[len(out)-1] = ev // replace previous motion event
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out = append(out, ev)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|||||||
@@ -303,7 +303,8 @@ func (p *Parser) parseCsi(b []byte) (int, Event) {
|
|||||||
return i, CursorPositionEvent{Y: row - 1, X: col - 1}
|
return i, CursorPositionEvent{Y: row - 1, X: col - 1}
|
||||||
case 'm' | '<'<<parser.PrefixShift, 'M' | '<'<<parser.PrefixShift:
|
case 'm' | '<'<<parser.PrefixShift, 'M' | '<'<<parser.PrefixShift:
|
||||||
// Handle SGR mouse
|
// Handle SGR mouse
|
||||||
if paramsLen == 3 {
|
if paramsLen >= 3 {
|
||||||
|
pa = pa[:3]
|
||||||
return i, parseSGRMouseEvent(cmd, pa)
|
return i, parseSGRMouseEvent(cmd, pa)
|
||||||
}
|
}
|
||||||
case 'm' | '>'<<parser.PrefixShift:
|
case 'm' | '>'<<parser.PrefixShift:
|
||||||
|
|||||||
@@ -50,6 +50,9 @@ type App struct {
|
|||||||
IsLeaderSequence bool
|
IsLeaderSequence bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SessionCreatedMsg = struct {
|
||||||
|
Session *opencode.Session
|
||||||
|
}
|
||||||
type SessionSelectedMsg = *opencode.Session
|
type SessionSelectedMsg = *opencode.Session
|
||||||
type SessionLoadedMsg struct{}
|
type SessionLoadedMsg struct{}
|
||||||
type ModelSelectedMsg struct {
|
type ModelSelectedMsg struct {
|
||||||
@@ -202,10 +205,17 @@ func (a *App) SetClipboard(text string) tea.Cmd {
|
|||||||
return tea.Sequence(cmds...)
|
return tea.Sequence(cmds...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) SwitchMode() (*App, tea.Cmd) {
|
func (a *App) cycleMode(forward bool) (*App, tea.Cmd) {
|
||||||
a.ModeIndex++
|
if forward {
|
||||||
if a.ModeIndex >= len(a.Modes) {
|
a.ModeIndex++
|
||||||
a.ModeIndex = 0
|
if a.ModeIndex >= len(a.Modes) {
|
||||||
|
a.ModeIndex = 0
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
a.ModeIndex--
|
||||||
|
if a.ModeIndex < 0 {
|
||||||
|
a.ModeIndex = len(a.Modes) - 1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
a.Mode = &a.Modes[a.ModeIndex]
|
a.Mode = &a.Modes[a.ModeIndex]
|
||||||
|
|
||||||
@@ -241,8 +251,16 @@ func (a *App) SwitchMode() (*App, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *App) SwitchMode() (*App, tea.Cmd) {
|
||||||
|
return a.cycleMode(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *App) SwitchModeReverse() (*App, tea.Cmd) {
|
||||||
|
return a.cycleMode(false)
|
||||||
|
}
|
||||||
|
|
||||||
func (a *App) InitializeProvider() tea.Cmd {
|
func (a *App) InitializeProvider() tea.Cmd {
|
||||||
providersResponse, err := a.Client.Config.Providers(context.Background())
|
providersResponse, err := a.Client.App.Providers(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Failed to list providers", "error", err)
|
slog.Error("Failed to list providers", "error", err)
|
||||||
// TODO: notify user
|
// TODO: notify user
|
||||||
@@ -337,7 +355,7 @@ func (a *App) InitializeProvider() tea.Cmd {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getDefaultModel(
|
func getDefaultModel(
|
||||||
response *opencode.ConfigProvidersResponse,
|
response *opencode.AppProvidersResponse,
|
||||||
provider opencode.Provider,
|
provider opencode.Provider,
|
||||||
) *opencode.Model {
|
) *opencode.Model {
|
||||||
if match, ok := response.Default[provider.ID]; ok {
|
if match, ok := response.Default[provider.ID]; ok {
|
||||||
@@ -380,7 +398,7 @@ func (a *App) InitializeProject(ctx context.Context) tea.Cmd {
|
|||||||
}
|
}
|
||||||
|
|
||||||
a.Session = session
|
a.Session = session
|
||||||
cmds = append(cmds, util.CmdHandler(SessionSelectedMsg(session)))
|
cmds = append(cmds, util.CmdHandler(SessionCreatedMsg{Session: session}))
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
_, err := a.Client.Session.Init(ctx, a.Session.ID, opencode.SessionInitParams{
|
_, err := a.Client.Session.Init(ctx, a.Session.ID, opencode.SessionInitParams{
|
||||||
@@ -456,7 +474,7 @@ func (a *App) SendChatMessage(
|
|||||||
return a, toast.NewErrorToast(err.Error())
|
return a, toast.NewErrorToast(err.Error())
|
||||||
}
|
}
|
||||||
a.Session = session
|
a.Session = session
|
||||||
cmds = append(cmds, util.CmdHandler(SessionSelectedMsg(session)))
|
cmds = append(cmds, util.CmdHandler(SessionCreatedMsg{Session: session}))
|
||||||
}
|
}
|
||||||
|
|
||||||
message := opencode.UserMessage{
|
message := opencode.UserMessage{
|
||||||
@@ -600,7 +618,7 @@ func (a *App) ListMessages(ctx context.Context, sessionId string) ([]Message, er
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) ListProviders(ctx context.Context) ([]opencode.Provider, error) {
|
func (a *App) ListProviders(ctx context.Context) ([]opencode.Provider, error) {
|
||||||
response, err := a.Client.Config.Providers(ctx)
|
response, err := a.Client.App.Providers(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
const MAX_CONTAINER_WIDTH = 86
|
||||||
|
const EDIT_DIFF_MAX_WIDTH = 180
|
||||||
@@ -87,6 +87,7 @@ func (r CommandRegistry) Matches(msg tea.KeyPressMsg, leader bool) []Command {
|
|||||||
const (
|
const (
|
||||||
AppHelpCommand CommandName = "app_help"
|
AppHelpCommand CommandName = "app_help"
|
||||||
SwitchModeCommand CommandName = "switch_mode"
|
SwitchModeCommand CommandName = "switch_mode"
|
||||||
|
SwitchModeReverseCommand CommandName = "switch_mode_reverse"
|
||||||
EditorOpenCommand CommandName = "editor_open"
|
EditorOpenCommand CommandName = "editor_open"
|
||||||
SessionNewCommand CommandName = "session_new"
|
SessionNewCommand CommandName = "session_new"
|
||||||
SessionListCommand CommandName = "session_list"
|
SessionListCommand CommandName = "session_list"
|
||||||
@@ -94,6 +95,7 @@ const (
|
|||||||
SessionUnshareCommand CommandName = "session_unshare"
|
SessionUnshareCommand CommandName = "session_unshare"
|
||||||
SessionInterruptCommand CommandName = "session_interrupt"
|
SessionInterruptCommand CommandName = "session_interrupt"
|
||||||
SessionCompactCommand CommandName = "session_compact"
|
SessionCompactCommand CommandName = "session_compact"
|
||||||
|
SessionExportCommand CommandName = "session_export"
|
||||||
ToolDetailsCommand CommandName = "tool_details"
|
ToolDetailsCommand CommandName = "tool_details"
|
||||||
ModelListCommand CommandName = "model_list"
|
ModelListCommand CommandName = "model_list"
|
||||||
ThemeListCommand CommandName = "theme_list"
|
ThemeListCommand CommandName = "theme_list"
|
||||||
@@ -155,15 +157,26 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
Name: SwitchModeCommand,
|
Name: SwitchModeCommand,
|
||||||
Description: "switch mode",
|
Description: "next mode",
|
||||||
Keybindings: parseBindings("tab"),
|
Keybindings: parseBindings("tab"),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: SwitchModeReverseCommand,
|
||||||
|
Description: "previous mode",
|
||||||
|
Keybindings: parseBindings("shift+tab"),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
Name: EditorOpenCommand,
|
Name: EditorOpenCommand,
|
||||||
Description: "open editor",
|
Description: "open editor",
|
||||||
Keybindings: parseBindings("<leader>e"),
|
Keybindings: parseBindings("<leader>e"),
|
||||||
Trigger: []string{"editor"},
|
Trigger: []string{"editor"},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
Name: SessionExportCommand,
|
||||||
|
Description: "export conversation",
|
||||||
|
Keybindings: parseBindings("<leader>x"),
|
||||||
|
Trigger: []string{"export"},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
Name: SessionNewCommand,
|
Name: SessionNewCommand,
|
||||||
Description: "new session",
|
Description: "new session",
|
||||||
@@ -217,12 +230,12 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
|
|||||||
Keybindings: parseBindings("<leader>t"),
|
Keybindings: parseBindings("<leader>t"),
|
||||||
Trigger: []string{"themes"},
|
Trigger: []string{"themes"},
|
||||||
},
|
},
|
||||||
{
|
// {
|
||||||
Name: FileListCommand,
|
// Name: FileListCommand,
|
||||||
Description: "list files",
|
// Description: "list files",
|
||||||
Keybindings: parseBindings("<leader>f"),
|
// Keybindings: parseBindings("<leader>f"),
|
||||||
Trigger: []string{"files"},
|
// Trigger: []string{"files"},
|
||||||
},
|
// },
|
||||||
{
|
{
|
||||||
Name: FileCloseCommand,
|
Name: FileCloseCommand,
|
||||||
Description: "close file",
|
Description: "close file",
|
||||||
@@ -323,7 +336,7 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
|
|||||||
Name: AppExitCommand,
|
Name: AppExitCommand,
|
||||||
Description: "exit the app",
|
Description: "exit the app",
|
||||||
Keybindings: parseBindings("ctrl+c", "<leader>q"),
|
Keybindings: parseBindings("ctrl+c", "<leader>q"),
|
||||||
Trigger: []string{"exit", "quit"},
|
Trigger: []string{"exit", "quit", "q"},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
registry := make(CommandRegistry)
|
registry := make(CommandRegistry)
|
||||||
@@ -331,6 +344,10 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
|
|||||||
marshalled, _ := json.Marshal(config.Keybinds)
|
marshalled, _ := json.Marshal(config.Keybinds)
|
||||||
json.Unmarshal(marshalled, &keybinds)
|
json.Unmarshal(marshalled, &keybinds)
|
||||||
for _, command := range defaults {
|
for _, command := range defaults {
|
||||||
|
// Remove share/unshare commands if sharing is disabled
|
||||||
|
if config.Share == opencode.ConfigShareDisabled && (command.Name == SessionShareCommand || command.Name == SessionUnshareCommand) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
if keybind, ok := keybinds[string(command.Name)]; ok && keybind != "" {
|
if keybind, ok := keybinds[string(command.Name)]; ok && keybind != "" {
|
||||||
command.Keybindings = parseBindings(keybind)
|
command.Keybindings = parseBindings(keybind)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
"github.com/lithammer/fuzzysearch/fuzzy"
|
"github.com/lithammer/fuzzysearch/fuzzy"
|
||||||
"github.com/sst/opencode/internal/app"
|
"github.com/sst/opencode/internal/app"
|
||||||
"github.com/sst/opencode/internal/commands"
|
"github.com/sst/opencode/internal/commands"
|
||||||
"github.com/sst/opencode/internal/components/dialog"
|
|
||||||
"github.com/sst/opencode/internal/styles"
|
"github.com/sst/opencode/internal/styles"
|
||||||
"github.com/sst/opencode/internal/theme"
|
"github.com/sst/opencode/internal/theme"
|
||||||
)
|
)
|
||||||
@@ -17,7 +16,7 @@ type CommandCompletionProvider struct {
|
|||||||
app *app.App
|
app *app.App
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCommandCompletionProvider(app *app.App) dialog.CompletionProvider {
|
func NewCommandCompletionProvider(app *app.App) CompletionProvider {
|
||||||
return &CommandCompletionProvider{app: app}
|
return &CommandCompletionProvider{app: app}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,24 +31,28 @@ func (c *CommandCompletionProvider) GetEmptyMessage() string {
|
|||||||
func (c *CommandCompletionProvider) getCommandCompletionItem(
|
func (c *CommandCompletionProvider) getCommandCompletionItem(
|
||||||
cmd commands.Command,
|
cmd commands.Command,
|
||||||
space int,
|
space int,
|
||||||
t theme.Theme,
|
) CompletionSuggestion {
|
||||||
) dialog.CompletionItemI {
|
displayFunc := func(s styles.Style) string {
|
||||||
spacer := strings.Repeat(" ", space)
|
t := theme.CurrentTheme()
|
||||||
title := " /" + cmd.PrimaryTrigger() + styles.NewStyle().
|
spacer := strings.Repeat(" ", space)
|
||||||
Foreground(t.TextMuted()).
|
display := " /" + cmd.PrimaryTrigger() + s.
|
||||||
Render(spacer+cmd.Description)
|
Foreground(t.TextMuted()).
|
||||||
|
Render(spacer+cmd.Description)
|
||||||
|
return display
|
||||||
|
}
|
||||||
|
|
||||||
value := string(cmd.Name)
|
value := string(cmd.Name)
|
||||||
return dialog.NewCompletionItem(dialog.CompletionItem{
|
return CompletionSuggestion{
|
||||||
Title: title,
|
Display: displayFunc,
|
||||||
Value: value,
|
Value: value,
|
||||||
ProviderID: c.GetId(),
|
ProviderID: c.GetId(),
|
||||||
}, dialog.WithBackgroundColor(t.BackgroundElement()))
|
RawData: cmd,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CommandCompletionProvider) GetChildEntries(
|
func (c *CommandCompletionProvider) GetChildEntries(
|
||||||
query string,
|
query string,
|
||||||
) ([]dialog.CompletionItemI, error) {
|
) ([]CompletionSuggestion, error) {
|
||||||
t := theme.CurrentTheme()
|
|
||||||
commands := c.app.Commands
|
commands := c.app.Commands
|
||||||
|
|
||||||
space := 1
|
space := 1
|
||||||
@@ -63,47 +66,42 @@ func (c *CommandCompletionProvider) GetChildEntries(
|
|||||||
sorted := commands.Sorted()
|
sorted := commands.Sorted()
|
||||||
if query == "" {
|
if query == "" {
|
||||||
// If no query, return all commands
|
// If no query, return all commands
|
||||||
items := []dialog.CompletionItemI{}
|
items := []CompletionSuggestion{}
|
||||||
for _, cmd := range sorted {
|
for _, cmd := range sorted {
|
||||||
if !cmd.HasTrigger() {
|
if !cmd.HasTrigger() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
space := space - lipgloss.Width(cmd.PrimaryTrigger())
|
space := space - lipgloss.Width(cmd.PrimaryTrigger())
|
||||||
items = append(items, c.getCommandCompletionItem(cmd, space, t))
|
items = append(items, c.getCommandCompletionItem(cmd, space))
|
||||||
}
|
}
|
||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use fuzzy matching for commands
|
|
||||||
var commandNames []string
|
var commandNames []string
|
||||||
commandMap := make(map[string]dialog.CompletionItemI)
|
commandMap := make(map[string]CompletionSuggestion)
|
||||||
|
|
||||||
for _, cmd := range sorted {
|
for _, cmd := range sorted {
|
||||||
if !cmd.HasTrigger() {
|
if !cmd.HasTrigger() {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
space := space - lipgloss.Width(cmd.PrimaryTrigger())
|
space := space - lipgloss.Width(cmd.PrimaryTrigger())
|
||||||
// Add all triggers as searchable options
|
|
||||||
for _, trigger := range cmd.Trigger {
|
for _, trigger := range cmd.Trigger {
|
||||||
commandNames = append(commandNames, trigger)
|
commandNames = append(commandNames, trigger)
|
||||||
commandMap[trigger] = c.getCommandCompletionItem(cmd, space, t)
|
commandMap[trigger] = c.getCommandCompletionItem(cmd, space)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find fuzzy matches
|
|
||||||
matches := fuzzy.RankFindFold(query, commandNames)
|
matches := fuzzy.RankFindFold(query, commandNames)
|
||||||
|
|
||||||
// Sort by score (best matches first)
|
|
||||||
sort.Sort(matches)
|
sort.Sort(matches)
|
||||||
|
|
||||||
// Convert matches to completion items, deduplicating by command name
|
// Convert matches to completion items, deduplicating by command name
|
||||||
items := []dialog.CompletionItemI{}
|
items := []CompletionSuggestion{}
|
||||||
seen := make(map[string]bool)
|
seen := make(map[string]bool)
|
||||||
for _, match := range matches {
|
for _, match := range matches {
|
||||||
if item, ok := commandMap[match.Target]; ok {
|
if item, ok := commandMap[match.Target]; ok {
|
||||||
// Use the command's value (name) as the deduplication key
|
// Use the command's value (name) as the deduplication key
|
||||||
if !seen[item.GetValue()] {
|
if !seen[item.Value] {
|
||||||
seen[item.GetValue()] = true
|
seen[item.Value] = true
|
||||||
items = append(items, item)
|
items = append(items, item)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,14 +9,13 @@ import (
|
|||||||
|
|
||||||
"github.com/sst/opencode-sdk-go"
|
"github.com/sst/opencode-sdk-go"
|
||||||
"github.com/sst/opencode/internal/app"
|
"github.com/sst/opencode/internal/app"
|
||||||
"github.com/sst/opencode/internal/components/dialog"
|
|
||||||
"github.com/sst/opencode/internal/styles"
|
"github.com/sst/opencode/internal/styles"
|
||||||
"github.com/sst/opencode/internal/theme"
|
"github.com/sst/opencode/internal/theme"
|
||||||
)
|
)
|
||||||
|
|
||||||
type filesContextGroup struct {
|
type filesContextGroup struct {
|
||||||
app *app.App
|
app *app.App
|
||||||
gitFiles []dialog.CompletionItemI
|
gitFiles []CompletionSuggestion
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cg *filesContextGroup) GetId() string {
|
func (cg *filesContextGroup) GetId() string {
|
||||||
@@ -27,12 +26,8 @@ func (cg *filesContextGroup) GetEmptyMessage() string {
|
|||||||
return "no matching files"
|
return "no matching files"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cg *filesContextGroup) getGitFiles() []dialog.CompletionItemI {
|
func (cg *filesContextGroup) getGitFiles() []CompletionSuggestion {
|
||||||
t := theme.CurrentTheme()
|
items := make([]CompletionSuggestion, 0)
|
||||||
items := make([]dialog.CompletionItemI, 0)
|
|
||||||
base := styles.NewStyle().Background(t.BackgroundElement())
|
|
||||||
green := base.Foreground(t.Success()).Render
|
|
||||||
red := base.Foreground(t.Error()).Render
|
|
||||||
|
|
||||||
status, _ := cg.app.Client.File.Status(context.Background())
|
status, _ := cg.app.Client.File.Status(context.Background())
|
||||||
if status != nil {
|
if status != nil {
|
||||||
@@ -42,21 +37,25 @@ func (cg *filesContextGroup) getGitFiles() []dialog.CompletionItemI {
|
|||||||
})
|
})
|
||||||
|
|
||||||
for _, file := range files {
|
for _, file := range files {
|
||||||
title := file.Path
|
displayFunc := func(s styles.Style) string {
|
||||||
if file.Added > 0 {
|
t := theme.CurrentTheme()
|
||||||
title += green(" +" + strconv.Itoa(int(file.Added)))
|
green := s.Foreground(t.Success()).Render
|
||||||
|
red := s.Foreground(t.Error()).Render
|
||||||
|
display := file.Path
|
||||||
|
if file.Added > 0 {
|
||||||
|
display += green(" +" + strconv.Itoa(int(file.Added)))
|
||||||
|
}
|
||||||
|
if file.Removed > 0 {
|
||||||
|
display += red(" -" + strconv.Itoa(int(file.Removed)))
|
||||||
|
}
|
||||||
|
return display
|
||||||
}
|
}
|
||||||
if file.Removed > 0 {
|
item := CompletionSuggestion{
|
||||||
title += red(" -" + strconv.Itoa(int(file.Removed)))
|
Display: displayFunc,
|
||||||
}
|
|
||||||
item := dialog.NewCompletionItem(dialog.CompletionItem{
|
|
||||||
Title: title,
|
|
||||||
Value: file.Path,
|
Value: file.Path,
|
||||||
ProviderID: cg.GetId(),
|
ProviderID: cg.GetId(),
|
||||||
Raw: file,
|
RawData: file,
|
||||||
},
|
}
|
||||||
dialog.WithBackgroundColor(t.BackgroundElement()),
|
|
||||||
)
|
|
||||||
items = append(items, item)
|
items = append(items, item)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -66,8 +65,8 @@ func (cg *filesContextGroup) getGitFiles() []dialog.CompletionItemI {
|
|||||||
|
|
||||||
func (cg *filesContextGroup) GetChildEntries(
|
func (cg *filesContextGroup) GetChildEntries(
|
||||||
query string,
|
query string,
|
||||||
) ([]dialog.CompletionItemI, error) {
|
) ([]CompletionSuggestion, error) {
|
||||||
items := make([]dialog.CompletionItemI, 0)
|
items := make([]CompletionSuggestion, 0)
|
||||||
|
|
||||||
query = strings.TrimSpace(query)
|
query = strings.TrimSpace(query)
|
||||||
if query == "" {
|
if query == "" {
|
||||||
@@ -89,7 +88,7 @@ func (cg *filesContextGroup) GetChildEntries(
|
|||||||
for _, file := range *files {
|
for _, file := range *files {
|
||||||
exists := false
|
exists := false
|
||||||
for _, existing := range cg.gitFiles {
|
for _, existing := range cg.gitFiles {
|
||||||
if existing.GetValue() == file {
|
if existing.Value == file {
|
||||||
if query != "" {
|
if query != "" {
|
||||||
items = append(items, existing)
|
items = append(items, existing)
|
||||||
}
|
}
|
||||||
@@ -97,14 +96,18 @@ func (cg *filesContextGroup) GetChildEntries(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !exists {
|
if !exists {
|
||||||
item := dialog.NewCompletionItem(dialog.CompletionItem{
|
displayFunc := func(s styles.Style) string {
|
||||||
Title: file,
|
// t := theme.CurrentTheme()
|
||||||
|
// return s.Foreground(t.Text()).Render(file)
|
||||||
|
return s.Render(file)
|
||||||
|
}
|
||||||
|
|
||||||
|
item := CompletionSuggestion{
|
||||||
|
Display: displayFunc,
|
||||||
Value: file,
|
Value: file,
|
||||||
ProviderID: cg.GetId(),
|
ProviderID: cg.GetId(),
|
||||||
Raw: file,
|
RawData: file,
|
||||||
},
|
}
|
||||||
dialog.WithBackgroundColor(theme.CurrentTheme().BackgroundElement()),
|
|
||||||
)
|
|
||||||
items = append(items, item)
|
items = append(items, item)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -112,7 +115,7 @@ func (cg *filesContextGroup) GetChildEntries(
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewFileContextGroup(app *app.App) dialog.CompletionProvider {
|
func NewFileContextGroup(app *app.App) CompletionProvider {
|
||||||
cg := &filesContextGroup{
|
cg := &filesContextGroup{
|
||||||
app: app,
|
app: app,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package completions
|
||||||
|
|
||||||
|
// CompletionProvider defines the interface for completion data providers
|
||||||
|
type CompletionProvider interface {
|
||||||
|
GetId() string
|
||||||
|
GetChildEntries(query string) ([]CompletionSuggestion, error)
|
||||||
|
GetEmptyMessage() string
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package completions
|
||||||
|
|
||||||
|
import "github.com/sst/opencode/internal/styles"
|
||||||
|
|
||||||
|
// CompletionSuggestion represents a data-only completion suggestion
|
||||||
|
// with no styling or rendering logic
|
||||||
|
type CompletionSuggestion struct {
|
||||||
|
// The text to be displayed in the list. May contain minimal inline
|
||||||
|
// ANSI styling if intrinsic to the data (e.g., git diff colors).
|
||||||
|
Display func(styles.Style) string
|
||||||
|
|
||||||
|
// The value to be used when the item is selected (e.g., inserted into the editor).
|
||||||
|
Value string
|
||||||
|
|
||||||
|
// An optional, longer description to be displayed.
|
||||||
|
Description string
|
||||||
|
|
||||||
|
// The ID of the provider that generated this suggestion.
|
||||||
|
ProviderID string
|
||||||
|
|
||||||
|
// The raw, underlying data object (e.g., opencode.Symbol, commands.Command).
|
||||||
|
// This allows the selection handler to perform rich actions.
|
||||||
|
RawData any
|
||||||
|
}
|
||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
|
|
||||||
"github.com/sst/opencode-sdk-go"
|
"github.com/sst/opencode-sdk-go"
|
||||||
"github.com/sst/opencode/internal/app"
|
"github.com/sst/opencode/internal/app"
|
||||||
"github.com/sst/opencode/internal/components/dialog"
|
|
||||||
"github.com/sst/opencode/internal/styles"
|
"github.com/sst/opencode/internal/styles"
|
||||||
"github.com/sst/opencode/internal/theme"
|
"github.com/sst/opencode/internal/theme"
|
||||||
)
|
)
|
||||||
@@ -58,8 +57,8 @@ const (
|
|||||||
|
|
||||||
func (cg *symbolsContextGroup) GetChildEntries(
|
func (cg *symbolsContextGroup) GetChildEntries(
|
||||||
query string,
|
query string,
|
||||||
) ([]dialog.CompletionItemI, error) {
|
) ([]CompletionSuggestion, error) {
|
||||||
items := make([]dialog.CompletionItemI, 0)
|
items := make([]CompletionSuggestion, 0)
|
||||||
|
|
||||||
query = strings.TrimSpace(query)
|
query = strings.TrimSpace(query)
|
||||||
if query == "" {
|
if query == "" {
|
||||||
@@ -78,40 +77,42 @@ func (cg *symbolsContextGroup) GetChildEntries(
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
t := theme.CurrentTheme()
|
|
||||||
baseStyle := styles.NewStyle().Background(t.BackgroundElement())
|
|
||||||
base := baseStyle.Render
|
|
||||||
muted := baseStyle.Foreground(t.TextMuted()).Render
|
|
||||||
|
|
||||||
for _, sym := range *symbols {
|
for _, sym := range *symbols {
|
||||||
parts := strings.Split(sym.Name, ".")
|
parts := strings.Split(sym.Name, ".")
|
||||||
lastPart := parts[len(parts)-1]
|
lastPart := parts[len(parts)-1]
|
||||||
title := base(lastPart)
|
|
||||||
|
|
||||||
uriParts := strings.Split(sym.Location.Uri, "/")
|
|
||||||
lastTwoParts := uriParts[len(uriParts)-2:]
|
|
||||||
joined := strings.Join(lastTwoParts, "/")
|
|
||||||
title += muted(fmt.Sprintf(" %s", joined))
|
|
||||||
|
|
||||||
start := int(sym.Location.Range.Start.Line)
|
start := int(sym.Location.Range.Start.Line)
|
||||||
end := int(sym.Location.Range.End.Line)
|
end := int(sym.Location.Range.End.Line)
|
||||||
title += muted(fmt.Sprintf(":L%d-%d", start, end))
|
|
||||||
|
displayFunc := func(s styles.Style) string {
|
||||||
|
t := theme.CurrentTheme()
|
||||||
|
base := s.Foreground(t.Text()).Render
|
||||||
|
muted := s.Foreground(t.TextMuted()).Render
|
||||||
|
display := base(lastPart)
|
||||||
|
|
||||||
|
uriParts := strings.Split(sym.Location.Uri, "/")
|
||||||
|
lastTwoParts := uriParts[len(uriParts)-2:]
|
||||||
|
joined := strings.Join(lastTwoParts, "/")
|
||||||
|
display += muted(fmt.Sprintf(" %s", joined))
|
||||||
|
|
||||||
|
display += muted(fmt.Sprintf(":L%d-%d", start, end))
|
||||||
|
return display
|
||||||
|
}
|
||||||
|
|
||||||
value := fmt.Sprintf("%s?start=%d&end=%d", sym.Location.Uri, start, end)
|
value := fmt.Sprintf("%s?start=%d&end=%d", sym.Location.Uri, start, end)
|
||||||
|
|
||||||
item := dialog.NewCompletionItem(dialog.CompletionItem{
|
item := CompletionSuggestion{
|
||||||
Title: title,
|
Display: displayFunc,
|
||||||
Value: value,
|
Value: value,
|
||||||
ProviderID: cg.GetId(),
|
ProviderID: cg.GetId(),
|
||||||
Raw: sym,
|
RawData: sym,
|
||||||
})
|
}
|
||||||
items = append(items, item)
|
items = append(items, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSymbolsContextGroup(app *app.App) dialog.CompletionProvider {
|
func NewSymbolsContextGroup(app *app.App) CompletionProvider {
|
||||||
return &symbolsContextGroup{
|
return &symbolsContextGroup{
|
||||||
app: app,
|
app: app,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,28 +1,28 @@
|
|||||||
package chat
|
package chat
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"hash/fnv"
|
||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
// MessageCache caches rendered messages to avoid re-rendering
|
// PartCache caches rendered messages to avoid re-rendering
|
||||||
type MessageCache struct {
|
type PartCache struct {
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
cache map[string]string
|
cache map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewMessageCache creates a new message cache
|
// NewPartCache creates a new message cache
|
||||||
func NewMessageCache() *MessageCache {
|
func NewPartCache() *PartCache {
|
||||||
return &MessageCache{
|
return &PartCache{
|
||||||
cache: make(map[string]string),
|
cache: make(map[string]string),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// generateKey creates a unique key for a message based on its content and rendering parameters
|
// generateKey creates a unique key for a message based on its content and rendering parameters
|
||||||
func (c *MessageCache) GenerateKey(params ...any) string {
|
func (c *PartCache) GenerateKey(params ...any) string {
|
||||||
h := sha256.New()
|
h := fnv.New64a()
|
||||||
for _, param := range params {
|
for _, param := range params {
|
||||||
h.Write(fmt.Appendf(nil, ":%v", param))
|
h.Write(fmt.Appendf(nil, ":%v", param))
|
||||||
}
|
}
|
||||||
@@ -30,7 +30,7 @@ func (c *MessageCache) GenerateKey(params ...any) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get retrieves a cached rendered message
|
// Get retrieves a cached rendered message
|
||||||
func (c *MessageCache) Get(key string) (string, bool) {
|
func (c *PartCache) Get(key string) (string, bool) {
|
||||||
c.mu.RLock()
|
c.mu.RLock()
|
||||||
defer c.mu.RUnlock()
|
defer c.mu.RUnlock()
|
||||||
|
|
||||||
@@ -39,14 +39,14 @@ func (c *MessageCache) Get(key string) (string, bool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Set stores a rendered message in the cache
|
// Set stores a rendered message in the cache
|
||||||
func (c *MessageCache) Set(key string, content string) {
|
func (c *PartCache) Set(key string, content string) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
c.cache[key] = content
|
c.cache[key] = content
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear removes all entries from the cache
|
// Clear removes all entries from the cache
|
||||||
func (c *MessageCache) Clear() {
|
func (c *PartCache) Clear() {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ func (c *MessageCache) Clear() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Size returns the number of cached entries
|
// Size returns the number of cached entries
|
||||||
func (c *MessageCache) Size() int {
|
func (c *PartCache) Size() int {
|
||||||
c.mu.RLock()
|
c.mu.RLock()
|
||||||
defer c.mu.RUnlock()
|
defer c.mu.RUnlock()
|
||||||
|
|
||||||
|
|||||||
@@ -27,8 +27,8 @@ import (
|
|||||||
|
|
||||||
type EditorComponent interface {
|
type EditorComponent interface {
|
||||||
tea.Model
|
tea.Model
|
||||||
View(width int) string
|
tea.ViewModel
|
||||||
Content(width int) string
|
Content() string
|
||||||
Lines() int
|
Lines() int
|
||||||
Value() string
|
Value() string
|
||||||
Length() int
|
Length() int
|
||||||
@@ -40,12 +40,14 @@ type EditorComponent interface {
|
|||||||
Paste() (tea.Model, tea.Cmd)
|
Paste() (tea.Model, tea.Cmd)
|
||||||
Newline() (tea.Model, tea.Cmd)
|
Newline() (tea.Model, tea.Cmd)
|
||||||
SetValue(value string)
|
SetValue(value string)
|
||||||
|
SetValueWithAttachments(value string)
|
||||||
SetInterruptKeyInDebounce(inDebounce bool)
|
SetInterruptKeyInDebounce(inDebounce bool)
|
||||||
SetExitKeyInDebounce(inDebounce bool)
|
SetExitKeyInDebounce(inDebounce bool)
|
||||||
}
|
}
|
||||||
|
|
||||||
type editorComponent struct {
|
type editorComponent struct {
|
||||||
app *app.App
|
app *app.App
|
||||||
|
width int
|
||||||
textarea textarea.Model
|
textarea textarea.Model
|
||||||
spinner spinner.Model
|
spinner spinner.Model
|
||||||
interruptKeyInDebounce bool
|
interruptKeyInDebounce bool
|
||||||
@@ -61,6 +63,12 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
var cmd tea.Cmd
|
var cmd tea.Cmd
|
||||||
|
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
|
case tea.WindowSizeMsg:
|
||||||
|
m.width = min(msg.Width-4, app.MAX_CONTAINER_WIDTH)
|
||||||
|
if m.app.Config.Layout == opencode.LayoutConfigStretch {
|
||||||
|
m.width = msg.Width - 4
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
case spinner.TickMsg:
|
case spinner.TickMsg:
|
||||||
m.spinner, cmd = m.spinner.Update(msg)
|
m.spinner, cmd = m.spinner.Update(msg)
|
||||||
return m, cmd
|
return m, cmd
|
||||||
@@ -87,51 +95,13 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
filePath := text
|
filePath := text
|
||||||
ext := strings.ToLower(filepath.Ext(filePath))
|
|
||||||
|
|
||||||
mediaType := ""
|
attachment := m.createAttachmentFromFile(filePath)
|
||||||
switch ext {
|
if attachment == nil {
|
||||||
case ".jpg":
|
|
||||||
mediaType = "image/jpeg"
|
|
||||||
case ".png", ".jpeg", ".gif", ".webp":
|
|
||||||
mediaType = "image/" + ext[1:]
|
|
||||||
case ".pdf":
|
|
||||||
mediaType = "application/pdf"
|
|
||||||
default:
|
|
||||||
attachment := &textarea.Attachment{
|
|
||||||
ID: uuid.NewString(),
|
|
||||||
Display: "@" + filePath,
|
|
||||||
URL: fmt.Sprintf("file://./%s", filePath),
|
|
||||||
Filename: filePath,
|
|
||||||
MediaType: "text/plain",
|
|
||||||
}
|
|
||||||
m.textarea.InsertAttachment(attachment)
|
|
||||||
m.textarea.InsertString(" ")
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
fileBytes, err := os.ReadFile(filePath)
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("Failed to read file", "error", err)
|
|
||||||
m.textarea.InsertRunesFromUserInput([]rune(msg))
|
m.textarea.InsertRunesFromUserInput([]rune(msg))
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
base64EncodedFile := base64.StdEncoding.EncodeToString(fileBytes)
|
|
||||||
url := fmt.Sprintf("data:%s;base64,%s", mediaType, base64EncodedFile)
|
|
||||||
attachmentCount := len(m.textarea.GetAttachments())
|
|
||||||
attachmentIndex := attachmentCount + 1
|
|
||||||
label := "File"
|
|
||||||
if strings.HasPrefix(mediaType, "image/") {
|
|
||||||
label = "Image"
|
|
||||||
}
|
|
||||||
|
|
||||||
attachment := &textarea.Attachment{
|
|
||||||
ID: uuid.NewString(),
|
|
||||||
MediaType: mediaType,
|
|
||||||
Display: fmt.Sprintf("[%s #%d]", label, attachmentIndex),
|
|
||||||
URL: url,
|
|
||||||
Filename: filePath,
|
|
||||||
}
|
|
||||||
m.textarea.InsertAttachment(attachment)
|
m.textarea.InsertAttachment(attachment)
|
||||||
m.textarea.InsertString(" ")
|
m.textarea.InsertString(" ")
|
||||||
case tea.ClipboardMsg:
|
case tea.ClipboardMsg:
|
||||||
@@ -142,9 +112,9 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
m.spinner = createSpinner()
|
m.spinner = createSpinner()
|
||||||
return m, tea.Batch(m.spinner.Tick, m.textarea.Focus())
|
return m, tea.Batch(m.spinner.Tick, m.textarea.Focus())
|
||||||
case dialog.CompletionSelectedMsg:
|
case dialog.CompletionSelectedMsg:
|
||||||
switch msg.Item.GetProviderID() {
|
switch msg.Item.ProviderID {
|
||||||
case "commands":
|
case "commands":
|
||||||
commandName := strings.TrimPrefix(msg.Item.GetValue(), "/")
|
commandName := strings.TrimPrefix(msg.Item.Value, "/")
|
||||||
updated, cmd := m.Clear()
|
updated, cmd := m.Clear()
|
||||||
m = updated.(*editorComponent)
|
m = updated.(*editorComponent)
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
@@ -154,7 +124,7 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
atIndex := m.textarea.LastRuneIndex('@')
|
atIndex := m.textarea.LastRuneIndex('@')
|
||||||
if atIndex == -1 {
|
if atIndex == -1 {
|
||||||
// Should not happen, but as a fallback, just insert.
|
// Should not happen, but as a fallback, just insert.
|
||||||
m.textarea.InsertString(msg.Item.GetValue() + " ")
|
m.textarea.InsertString(msg.Item.Value + " ")
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,26 +135,8 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
// Now, insert the attachment at the position where the '@' was.
|
// Now, insert the attachment at the position where the '@' was.
|
||||||
// The cursor is now at `atIndex` after the replacement.
|
// The cursor is now at `atIndex` after the replacement.
|
||||||
filePath := msg.Item.GetValue()
|
filePath := msg.Item.Value
|
||||||
extension := filepath.Ext(filePath)
|
attachment := m.createAttachmentFromPath(filePath)
|
||||||
mediaType := ""
|
|
||||||
switch extension {
|
|
||||||
case ".jpg":
|
|
||||||
mediaType = "image/jpeg"
|
|
||||||
case ".png", ".jpeg", ".gif", ".webp":
|
|
||||||
mediaType = "image/" + extension[1:]
|
|
||||||
case ".pdf":
|
|
||||||
mediaType = "application/pdf"
|
|
||||||
default:
|
|
||||||
mediaType = "text/plain"
|
|
||||||
}
|
|
||||||
attachment := &textarea.Attachment{
|
|
||||||
ID: uuid.NewString(),
|
|
||||||
Display: "@" + filePath,
|
|
||||||
URL: fmt.Sprintf("file://./%s", url.PathEscape(filePath)),
|
|
||||||
Filename: filePath,
|
|
||||||
MediaType: mediaType,
|
|
||||||
}
|
|
||||||
m.textarea.InsertAttachment(attachment)
|
m.textarea.InsertAttachment(attachment)
|
||||||
m.textarea.InsertString(" ")
|
m.textarea.InsertString(" ")
|
||||||
return m, nil
|
return m, nil
|
||||||
@@ -192,20 +144,20 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
atIndex := m.textarea.LastRuneIndex('@')
|
atIndex := m.textarea.LastRuneIndex('@')
|
||||||
if atIndex == -1 {
|
if atIndex == -1 {
|
||||||
// Should not happen, but as a fallback, just insert.
|
// Should not happen, but as a fallback, just insert.
|
||||||
m.textarea.InsertString(msg.Item.GetValue() + " ")
|
m.textarea.InsertString(msg.Item.Value + " ")
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
cursorCol := m.textarea.CursorColumn()
|
cursorCol := m.textarea.CursorColumn()
|
||||||
m.textarea.ReplaceRange(atIndex, cursorCol, "")
|
m.textarea.ReplaceRange(atIndex, cursorCol, "")
|
||||||
|
|
||||||
symbol := msg.Item.GetRaw().(opencode.Symbol)
|
symbol := msg.Item.RawData.(opencode.Symbol)
|
||||||
parts := strings.Split(symbol.Name, ".")
|
parts := strings.Split(symbol.Name, ".")
|
||||||
lastPart := parts[len(parts)-1]
|
lastPart := parts[len(parts)-1]
|
||||||
attachment := &textarea.Attachment{
|
attachment := &textarea.Attachment{
|
||||||
ID: uuid.NewString(),
|
ID: uuid.NewString(),
|
||||||
Display: "@" + lastPart,
|
Display: "@" + lastPart,
|
||||||
URL: msg.Item.GetValue(),
|
URL: msg.Item.Value,
|
||||||
Filename: lastPart,
|
Filename: lastPart,
|
||||||
MediaType: "text/plain",
|
MediaType: "text/plain",
|
||||||
}
|
}
|
||||||
@@ -213,7 +165,7 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
m.textarea.InsertString(" ")
|
m.textarea.InsertString(" ")
|
||||||
return m, nil
|
return m, nil
|
||||||
default:
|
default:
|
||||||
slog.Debug("Unknown provider", "provider", msg.Item.GetProviderID())
|
slog.Debug("Unknown provider", "provider", msg.Item.ProviderID)
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -227,7 +179,7 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
return m, tea.Batch(cmds...)
|
return m, tea.Batch(cmds...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *editorComponent) Content(width int) string {
|
func (m *editorComponent) Content() string {
|
||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
base := styles.NewStyle().Foreground(t.Text()).Background(t.Background()).Render
|
base := styles.NewStyle().Foreground(t.Text()).Background(t.Background()).Render
|
||||||
muted := styles.NewStyle().Foreground(t.TextMuted()).Background(t.Background()).Render
|
muted := styles.NewStyle().Foreground(t.TextMuted()).Background(t.Background()).Render
|
||||||
@@ -236,7 +188,7 @@ func (m *editorComponent) Content(width int) string {
|
|||||||
Bold(true)
|
Bold(true)
|
||||||
prompt := promptStyle.Render(">")
|
prompt := promptStyle.Render(">")
|
||||||
|
|
||||||
m.textarea.SetWidth(width - 6)
|
m.textarea.SetWidth(m.width - 6)
|
||||||
textarea := lipgloss.JoinHorizontal(
|
textarea := lipgloss.JoinHorizontal(
|
||||||
lipgloss.Top,
|
lipgloss.Top,
|
||||||
prompt,
|
prompt,
|
||||||
@@ -248,7 +200,7 @@ func (m *editorComponent) Content(width int) string {
|
|||||||
}
|
}
|
||||||
textarea = styles.NewStyle().
|
textarea = styles.NewStyle().
|
||||||
Background(t.BackgroundElement()).
|
Background(t.BackgroundElement()).
|
||||||
Width(width).
|
Width(m.width).
|
||||||
PaddingTop(1).
|
PaddingTop(1).
|
||||||
PaddingBottom(1).
|
PaddingBottom(1).
|
||||||
BorderStyle(lipgloss.ThickBorder()).
|
BorderStyle(lipgloss.ThickBorder()).
|
||||||
@@ -284,7 +236,7 @@ func (m *editorComponent) Content(width int) string {
|
|||||||
model = muted(m.app.Provider.Name) + base(" "+m.app.Model.Name)
|
model = muted(m.app.Provider.Name) + base(" "+m.app.Model.Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
space := width - 2 - lipgloss.Width(model) - lipgloss.Width(hint)
|
space := m.width - 2 - lipgloss.Width(model) - lipgloss.Width(hint)
|
||||||
spacer := styles.NewStyle().Background(t.Background()).Width(space).Render("")
|
spacer := styles.NewStyle().Background(t.Background()).Width(space).Render("")
|
||||||
|
|
||||||
info := hint + spacer + model
|
info := hint + spacer + model
|
||||||
@@ -294,10 +246,10 @@ func (m *editorComponent) Content(width int) string {
|
|||||||
return content
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *editorComponent) View(width int) string {
|
func (m *editorComponent) View() string {
|
||||||
if m.Lines() > 1 {
|
if m.Lines() > 1 {
|
||||||
return lipgloss.Place(
|
return lipgloss.Place(
|
||||||
width,
|
m.width,
|
||||||
5,
|
5,
|
||||||
lipgloss.Center,
|
lipgloss.Center,
|
||||||
lipgloss.Center,
|
lipgloss.Center,
|
||||||
@@ -305,7 +257,7 @@ func (m *editorComponent) View(width int) string {
|
|||||||
styles.WhitespaceStyle(theme.CurrentTheme().Background()),
|
styles.WhitespaceStyle(theme.CurrentTheme().Background()),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return m.Content(width)
|
return m.Content()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *editorComponent) Focused() bool {
|
func (m *editorComponent) Focused() bool {
|
||||||
@@ -337,6 +289,12 @@ func (m *editorComponent) Submit() (tea.Model, tea.Cmd) {
|
|||||||
if value == "" {
|
if value == "" {
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch value {
|
||||||
|
case "exit", "quit", "q", ":q":
|
||||||
|
return m, tea.Quit
|
||||||
|
}
|
||||||
|
|
||||||
if len(value) > 0 && value[len(value)-1] == '\\' {
|
if len(value) > 0 && value[len(value)-1] == '\\' {
|
||||||
// If the last character is a backslash, remove it and add a newline
|
// If the last character is a backslash, remove it and add a newline
|
||||||
m.textarea.ReplaceRange(len(value)-1, len(value), "")
|
m.textarea.ReplaceRange(len(value)-1, len(value), "")
|
||||||
@@ -411,6 +369,38 @@ func (m *editorComponent) SetValue(value string) {
|
|||||||
m.textarea.SetValue(value)
|
m.textarea.SetValue(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *editorComponent) SetValueWithAttachments(value string) {
|
||||||
|
m.textarea.Reset()
|
||||||
|
|
||||||
|
i := 0
|
||||||
|
for i < len(value) {
|
||||||
|
// Check if filepath and add attachment
|
||||||
|
if value[i] == '@' {
|
||||||
|
start := i + 1
|
||||||
|
end := start
|
||||||
|
for end < len(value) && value[end] != ' ' && value[end] != '\t' && value[end] != '\n' && value[end] != '\r' {
|
||||||
|
end++
|
||||||
|
}
|
||||||
|
|
||||||
|
if end > start {
|
||||||
|
filePath := value[start:end]
|
||||||
|
if _, err := os.Stat(filePath); err == nil {
|
||||||
|
attachment := m.createAttachmentFromFile(filePath)
|
||||||
|
if attachment != nil {
|
||||||
|
m.textarea.InsertAttachment(attachment)
|
||||||
|
i = end
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not a valid file path, insert the character normally
|
||||||
|
m.textarea.InsertRune(rune(value[i]))
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (m *editorComponent) SetExitKeyInDebounce(inDebounce bool) {
|
func (m *editorComponent) SetExitKeyInDebounce(inDebounce bool) {
|
||||||
m.exitKeyInDebounce = inDebounce
|
m.exitKeyInDebounce = inDebounce
|
||||||
}
|
}
|
||||||
@@ -491,3 +481,69 @@ func NewEditorComponent(app *app.App) EditorComponent {
|
|||||||
|
|
||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getMediaTypeFromExtension(ext string) string {
|
||||||
|
switch strings.ToLower(ext) {
|
||||||
|
case ".jpg":
|
||||||
|
return "image/jpeg"
|
||||||
|
case ".png", ".jpeg", ".gif", ".webp":
|
||||||
|
return "image/" + ext[1:]
|
||||||
|
case ".pdf":
|
||||||
|
return "application/pdf"
|
||||||
|
default:
|
||||||
|
return "text/plain"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *editorComponent) createAttachmentFromFile(filePath string) *textarea.Attachment {
|
||||||
|
ext := strings.ToLower(filepath.Ext(filePath))
|
||||||
|
mediaType := getMediaTypeFromExtension(ext)
|
||||||
|
|
||||||
|
// For text files, create a simple file reference
|
||||||
|
if mediaType == "text/plain" {
|
||||||
|
return &textarea.Attachment{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Display: "@" + filePath,
|
||||||
|
URL: fmt.Sprintf("file://./%s", filePath),
|
||||||
|
Filename: filePath,
|
||||||
|
MediaType: mediaType,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// For binary files (images, PDFs), read and encode
|
||||||
|
fileBytes, err := os.ReadFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to read file", "error", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
base64EncodedFile := base64.StdEncoding.EncodeToString(fileBytes)
|
||||||
|
url := fmt.Sprintf("data:%s;base64,%s", mediaType, base64EncodedFile)
|
||||||
|
attachmentCount := len(m.textarea.GetAttachments())
|
||||||
|
attachmentIndex := attachmentCount + 1
|
||||||
|
label := "File"
|
||||||
|
if strings.HasPrefix(mediaType, "image/") {
|
||||||
|
label = "Image"
|
||||||
|
}
|
||||||
|
|
||||||
|
return &textarea.Attachment{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
MediaType: mediaType,
|
||||||
|
Display: fmt.Sprintf("[%s #%d]", label, attachmentIndex),
|
||||||
|
URL: url,
|
||||||
|
Filename: filePath,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *editorComponent) createAttachmentFromPath(filePath string) *textarea.Attachment {
|
||||||
|
extension := filepath.Ext(filePath)
|
||||||
|
mediaType := getMediaTypeFromExtension(extension)
|
||||||
|
|
||||||
|
return &textarea.Attachment{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Display: "@" + filePath,
|
||||||
|
URL: fmt.Sprintf("file://./%s", url.PathEscape(filePath)),
|
||||||
|
Filename: filePath,
|
||||||
|
MediaType: mediaType,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -9,11 +9,11 @@ import (
|
|||||||
|
|
||||||
"github.com/charmbracelet/lipgloss/v2"
|
"github.com/charmbracelet/lipgloss/v2"
|
||||||
"github.com/charmbracelet/lipgloss/v2/compat"
|
"github.com/charmbracelet/lipgloss/v2/compat"
|
||||||
|
"github.com/charmbracelet/x/ansi"
|
||||||
|
"github.com/muesli/reflow/truncate"
|
||||||
"github.com/sst/opencode-sdk-go"
|
"github.com/sst/opencode-sdk-go"
|
||||||
"github.com/sst/opencode/internal/app"
|
"github.com/sst/opencode/internal/app"
|
||||||
"github.com/sst/opencode/internal/commands"
|
|
||||||
"github.com/sst/opencode/internal/components/diff"
|
"github.com/sst/opencode/internal/components/diff"
|
||||||
"github.com/sst/opencode/internal/layout"
|
|
||||||
"github.com/sst/opencode/internal/styles"
|
"github.com/sst/opencode/internal/styles"
|
||||||
"github.com/sst/opencode/internal/theme"
|
"github.com/sst/opencode/internal/theme"
|
||||||
"github.com/sst/opencode/internal/util"
|
"github.com/sst/opencode/internal/util"
|
||||||
@@ -109,7 +109,6 @@ func WithPaddingBottom(padding int) renderingOption {
|
|||||||
func renderContentBlock(
|
func renderContentBlock(
|
||||||
app *app.App,
|
app *app.App,
|
||||||
content string,
|
content string,
|
||||||
highlight bool,
|
|
||||||
width int,
|
width int,
|
||||||
options ...renderingOption,
|
options ...renderingOption,
|
||||||
) string {
|
) string {
|
||||||
@@ -158,18 +157,6 @@ func renderContentBlock(
|
|||||||
BorderRightBackground(t.Background())
|
BorderRightBackground(t.Background())
|
||||||
}
|
}
|
||||||
|
|
||||||
if highlight {
|
|
||||||
style = style.
|
|
||||||
BorderLeftForeground(borderColor).
|
|
||||||
BorderRightForeground(borderColor)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if highlight {
|
|
||||||
style = style.
|
|
||||||
Foreground(t.Text()).
|
|
||||||
Background(t.BackgroundElement()).
|
|
||||||
Bold(true)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
content = style.Render(content)
|
content = style.Render(content)
|
||||||
@@ -184,32 +171,6 @@ func renderContentBlock(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if highlight {
|
|
||||||
copy := app.Key(commands.MessagesCopyCommand)
|
|
||||||
// revert := app.Key(commands.MessagesRevertCommand)
|
|
||||||
|
|
||||||
background := t.Background()
|
|
||||||
header := layout.Render(
|
|
||||||
layout.FlexOptions{
|
|
||||||
Background: &background,
|
|
||||||
Direction: layout.Row,
|
|
||||||
Justify: layout.JustifyCenter,
|
|
||||||
Align: layout.AlignStretch,
|
|
||||||
Width: width - 2,
|
|
||||||
Gap: 5,
|
|
||||||
},
|
|
||||||
layout.FlexItem{
|
|
||||||
View: copy,
|
|
||||||
},
|
|
||||||
// layout.FlexItem{
|
|
||||||
// View: revert,
|
|
||||||
// },
|
|
||||||
)
|
|
||||||
header = styles.NewStyle().Background(t.Background()).Padding(0, 1).Render(header)
|
|
||||||
|
|
||||||
content = "\n\n\n" + header + "\n\n" + content + "\n\n\n"
|
|
||||||
}
|
|
||||||
|
|
||||||
return content
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,7 +180,6 @@ func renderText(
|
|||||||
text string,
|
text string,
|
||||||
author string,
|
author string,
|
||||||
showToolDetails bool,
|
showToolDetails bool,
|
||||||
highlight bool,
|
|
||||||
width int,
|
width int,
|
||||||
extra string,
|
extra string,
|
||||||
toolCalls ...opencode.ToolPart,
|
toolCalls ...opencode.ToolPart,
|
||||||
@@ -228,9 +188,6 @@ func renderText(
|
|||||||
|
|
||||||
var ts time.Time
|
var ts time.Time
|
||||||
backgroundColor := t.BackgroundPanel()
|
backgroundColor := t.BackgroundPanel()
|
||||||
if highlight {
|
|
||||||
backgroundColor = t.BackgroundElement()
|
|
||||||
}
|
|
||||||
var content string
|
var content string
|
||||||
switch casted := message.(type) {
|
switch casted := message.(type) {
|
||||||
case opencode.AssistantMessage:
|
case opencode.AssistantMessage:
|
||||||
@@ -238,8 +195,18 @@ func renderText(
|
|||||||
content = util.ToMarkdown(text, width, backgroundColor)
|
content = util.ToMarkdown(text, width, backgroundColor)
|
||||||
case opencode.UserMessage:
|
case opencode.UserMessage:
|
||||||
ts = time.UnixMilli(int64(casted.Time.Created))
|
ts = time.UnixMilli(int64(casted.Time.Created))
|
||||||
messageStyle := styles.NewStyle().Background(backgroundColor).Width(width - 6)
|
base := styles.NewStyle().Foreground(t.Text()).Background(backgroundColor)
|
||||||
content = messageStyle.Render(text)
|
words := strings.Fields(text)
|
||||||
|
for i, word := range words {
|
||||||
|
if strings.HasPrefix(word, "@") {
|
||||||
|
words[i] = base.Foreground(t.Secondary()).Render(word + " ")
|
||||||
|
} else {
|
||||||
|
words[i] = base.Render(word + " ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
text = strings.Join(words, "")
|
||||||
|
text = ansi.WordwrapWc(text, width-6, " -")
|
||||||
|
content = base.Width(width - 6).Render(text)
|
||||||
}
|
}
|
||||||
|
|
||||||
timestamp := ts.
|
timestamp := ts.
|
||||||
@@ -277,7 +244,6 @@ func renderText(
|
|||||||
return renderContentBlock(
|
return renderContentBlock(
|
||||||
app,
|
app,
|
||||||
content,
|
content,
|
||||||
highlight,
|
|
||||||
width,
|
width,
|
||||||
WithTextColor(t.Text()),
|
WithTextColor(t.Text()),
|
||||||
WithBorderColorRight(t.Secondary()),
|
WithBorderColorRight(t.Secondary()),
|
||||||
@@ -286,7 +252,6 @@ func renderText(
|
|||||||
return renderContentBlock(
|
return renderContentBlock(
|
||||||
app,
|
app,
|
||||||
content,
|
content,
|
||||||
highlight,
|
|
||||||
width,
|
width,
|
||||||
WithBorderColor(t.Accent()),
|
WithBorderColor(t.Accent()),
|
||||||
)
|
)
|
||||||
@@ -297,7 +262,6 @@ func renderText(
|
|||||||
func renderToolDetails(
|
func renderToolDetails(
|
||||||
app *app.App,
|
app *app.App,
|
||||||
toolCall opencode.ToolPart,
|
toolCall opencode.ToolPart,
|
||||||
highlight bool,
|
|
||||||
width int,
|
width int,
|
||||||
) string {
|
) string {
|
||||||
ignoredTools := []string{"todoread"}
|
ignoredTools := []string{"todoread"}
|
||||||
@@ -307,7 +271,7 @@ func renderToolDetails(
|
|||||||
|
|
||||||
if toolCall.State.Status == opencode.ToolPartStateStatusPending {
|
if toolCall.State.Status == opencode.ToolPartStateStatusPending {
|
||||||
title := renderToolTitle(toolCall, width)
|
title := renderToolTitle(toolCall, width)
|
||||||
return renderContentBlock(app, title, highlight, width)
|
return renderContentBlock(app, title, width)
|
||||||
}
|
}
|
||||||
|
|
||||||
var result *string
|
var result *string
|
||||||
@@ -332,129 +296,138 @@ func renderToolDetails(
|
|||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
backgroundColor := t.BackgroundPanel()
|
backgroundColor := t.BackgroundPanel()
|
||||||
borderColor := t.BackgroundPanel()
|
borderColor := t.BackgroundPanel()
|
||||||
if highlight {
|
defaultStyle := styles.NewStyle().Background(backgroundColor).Width(width - 6).Render
|
||||||
backgroundColor = t.BackgroundElement()
|
|
||||||
borderColor = t.BorderActive()
|
|
||||||
}
|
|
||||||
|
|
||||||
metadata := toolCall.State.Metadata.(map[string]any)
|
if toolCall.State.Metadata != nil {
|
||||||
switch toolCall.Tool {
|
metadata := toolCall.State.Metadata.(map[string]any)
|
||||||
case "read":
|
switch toolCall.Tool {
|
||||||
preview := metadata["preview"]
|
case "read":
|
||||||
if preview != nil && toolInputMap["filePath"] != nil {
|
var preview any
|
||||||
filename := toolInputMap["filePath"].(string)
|
if metadata != nil {
|
||||||
body = preview.(string)
|
preview = metadata["preview"]
|
||||||
body = util.RenderFile(filename, body, width, util.WithTruncate(6))
|
|
||||||
}
|
|
||||||
case "edit":
|
|
||||||
if filename, ok := toolInputMap["filePath"].(string); ok {
|
|
||||||
diffField := metadata["diff"]
|
|
||||||
if diffField != nil {
|
|
||||||
patch := diffField.(string)
|
|
||||||
var formattedDiff string
|
|
||||||
formattedDiff, _ = diff.FormatUnifiedDiff(
|
|
||||||
filename,
|
|
||||||
patch,
|
|
||||||
diff.WithWidth(width-2),
|
|
||||||
)
|
|
||||||
body = strings.TrimSpace(formattedDiff)
|
|
||||||
style := styles.NewStyle().
|
|
||||||
Background(backgroundColor).
|
|
||||||
Foreground(t.TextMuted()).
|
|
||||||
Padding(1, 2).
|
|
||||||
Width(width - 4)
|
|
||||||
if highlight {
|
|
||||||
style = style.Foreground(t.Text()).Bold(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
if diagnostics := renderDiagnostics(metadata, filename); diagnostics != "" {
|
|
||||||
diagnostics = style.Render(diagnostics)
|
|
||||||
body += "\n" + diagnostics
|
|
||||||
}
|
|
||||||
|
|
||||||
title := renderToolTitle(toolCall, width)
|
|
||||||
title = style.Render(title)
|
|
||||||
content := title + "\n" + body
|
|
||||||
content = renderContentBlock(
|
|
||||||
app,
|
|
||||||
content,
|
|
||||||
highlight,
|
|
||||||
width,
|
|
||||||
WithPadding(0),
|
|
||||||
WithBorderColor(borderColor),
|
|
||||||
)
|
|
||||||
return content
|
|
||||||
}
|
}
|
||||||
}
|
if preview != nil && toolInputMap["filePath"] != nil {
|
||||||
case "write":
|
filename := toolInputMap["filePath"].(string)
|
||||||
if filename, ok := toolInputMap["filePath"].(string); ok {
|
body = preview.(string)
|
||||||
if content, ok := toolInputMap["content"].(string); ok {
|
body = util.RenderFile(filename, body, width, util.WithTruncate(6))
|
||||||
body = util.RenderFile(filename, content, width)
|
}
|
||||||
if diagnostics := renderDiagnostics(metadata, filename); diagnostics != "" {
|
case "edit":
|
||||||
body += "\n\n" + diagnostics
|
if filename, ok := toolInputMap["filePath"].(string); ok {
|
||||||
|
var diffField any
|
||||||
|
if metadata != nil {
|
||||||
|
diffField = metadata["diff"]
|
||||||
|
}
|
||||||
|
if diffField != nil {
|
||||||
|
patch := diffField.(string)
|
||||||
|
var formattedDiff string
|
||||||
|
if width < 120 {
|
||||||
|
formattedDiff, _ = diff.FormatUnifiedDiff(
|
||||||
|
filename,
|
||||||
|
patch,
|
||||||
|
diff.WithWidth(width-2),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
formattedDiff, _ = diff.FormatDiff(
|
||||||
|
filename,
|
||||||
|
patch,
|
||||||
|
diff.WithWidth(width-2),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
body = strings.TrimSpace(formattedDiff)
|
||||||
|
style := styles.NewStyle().
|
||||||
|
Background(backgroundColor).
|
||||||
|
Foreground(t.TextMuted()).
|
||||||
|
Padding(1, 2).
|
||||||
|
Width(width - 4)
|
||||||
|
|
||||||
|
if diagnostics := renderDiagnostics(metadata, filename, backgroundColor, width-6); diagnostics != "" {
|
||||||
|
diagnostics = style.Render(diagnostics)
|
||||||
|
body += "\n" + diagnostics
|
||||||
|
}
|
||||||
|
|
||||||
|
title := renderToolTitle(toolCall, width)
|
||||||
|
title = style.Render(title)
|
||||||
|
content := title + "\n" + body
|
||||||
|
content = renderContentBlock(
|
||||||
|
app,
|
||||||
|
content,
|
||||||
|
width,
|
||||||
|
WithPadding(0),
|
||||||
|
WithBorderColor(borderColor),
|
||||||
|
)
|
||||||
|
return content
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
case "write":
|
||||||
case "bash":
|
if filename, ok := toolInputMap["filePath"].(string); ok {
|
||||||
stdout := metadata["stdout"]
|
if content, ok := toolInputMap["content"].(string); ok {
|
||||||
if stdout != nil {
|
body = util.RenderFile(filename, content, width)
|
||||||
command := toolInputMap["command"].(string)
|
if diagnostics := renderDiagnostics(metadata, filename, backgroundColor, width-4); diagnostics != "" {
|
||||||
body = fmt.Sprintf("```console\n> %s\n%s```", command, stdout)
|
body += "\n\n" + diagnostics
|
||||||
body = util.ToMarkdown(body, width, backgroundColor)
|
}
|
||||||
}
|
}
|
||||||
case "webfetch":
|
}
|
||||||
if format, ok := toolInputMap["format"].(string); ok && result != nil {
|
case "bash":
|
||||||
body = *result
|
stdout := metadata["stdout"]
|
||||||
body = util.TruncateHeight(body, 10)
|
if stdout != nil {
|
||||||
if format == "html" || format == "markdown" {
|
command := toolInputMap["command"].(string)
|
||||||
|
body = fmt.Sprintf("```console\n> %s\n%s```", command, stdout)
|
||||||
body = util.ToMarkdown(body, width, backgroundColor)
|
body = util.ToMarkdown(body, width, backgroundColor)
|
||||||
}
|
}
|
||||||
}
|
case "webfetch":
|
||||||
case "todowrite":
|
if format, ok := toolInputMap["format"].(string); ok && result != nil {
|
||||||
todos := metadata["todos"]
|
body = *result
|
||||||
if todos != nil {
|
body = util.TruncateHeight(body, 10)
|
||||||
for _, item := range todos.([]any) {
|
if format == "html" || format == "markdown" {
|
||||||
todo := item.(map[string]any)
|
body = util.ToMarkdown(body, width, backgroundColor)
|
||||||
content := todo["content"].(string)
|
|
||||||
switch todo["status"] {
|
|
||||||
case "completed":
|
|
||||||
body += fmt.Sprintf("- [x] %s\n", content)
|
|
||||||
case "cancelled":
|
|
||||||
// strike through cancelled todo
|
|
||||||
body += fmt.Sprintf("- [~] ~~%s~~\n", content)
|
|
||||||
case "in_progress":
|
|
||||||
// highlight in progress todo
|
|
||||||
body += fmt.Sprintf("- [ ] `%s`\n", content)
|
|
||||||
default:
|
|
||||||
body += fmt.Sprintf("- [ ] %s\n", content)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
body = util.ToMarkdown(body, width, backgroundColor)
|
case "todowrite":
|
||||||
}
|
todos := metadata["todos"]
|
||||||
case "task":
|
if todos != nil {
|
||||||
summary := metadata["summary"]
|
for _, item := range todos.([]any) {
|
||||||
if summary != nil {
|
todo := item.(map[string]any)
|
||||||
toolcalls := summary.([]any)
|
content := todo["content"].(string)
|
||||||
steps := []string{}
|
switch todo["status"] {
|
||||||
for _, item := range toolcalls {
|
case "completed":
|
||||||
data, _ := json.Marshal(item)
|
body += fmt.Sprintf("- [x] %s\n", content)
|
||||||
var toolCall opencode.ToolPart
|
case "cancelled":
|
||||||
_ = json.Unmarshal(data, &toolCall)
|
// strike through cancelled todo
|
||||||
step := renderToolTitle(toolCall, width)
|
body += fmt.Sprintf("- [~] ~~%s~~\n", content)
|
||||||
step = "∟ " + step
|
case "in_progress":
|
||||||
steps = append(steps, step)
|
// highlight in progress todo
|
||||||
|
body += fmt.Sprintf("- [ ] `%s`\n", content)
|
||||||
|
default:
|
||||||
|
body += fmt.Sprintf("- [ ] %s\n", content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
body = util.ToMarkdown(body, width, backgroundColor)
|
||||||
}
|
}
|
||||||
body = strings.Join(steps, "\n")
|
case "task":
|
||||||
|
summary := metadata["summary"]
|
||||||
|
if summary != nil {
|
||||||
|
toolcalls := summary.([]any)
|
||||||
|
steps := []string{}
|
||||||
|
for _, item := range toolcalls {
|
||||||
|
data, _ := json.Marshal(item)
|
||||||
|
var toolCall opencode.ToolPart
|
||||||
|
_ = json.Unmarshal(data, &toolCall)
|
||||||
|
step := renderToolTitle(toolCall, width)
|
||||||
|
step = "∟ " + step
|
||||||
|
steps = append(steps, step)
|
||||||
|
}
|
||||||
|
body = strings.Join(steps, "\n")
|
||||||
|
}
|
||||||
|
body = defaultStyle(body)
|
||||||
|
default:
|
||||||
|
if result == nil {
|
||||||
|
empty := ""
|
||||||
|
result = &empty
|
||||||
|
}
|
||||||
|
body = *result
|
||||||
|
body = util.TruncateHeight(body, 10)
|
||||||
|
body = defaultStyle(body)
|
||||||
}
|
}
|
||||||
body = styles.NewStyle().Width(width - 6).Render(body)
|
|
||||||
default:
|
|
||||||
if result == nil {
|
|
||||||
empty := ""
|
|
||||||
result = &empty
|
|
||||||
}
|
|
||||||
body = *result
|
|
||||||
body = util.TruncateHeight(body, 10)
|
|
||||||
body = styles.NewStyle().Width(width - 6).Render(body)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
error := ""
|
error := ""
|
||||||
@@ -473,12 +446,16 @@ func renderToolDetails(
|
|||||||
if body == "" && error == "" && result != nil {
|
if body == "" && error == "" && result != nil {
|
||||||
body = *result
|
body = *result
|
||||||
body = util.TruncateHeight(body, 10)
|
body = util.TruncateHeight(body, 10)
|
||||||
body = styles.NewStyle().Width(width - 6).Render(body)
|
body = defaultStyle(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
if body == "" {
|
||||||
|
body = defaultStyle("")
|
||||||
}
|
}
|
||||||
|
|
||||||
title := renderToolTitle(toolCall, width)
|
title := renderToolTitle(toolCall, width)
|
||||||
content := title + "\n\n" + body
|
content := title + "\n\n" + body
|
||||||
return renderContentBlock(app, content, highlight, width, WithBorderColor(borderColor))
|
return renderContentBlock(app, content, width, WithBorderColor(borderColor))
|
||||||
}
|
}
|
||||||
|
|
||||||
func renderToolName(name string) string {
|
func renderToolName(name string) string {
|
||||||
@@ -583,6 +560,8 @@ func renderToolTitle(
|
|||||||
toolName := renderToolName(toolCall.Tool)
|
toolName := renderToolName(toolCall.Tool)
|
||||||
title = fmt.Sprintf("%s %s", toolName, toolArgs)
|
title = fmt.Sprintf("%s %s", toolName, toolArgs)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
title = truncate.StringWithTail(title, uint(width-6), "...")
|
||||||
return title
|
return title
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -660,7 +639,12 @@ type Diagnostic struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// renderDiagnostics formats LSP diagnostics for display in the TUI
|
// renderDiagnostics formats LSP diagnostics for display in the TUI
|
||||||
func renderDiagnostics(metadata map[string]any, filePath string) string {
|
func renderDiagnostics(
|
||||||
|
metadata map[string]any,
|
||||||
|
filePath string,
|
||||||
|
backgroundColor compat.AdaptiveColor,
|
||||||
|
width int,
|
||||||
|
) string {
|
||||||
if diagnosticsData, ok := metadata["diagnostics"].(map[string]any); ok {
|
if diagnosticsData, ok := metadata["diagnostics"].(map[string]any); ok {
|
||||||
if fileDiagnostics, ok := diagnosticsData[filePath].([]any); ok {
|
if fileDiagnostics, ok := diagnosticsData[filePath].([]any); ok {
|
||||||
var errorDiagnostics []string
|
var errorDiagnostics []string
|
||||||
@@ -696,9 +680,15 @@ func renderDiagnostics(metadata map[string]any, filePath string) string {
|
|||||||
var result strings.Builder
|
var result strings.Builder
|
||||||
for _, diagnostic := range errorDiagnostics {
|
for _, diagnostic := range errorDiagnostics {
|
||||||
if result.Len() > 0 {
|
if result.Len() > 0 {
|
||||||
result.WriteString("\n")
|
result.WriteString("\n\n")
|
||||||
}
|
}
|
||||||
result.WriteString(styles.NewStyle().Foreground(t.Error()).Render(diagnostic))
|
diagnostic = ansi.WordwrapWc(diagnostic, width, " -")
|
||||||
|
result.WriteString(
|
||||||
|
styles.NewStyle().
|
||||||
|
Background(backgroundColor).
|
||||||
|
Foreground(t.Error()).
|
||||||
|
Render(diagnostic),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
return result.String()
|
return result.String()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"github.com/sst/opencode-sdk-go"
|
"github.com/sst/opencode-sdk-go"
|
||||||
"github.com/sst/opencode/internal/app"
|
"github.com/sst/opencode/internal/app"
|
||||||
"github.com/sst/opencode/internal/components/dialog"
|
"github.com/sst/opencode/internal/components/dialog"
|
||||||
|
"github.com/sst/opencode/internal/components/toast"
|
||||||
"github.com/sst/opencode/internal/layout"
|
"github.com/sst/opencode/internal/layout"
|
||||||
"github.com/sst/opencode/internal/styles"
|
"github.com/sst/opencode/internal/styles"
|
||||||
"github.com/sst/opencode/internal/theme"
|
"github.com/sst/opencode/internal/theme"
|
||||||
@@ -18,37 +19,30 @@ import (
|
|||||||
|
|
||||||
type MessagesComponent interface {
|
type MessagesComponent interface {
|
||||||
tea.Model
|
tea.Model
|
||||||
View(width, height int) string
|
tea.ViewModel
|
||||||
SetWidth(width int) tea.Cmd
|
|
||||||
PageUp() (tea.Model, tea.Cmd)
|
PageUp() (tea.Model, tea.Cmd)
|
||||||
PageDown() (tea.Model, tea.Cmd)
|
PageDown() (tea.Model, tea.Cmd)
|
||||||
HalfPageUp() (tea.Model, tea.Cmd)
|
HalfPageUp() (tea.Model, tea.Cmd)
|
||||||
HalfPageDown() (tea.Model, tea.Cmd)
|
HalfPageDown() (tea.Model, tea.Cmd)
|
||||||
First() (tea.Model, tea.Cmd)
|
|
||||||
Last() (tea.Model, tea.Cmd)
|
|
||||||
Previous() (tea.Model, tea.Cmd)
|
|
||||||
Next() (tea.Model, tea.Cmd)
|
|
||||||
ToolDetailsVisible() bool
|
ToolDetailsVisible() bool
|
||||||
Selected() string
|
GotoTop() (tea.Model, tea.Cmd)
|
||||||
|
GotoBottom() (tea.Model, tea.Cmd)
|
||||||
|
CopyLastMessage() (tea.Model, tea.Cmd)
|
||||||
}
|
}
|
||||||
|
|
||||||
type messagesComponent struct {
|
type messagesComponent struct {
|
||||||
width int
|
width, height int
|
||||||
app *app.App
|
app *app.App
|
||||||
|
header string
|
||||||
viewport viewport.Model
|
viewport viewport.Model
|
||||||
cache *MessageCache
|
cache *PartCache
|
||||||
rendering bool
|
rendering bool
|
||||||
showToolDetails bool
|
showToolDetails bool
|
||||||
tail bool
|
tail bool
|
||||||
partCount int
|
partCount int
|
||||||
lineCount int
|
lineCount int
|
||||||
selectedPart int
|
|
||||||
selectedText string
|
|
||||||
}
|
}
|
||||||
type renderFinishedMsg struct{}
|
type renderFinishedMsg struct{}
|
||||||
type selectedMessagePartChangedMsg struct {
|
|
||||||
part int
|
|
||||||
}
|
|
||||||
|
|
||||||
type ToggleToolDetailsMsg struct{}
|
type ToggleToolDetailsMsg struct{}
|
||||||
|
|
||||||
@@ -56,17 +50,23 @@ func (m *messagesComponent) Init() tea.Cmd {
|
|||||||
return tea.Batch(m.viewport.Init())
|
return tea.Batch(m.viewport.Init())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *messagesComponent) Selected() string {
|
|
||||||
return m.selectedText
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||||
var cmds []tea.Cmd
|
var cmds []tea.Cmd
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
|
case tea.WindowSizeMsg:
|
||||||
|
effectiveWidth := msg.Width - 4
|
||||||
|
// Clear cache on resize since width affects rendering
|
||||||
|
if m.width != effectiveWidth {
|
||||||
|
m.cache.Clear()
|
||||||
|
}
|
||||||
|
m.width = effectiveWidth
|
||||||
|
m.height = msg.Height - 7
|
||||||
|
m.viewport.SetWidth(m.width)
|
||||||
|
m.header = m.renderHeader()
|
||||||
|
return m, m.Reload()
|
||||||
case app.SendMsg:
|
case app.SendMsg:
|
||||||
m.viewport.GotoBottom()
|
m.viewport.GotoBottom()
|
||||||
m.tail = true
|
m.tail = true
|
||||||
m.selectedPart = -1
|
|
||||||
return m, nil
|
return m, nil
|
||||||
case app.OptimisticMessageAddedMsg:
|
case app.OptimisticMessageAddedMsg:
|
||||||
m.tail = true
|
m.tail = true
|
||||||
@@ -90,25 +90,21 @@ func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
if m.tail {
|
if m.tail {
|
||||||
m.viewport.GotoBottom()
|
m.viewport.GotoBottom()
|
||||||
}
|
}
|
||||||
case selectedMessagePartChangedMsg:
|
|
||||||
return m, m.Reload()
|
|
||||||
case opencode.EventListResponseEventSessionUpdated:
|
case opencode.EventListResponseEventSessionUpdated:
|
||||||
if msg.Properties.Info.ID == m.app.Session.ID {
|
if msg.Properties.Info.ID == m.app.Session.ID {
|
||||||
m.renderView(m.width)
|
m.header = m.renderHeader()
|
||||||
if m.tail {
|
|
||||||
m.viewport.GotoBottom()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
case opencode.EventListResponseEventMessageUpdated:
|
case opencode.EventListResponseEventMessageUpdated:
|
||||||
if msg.Properties.Info.SessionID == m.app.Session.ID {
|
if msg.Properties.Info.SessionID == m.app.Session.ID {
|
||||||
m.renderView(m.width)
|
m.renderView()
|
||||||
if m.tail {
|
if m.tail {
|
||||||
m.viewport.GotoBottom()
|
m.viewport.GotoBottom()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case opencode.EventListResponseEventMessagePartUpdated:
|
case opencode.EventListResponseEventMessagePartUpdated:
|
||||||
if msg.Properties.Part.SessionID == m.app.Session.ID {
|
if msg.Properties.Part.SessionID == m.app.Session.ID {
|
||||||
m.renderView(m.width)
|
m.renderView()
|
||||||
if m.tail {
|
if m.tail {
|
||||||
m.viewport.GotoBottom()
|
m.viewport.GotoBottom()
|
||||||
}
|
}
|
||||||
@@ -123,10 +119,12 @@ func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
return m, tea.Batch(cmds...)
|
return m, tea.Batch(cmds...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *messagesComponent) renderView(width int) {
|
func (m *messagesComponent) renderView() {
|
||||||
measure := util.Measure("messages.renderView")
|
measure := util.Measure("messages.renderView")
|
||||||
defer measure("messageCount", len(m.app.Messages))
|
defer measure("messageCount", len(m.app.Messages))
|
||||||
|
|
||||||
|
m.header = m.renderHeader()
|
||||||
|
|
||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
blocks := make([]string, 0)
|
blocks := make([]string, 0)
|
||||||
m.partCount = 0
|
m.partCount = 0
|
||||||
@@ -134,16 +132,23 @@ func (m *messagesComponent) renderView(width int) {
|
|||||||
|
|
||||||
orphanedToolCalls := make([]opencode.ToolPart, 0)
|
orphanedToolCalls := make([]opencode.ToolPart, 0)
|
||||||
|
|
||||||
|
width := min(m.width, app.MAX_CONTAINER_WIDTH)
|
||||||
|
if m.app.Config.Layout == opencode.LayoutConfigStretch {
|
||||||
|
width = m.width
|
||||||
|
}
|
||||||
|
|
||||||
for _, message := range m.app.Messages {
|
for _, message := range m.app.Messages {
|
||||||
var content string
|
var content string
|
||||||
var cached bool
|
var cached bool
|
||||||
|
|
||||||
switch casted := message.Info.(type) {
|
switch casted := message.Info.(type) {
|
||||||
case opencode.UserMessage:
|
case opencode.UserMessage:
|
||||||
userLoop:
|
|
||||||
for partIndex, part := range message.Parts {
|
for partIndex, part := range message.Parts {
|
||||||
switch part := part.(type) {
|
switch part := part.(type) {
|
||||||
case opencode.TextPart:
|
case opencode.TextPart:
|
||||||
|
if part.Synthetic {
|
||||||
|
continue
|
||||||
|
}
|
||||||
remainingParts := message.Parts[partIndex+1:]
|
remainingParts := message.Parts[partIndex+1:]
|
||||||
fileParts := make([]opencode.FilePart, 0)
|
fileParts := make([]opencode.FilePart, 0)
|
||||||
for _, part := range remainingParts {
|
for _, part := range remainingParts {
|
||||||
@@ -183,7 +188,7 @@ func (m *messagesComponent) renderView(width int) {
|
|||||||
flexItems...,
|
flexItems...,
|
||||||
)
|
)
|
||||||
|
|
||||||
key := m.cache.GenerateKey(casted.ID, part.Text, width, m.selectedPart == m.partCount, files)
|
key := m.cache.GenerateKey(casted.ID, part.Text, width, files)
|
||||||
content, cached = m.cache.Get(key)
|
content, cached = m.cache.Get(key)
|
||||||
if !cached {
|
if !cached {
|
||||||
content = renderText(
|
content = renderText(
|
||||||
@@ -192,18 +197,22 @@ func (m *messagesComponent) renderView(width int) {
|
|||||||
part.Text,
|
part.Text,
|
||||||
m.app.Config.Username,
|
m.app.Config.Username,
|
||||||
m.showToolDetails,
|
m.showToolDetails,
|
||||||
m.partCount == m.selectedPart,
|
|
||||||
width,
|
width,
|
||||||
files,
|
files,
|
||||||
)
|
)
|
||||||
|
content = lipgloss.PlaceHorizontal(
|
||||||
|
m.width,
|
||||||
|
lipgloss.Center,
|
||||||
|
content,
|
||||||
|
styles.WhitespaceStyle(t.Background()),
|
||||||
|
)
|
||||||
m.cache.Set(key, content)
|
m.cache.Set(key, content)
|
||||||
}
|
}
|
||||||
if content != "" {
|
if content != "" {
|
||||||
m = m.updateSelected(content, part.Text)
|
m.partCount++
|
||||||
|
m.lineCount += lipgloss.Height(content) + 1
|
||||||
blocks = append(blocks, content)
|
blocks = append(blocks, content)
|
||||||
}
|
}
|
||||||
// Only render the first text part
|
|
||||||
break userLoop
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -236,7 +245,7 @@ func (m *messagesComponent) renderView(width int) {
|
|||||||
remaining = false
|
remaining = false
|
||||||
case opencode.ToolPart:
|
case opencode.ToolPart:
|
||||||
toolCallParts = append(toolCallParts, part)
|
toolCallParts = append(toolCallParts, part)
|
||||||
if part.State.Status != opencode.ToolPartStateStatusCompleted || part.State.Status != opencode.ToolPartStateStatusError {
|
if part.State.Status != opencode.ToolPartStateStatusCompleted && part.State.Status != opencode.ToolPartStateStatusError {
|
||||||
// i don't think there's a case where a tool call isn't in result state
|
// i don't think there's a case where a tool call isn't in result state
|
||||||
// and the message time is 0, but just in case
|
// and the message time is 0, but just in case
|
||||||
finished = false
|
finished = false
|
||||||
@@ -245,7 +254,7 @@ func (m *messagesComponent) renderView(width int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if finished {
|
if finished {
|
||||||
key := m.cache.GenerateKey(casted.ID, part.Text, width, m.showToolDetails, m.selectedPart == m.partCount)
|
key := m.cache.GenerateKey(casted.ID, part.Text, width, m.showToolDetails)
|
||||||
content, cached = m.cache.Get(key)
|
content, cached = m.cache.Get(key)
|
||||||
if !cached {
|
if !cached {
|
||||||
content = renderText(
|
content = renderText(
|
||||||
@@ -254,11 +263,16 @@ func (m *messagesComponent) renderView(width int) {
|
|||||||
part.Text,
|
part.Text,
|
||||||
casted.ModelID,
|
casted.ModelID,
|
||||||
m.showToolDetails,
|
m.showToolDetails,
|
||||||
m.partCount == m.selectedPart,
|
|
||||||
width,
|
width,
|
||||||
"",
|
"",
|
||||||
toolCallParts...,
|
toolCallParts...,
|
||||||
)
|
)
|
||||||
|
content = lipgloss.PlaceHorizontal(
|
||||||
|
m.width,
|
||||||
|
lipgloss.Center,
|
||||||
|
content,
|
||||||
|
styles.WhitespaceStyle(t.Background()),
|
||||||
|
)
|
||||||
m.cache.Set(key, content)
|
m.cache.Set(key, content)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -268,14 +282,20 @@ func (m *messagesComponent) renderView(width int) {
|
|||||||
part.Text,
|
part.Text,
|
||||||
casted.ModelID,
|
casted.ModelID,
|
||||||
m.showToolDetails,
|
m.showToolDetails,
|
||||||
m.partCount == m.selectedPart,
|
|
||||||
width,
|
width,
|
||||||
"",
|
"",
|
||||||
toolCallParts...,
|
toolCallParts...,
|
||||||
)
|
)
|
||||||
|
content = lipgloss.PlaceHorizontal(
|
||||||
|
m.width,
|
||||||
|
lipgloss.Center,
|
||||||
|
content,
|
||||||
|
styles.WhitespaceStyle(t.Background()),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if content != "" {
|
if content != "" {
|
||||||
m = m.updateSelected(content, part.Text)
|
m.partCount++
|
||||||
|
m.lineCount += lipgloss.Height(content) + 1
|
||||||
blocks = append(blocks, content)
|
blocks = append(blocks, content)
|
||||||
}
|
}
|
||||||
case opencode.ToolPart:
|
case opencode.ToolPart:
|
||||||
@@ -286,21 +306,32 @@ func (m *messagesComponent) renderView(width int) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
width := width
|
||||||
|
if m.app.Config.Layout == opencode.LayoutConfigAuto &&
|
||||||
|
part.Tool == "edit" &&
|
||||||
|
part.State.Error == "" {
|
||||||
|
width = min(m.width, app.EDIT_DIFF_MAX_WIDTH)
|
||||||
|
}
|
||||||
|
|
||||||
if part.State.Status == opencode.ToolPartStateStatusCompleted || part.State.Status == opencode.ToolPartStateStatusError {
|
if part.State.Status == opencode.ToolPartStateStatusCompleted || part.State.Status == opencode.ToolPartStateStatusError {
|
||||||
key := m.cache.GenerateKey(casted.ID,
|
key := m.cache.GenerateKey(casted.ID,
|
||||||
part.ID,
|
part.ID,
|
||||||
m.showToolDetails,
|
m.showToolDetails,
|
||||||
width,
|
width,
|
||||||
m.partCount == m.selectedPart,
|
|
||||||
)
|
)
|
||||||
content, cached = m.cache.Get(key)
|
content, cached = m.cache.Get(key)
|
||||||
if !cached {
|
if !cached {
|
||||||
content = renderToolDetails(
|
content = renderToolDetails(
|
||||||
m.app,
|
m.app,
|
||||||
part,
|
part,
|
||||||
m.partCount == m.selectedPart,
|
|
||||||
width,
|
width,
|
||||||
)
|
)
|
||||||
|
content = lipgloss.PlaceHorizontal(
|
||||||
|
m.width,
|
||||||
|
lipgloss.Center,
|
||||||
|
content,
|
||||||
|
styles.WhitespaceStyle(t.Background()),
|
||||||
|
)
|
||||||
m.cache.Set(key, content)
|
m.cache.Set(key, content)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -308,12 +339,18 @@ func (m *messagesComponent) renderView(width int) {
|
|||||||
content = renderToolDetails(
|
content = renderToolDetails(
|
||||||
m.app,
|
m.app,
|
||||||
part,
|
part,
|
||||||
m.partCount == m.selectedPart,
|
|
||||||
width,
|
width,
|
||||||
)
|
)
|
||||||
|
content = lipgloss.PlaceHorizontal(
|
||||||
|
m.width,
|
||||||
|
lipgloss.Center,
|
||||||
|
content,
|
||||||
|
styles.WhitespaceStyle(t.Background()),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if content != "" {
|
if content != "" {
|
||||||
m = m.updateSelected(content, "")
|
m.partCount++
|
||||||
|
m.lineCount += lipgloss.Height(content) + 1
|
||||||
blocks = append(blocks, content)
|
blocks = append(blocks, content)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -340,44 +377,44 @@ func (m *messagesComponent) renderView(width int) {
|
|||||||
error = renderContentBlock(
|
error = renderContentBlock(
|
||||||
m.app,
|
m.app,
|
||||||
error,
|
error,
|
||||||
false,
|
|
||||||
width,
|
width,
|
||||||
WithBorderColor(t.Error()),
|
WithBorderColor(t.Error()),
|
||||||
)
|
)
|
||||||
|
error = lipgloss.PlaceHorizontal(
|
||||||
|
m.width,
|
||||||
|
lipgloss.Center,
|
||||||
|
error,
|
||||||
|
styles.WhitespaceStyle(t.Background()),
|
||||||
|
)
|
||||||
blocks = append(blocks, error)
|
blocks = append(blocks, error)
|
||||||
m.lineCount += lipgloss.Height(error) + 1
|
m.lineCount += lipgloss.Height(error) + 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
m.viewport.SetHeight(m.height - lipgloss.Height(m.header))
|
||||||
m.viewport.SetContent("\n" + strings.Join(blocks, "\n\n"))
|
m.viewport.SetContent("\n" + strings.Join(blocks, "\n\n"))
|
||||||
if m.selectedPart == m.partCount {
|
if m.tail {
|
||||||
m.viewport.GotoBottom()
|
m.viewport.GotoBottom()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *messagesComponent) updateSelected(content string, selectedText string) *messagesComponent {
|
func (m *messagesComponent) renderHeader() string {
|
||||||
if m.selectedPart == m.partCount {
|
|
||||||
m.viewport.SetYOffset(m.lineCount - (m.viewport.Height() / 2) + 4)
|
|
||||||
m.selectedText = selectedText
|
|
||||||
}
|
|
||||||
m.partCount++
|
|
||||||
m.lineCount += lipgloss.Height(content) + 1
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *messagesComponent) header(width int) string {
|
|
||||||
if m.app.Session.ID == "" {
|
if m.app.Session.ID == "" {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
headerWidth := min(m.width, app.MAX_CONTAINER_WIDTH)
|
||||||
|
if m.app.Config.Layout == opencode.LayoutConfigStretch {
|
||||||
|
headerWidth = m.width
|
||||||
|
}
|
||||||
|
|
||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
base := styles.NewStyle().Foreground(t.Text()).Background(t.Background()).Render
|
base := styles.NewStyle().Foreground(t.Text()).Background(t.Background()).Render
|
||||||
muted := styles.NewStyle().Foreground(t.TextMuted()).Background(t.Background()).Render
|
muted := styles.NewStyle().Foreground(t.TextMuted()).Background(t.Background()).Render
|
||||||
headerLines := []string{}
|
headerLines := []string{}
|
||||||
headerLines = append(
|
headerLines = append(
|
||||||
headerLines,
|
headerLines,
|
||||||
util.ToMarkdown("# "+m.app.Session.Title, width-6, t.Background()),
|
util.ToMarkdown("# "+m.app.Session.Title, headerWidth-6, t.Background()),
|
||||||
)
|
)
|
||||||
|
|
||||||
share := ""
|
share := ""
|
||||||
@@ -420,29 +457,34 @@ func (m *messagesComponent) header(width int) string {
|
|||||||
Render(formatTokensAndCost(tokens, contextWindow, cost, isSubscriptionModel))
|
Render(formatTokensAndCost(tokens, contextWindow, cost, isSubscriptionModel))
|
||||||
|
|
||||||
background := t.Background()
|
background := t.Background()
|
||||||
share = layout.Render(
|
|
||||||
|
var items []layout.FlexItem
|
||||||
|
justify := layout.JustifyEnd
|
||||||
|
|
||||||
|
if m.app.Config.Share != opencode.ConfigShareDisabled {
|
||||||
|
items = append(items, layout.FlexItem{View: share})
|
||||||
|
justify = layout.JustifySpaceBetween
|
||||||
|
}
|
||||||
|
|
||||||
|
items = append(items, layout.FlexItem{View: sessionInfo})
|
||||||
|
|
||||||
|
headerRow := layout.Render(
|
||||||
layout.FlexOptions{
|
layout.FlexOptions{
|
||||||
Background: &background,
|
Background: &background,
|
||||||
Direction: layout.Row,
|
Direction: layout.Row,
|
||||||
Justify: layout.JustifySpaceBetween,
|
Justify: justify,
|
||||||
Align: layout.AlignStretch,
|
Align: layout.AlignStretch,
|
||||||
Width: width - 6,
|
Width: headerWidth - 6,
|
||||||
},
|
|
||||||
layout.FlexItem{
|
|
||||||
View: share,
|
|
||||||
},
|
|
||||||
layout.FlexItem{
|
|
||||||
View: sessionInfo,
|
|
||||||
},
|
},
|
||||||
|
items...,
|
||||||
)
|
)
|
||||||
|
|
||||||
headerLines = append(headerLines, share)
|
headerLines = append(headerLines, headerRow)
|
||||||
|
|
||||||
header := strings.Join(headerLines, "\n")
|
header := strings.Join(headerLines, "\n")
|
||||||
|
|
||||||
header = styles.NewStyle().
|
header = styles.NewStyle().
|
||||||
Background(t.Background()).
|
Background(t.Background()).
|
||||||
Width(width).
|
Width(headerWidth).
|
||||||
PaddingLeft(2).
|
PaddingLeft(2).
|
||||||
PaddingRight(2).
|
PaddingRight(2).
|
||||||
BorderLeft(true).
|
BorderLeft(true).
|
||||||
@@ -451,6 +493,12 @@ func (m *messagesComponent) header(width int) string {
|
|||||||
BorderForeground(t.BackgroundElement()).
|
BorderForeground(t.BackgroundElement()).
|
||||||
BorderStyle(lipgloss.ThickBorder()).
|
BorderStyle(lipgloss.ThickBorder()).
|
||||||
Render(header)
|
Render(header)
|
||||||
|
header = lipgloss.PlaceHorizontal(
|
||||||
|
m.width,
|
||||||
|
lipgloss.Center,
|
||||||
|
header,
|
||||||
|
styles.WhitespaceStyle(t.Background()),
|
||||||
|
)
|
||||||
|
|
||||||
return "\n" + header + "\n"
|
return "\n" + header + "\n"
|
||||||
}
|
}
|
||||||
@@ -480,7 +528,10 @@ func formatTokensAndCost(
|
|||||||
formattedTokens = strings.Replace(formattedTokens, ".0M", "M", 1)
|
formattedTokens = strings.Replace(formattedTokens, ".0M", "M", 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
percentage := (float64(tokens) / float64(contextWindow)) * 100
|
percentage := 0.0
|
||||||
|
if contextWindow > 0 {
|
||||||
|
percentage = (float64(tokens) / float64(contextWindow)) * 100
|
||||||
|
}
|
||||||
|
|
||||||
if isSubscriptionModel {
|
if isSubscriptionModel {
|
||||||
return fmt.Sprintf(
|
return fmt.Sprintf(
|
||||||
@@ -499,44 +550,27 @@ func formatTokensAndCost(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *messagesComponent) View(width, height int) string {
|
func (m *messagesComponent) View() string {
|
||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
if m.rendering {
|
if m.rendering {
|
||||||
return lipgloss.Place(
|
return lipgloss.Place(
|
||||||
width,
|
m.width,
|
||||||
height,
|
m.height,
|
||||||
lipgloss.Center,
|
lipgloss.Center,
|
||||||
lipgloss.Center,
|
lipgloss.Center,
|
||||||
styles.NewStyle().Background(t.Background()).Render(""),
|
styles.NewStyle().Background(t.Background()).Render(""),
|
||||||
styles.WhitespaceStyle(t.Background()),
|
styles.WhitespaceStyle(t.Background()),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
header := m.header(width)
|
|
||||||
m.viewport.SetWidth(width)
|
|
||||||
m.viewport.SetHeight(height - lipgloss.Height(header))
|
|
||||||
|
|
||||||
return styles.NewStyle().
|
return styles.NewStyle().
|
||||||
Background(t.Background()).
|
Background(t.Background()).
|
||||||
Render(header + "\n" + m.viewport.View())
|
Render(m.header + "\n" + m.viewport.View())
|
||||||
}
|
|
||||||
|
|
||||||
func (m *messagesComponent) SetWidth(width int) tea.Cmd {
|
|
||||||
if m.width == width {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
// Clear cache on resize since width affects rendering
|
|
||||||
if m.width != width {
|
|
||||||
m.cache.Clear()
|
|
||||||
}
|
|
||||||
m.width = width
|
|
||||||
m.viewport.SetWidth(width)
|
|
||||||
m.renderView(width)
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *messagesComponent) Reload() tea.Cmd {
|
func (m *messagesComponent) Reload() tea.Cmd {
|
||||||
return func() tea.Msg {
|
return func() tea.Msg {
|
||||||
m.renderView(m.width)
|
m.renderView()
|
||||||
return renderFinishedMsg{}
|
return renderFinishedMsg{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -561,61 +595,50 @@ func (m *messagesComponent) HalfPageDown() (tea.Model, tea.Cmd) {
|
|||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *messagesComponent) Previous() (tea.Model, tea.Cmd) {
|
|
||||||
m.tail = false
|
|
||||||
if m.selectedPart < 0 {
|
|
||||||
m.selectedPart = m.partCount
|
|
||||||
}
|
|
||||||
m.selectedPart--
|
|
||||||
if m.selectedPart < 0 {
|
|
||||||
m.selectedPart = 0
|
|
||||||
}
|
|
||||||
return m, util.CmdHandler(selectedMessagePartChangedMsg{
|
|
||||||
part: m.selectedPart,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *messagesComponent) Next() (tea.Model, tea.Cmd) {
|
|
||||||
m.tail = false
|
|
||||||
m.selectedPart++
|
|
||||||
if m.selectedPart >= m.partCount {
|
|
||||||
m.selectedPart = m.partCount
|
|
||||||
}
|
|
||||||
return m, util.CmdHandler(selectedMessagePartChangedMsg{
|
|
||||||
part: m.selectedPart,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *messagesComponent) First() (tea.Model, tea.Cmd) {
|
|
||||||
m.selectedPart = 0
|
|
||||||
m.tail = false
|
|
||||||
return m, util.CmdHandler(selectedMessagePartChangedMsg{
|
|
||||||
part: m.selectedPart,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *messagesComponent) Last() (tea.Model, tea.Cmd) {
|
|
||||||
m.selectedPart = m.partCount - 1
|
|
||||||
m.tail = true
|
|
||||||
return m, util.CmdHandler(selectedMessagePartChangedMsg{
|
|
||||||
part: m.selectedPart,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *messagesComponent) ToolDetailsVisible() bool {
|
func (m *messagesComponent) ToolDetailsVisible() bool {
|
||||||
return m.showToolDetails
|
return m.showToolDetails
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *messagesComponent) GotoTop() (tea.Model, tea.Cmd) {
|
||||||
|
m.viewport.GotoTop()
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *messagesComponent) GotoBottom() (tea.Model, tea.Cmd) {
|
||||||
|
m.viewport.GotoBottom()
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *messagesComponent) CopyLastMessage() (tea.Model, tea.Cmd) {
|
||||||
|
if len(m.app.Messages) == 0 {
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
lastMessage := m.app.Messages[len(m.app.Messages)-1]
|
||||||
|
var lastTextPart *opencode.TextPart
|
||||||
|
for _, part := range lastMessage.Parts {
|
||||||
|
if p, ok := part.(opencode.TextPart); ok {
|
||||||
|
lastTextPart = &p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if lastTextPart == nil {
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
var cmds []tea.Cmd
|
||||||
|
cmds = append(cmds, m.app.SetClipboard(lastTextPart.Text))
|
||||||
|
cmds = append(cmds, toast.NewSuccessToast("Message copied to clipboard"))
|
||||||
|
return m, tea.Batch(cmds...)
|
||||||
|
}
|
||||||
|
|
||||||
func NewMessagesComponent(app *app.App) MessagesComponent {
|
func NewMessagesComponent(app *app.App) MessagesComponent {
|
||||||
vp := viewport.New()
|
vp := viewport.New()
|
||||||
vp.KeyMap = viewport.KeyMap{}
|
vp.KeyMap = viewport.KeyMap{}
|
||||||
|
vp.MouseWheelDelta = 4
|
||||||
|
|
||||||
return &messagesComponent{
|
return &messagesComponent{
|
||||||
app: app,
|
app: app,
|
||||||
viewport: vp,
|
viewport: vp,
|
||||||
showToolDetails: true,
|
showToolDetails: true,
|
||||||
cache: NewMessageCache(),
|
cache: NewPartCache(),
|
||||||
tail: true,
|
tail: true,
|
||||||
selectedPart: -1,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,100 +9,17 @@ import (
|
|||||||
"github.com/charmbracelet/bubbles/v2/textarea"
|
"github.com/charmbracelet/bubbles/v2/textarea"
|
||||||
tea "github.com/charmbracelet/bubbletea/v2"
|
tea "github.com/charmbracelet/bubbletea/v2"
|
||||||
"github.com/charmbracelet/lipgloss/v2"
|
"github.com/charmbracelet/lipgloss/v2"
|
||||||
"github.com/charmbracelet/lipgloss/v2/compat"
|
|
||||||
"github.com/lithammer/fuzzysearch/fuzzy"
|
"github.com/lithammer/fuzzysearch/fuzzy"
|
||||||
"github.com/muesli/reflow/truncate"
|
"github.com/muesli/reflow/truncate"
|
||||||
|
"github.com/sst/opencode/internal/completions"
|
||||||
"github.com/sst/opencode/internal/components/list"
|
"github.com/sst/opencode/internal/components/list"
|
||||||
"github.com/sst/opencode/internal/styles"
|
"github.com/sst/opencode/internal/styles"
|
||||||
"github.com/sst/opencode/internal/theme"
|
"github.com/sst/opencode/internal/theme"
|
||||||
"github.com/sst/opencode/internal/util"
|
"github.com/sst/opencode/internal/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
type CompletionItem struct {
|
|
||||||
Title string
|
|
||||||
Value string
|
|
||||||
ProviderID string
|
|
||||||
Raw any
|
|
||||||
backgroundColor *compat.AdaptiveColor
|
|
||||||
}
|
|
||||||
|
|
||||||
type CompletionItemI interface {
|
|
||||||
list.ListItem
|
|
||||||
GetValue() string
|
|
||||||
DisplayValue() string
|
|
||||||
GetProviderID() string
|
|
||||||
GetRaw() any
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ci *CompletionItem) Render(selected bool, width int, isFirstInViewport bool) string {
|
|
||||||
t := theme.CurrentTheme()
|
|
||||||
baseStyle := styles.NewStyle().Foreground(t.Text())
|
|
||||||
|
|
||||||
truncatedStr := truncate.String(string(ci.DisplayValue()), uint(width-4))
|
|
||||||
|
|
||||||
backgroundColor := t.BackgroundPanel()
|
|
||||||
if ci.backgroundColor != nil {
|
|
||||||
backgroundColor = *ci.backgroundColor
|
|
||||||
}
|
|
||||||
|
|
||||||
itemStyle := baseStyle.
|
|
||||||
Background(backgroundColor).
|
|
||||||
Padding(0, 1)
|
|
||||||
|
|
||||||
if selected {
|
|
||||||
itemStyle = itemStyle.Foreground(t.Primary())
|
|
||||||
}
|
|
||||||
|
|
||||||
title := itemStyle.Render(truncatedStr)
|
|
||||||
return title
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ci *CompletionItem) DisplayValue() string {
|
|
||||||
return ci.Title
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ci *CompletionItem) GetValue() string {
|
|
||||||
return ci.Value
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ci *CompletionItem) GetProviderID() string {
|
|
||||||
return ci.ProviderID
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ci *CompletionItem) GetRaw() any {
|
|
||||||
return ci.Raw
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ci *CompletionItem) Selectable() bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
type CompletionItemOption func(*CompletionItem)
|
|
||||||
|
|
||||||
func WithBackgroundColor(color compat.AdaptiveColor) CompletionItemOption {
|
|
||||||
return func(ci *CompletionItem) {
|
|
||||||
ci.backgroundColor = &color
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCompletionItem(
|
|
||||||
completionItem CompletionItem,
|
|
||||||
opts ...CompletionItemOption,
|
|
||||||
) CompletionItemI {
|
|
||||||
for _, opt := range opts {
|
|
||||||
opt(&completionItem)
|
|
||||||
}
|
|
||||||
return &completionItem
|
|
||||||
}
|
|
||||||
|
|
||||||
type CompletionProvider interface {
|
|
||||||
GetId() string
|
|
||||||
GetChildEntries(query string) ([]CompletionItemI, error)
|
|
||||||
GetEmptyMessage() string
|
|
||||||
}
|
|
||||||
|
|
||||||
type CompletionSelectedMsg struct {
|
type CompletionSelectedMsg struct {
|
||||||
Item CompletionItemI
|
Item completions.CompletionSuggestion
|
||||||
SearchString string
|
SearchString string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,11 +38,11 @@ type CompletionDialog interface {
|
|||||||
|
|
||||||
type completionDialogComponent struct {
|
type completionDialogComponent struct {
|
||||||
query string
|
query string
|
||||||
providers []CompletionProvider
|
providers []completions.CompletionProvider
|
||||||
width int
|
width int
|
||||||
height int
|
height int
|
||||||
pseudoSearchTextArea textarea.Model
|
pseudoSearchTextArea textarea.Model
|
||||||
list list.List[CompletionItemI]
|
list list.List[completions.CompletionSuggestion]
|
||||||
trigger string
|
trigger string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,7 +56,7 @@ var completionDialogKeys = completionDialogKeyMap{
|
|||||||
key.WithKeys("tab", "enter", "right"),
|
key.WithKeys("tab", "enter", "right"),
|
||||||
),
|
),
|
||||||
Cancel: key.NewBinding(
|
Cancel: key.NewBinding(
|
||||||
key.WithKeys(" ", "esc", "backspace", "ctrl+c"),
|
key.WithKeys("space", " ", "esc", "backspace", "ctrl+h", "ctrl+c"),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,7 +66,8 @@ func (c *completionDialogComponent) Init() tea.Cmd {
|
|||||||
|
|
||||||
func (c *completionDialogComponent) getAllCompletions(query string) tea.Cmd {
|
func (c *completionDialogComponent) getAllCompletions(query string) tea.Cmd {
|
||||||
return func() tea.Msg {
|
return func() tea.Msg {
|
||||||
allItems := make([]CompletionItemI, 0)
|
allItems := make([]completions.CompletionSuggestion, 0)
|
||||||
|
providersWithResults := 0
|
||||||
|
|
||||||
// Collect results from all providers
|
// Collect results from all providers
|
||||||
for _, provider := range c.providers {
|
for _, provider := range c.providers {
|
||||||
@@ -164,25 +82,27 @@ func (c *completionDialogComponent) getAllCompletions(query string) tea.Cmd {
|
|||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
allItems = append(allItems, items...)
|
if len(items) > 0 {
|
||||||
|
providersWithResults++
|
||||||
|
allItems = append(allItems, items...)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If there's a query, use fuzzy ranking to sort results
|
// If there's a query, use fuzzy ranking to sort results
|
||||||
if query != "" && len(allItems) > 0 {
|
if query != "" && providersWithResults > 1 {
|
||||||
|
t := theme.CurrentTheme()
|
||||||
|
baseStyle := styles.NewStyle().Background(t.BackgroundElement())
|
||||||
// Create a slice of display values for fuzzy matching
|
// Create a slice of display values for fuzzy matching
|
||||||
displayValues := make([]string, len(allItems))
|
displayValues := make([]string, len(allItems))
|
||||||
for i, item := range allItems {
|
for i, item := range allItems {
|
||||||
displayValues[i] = item.DisplayValue()
|
displayValues[i] = item.Display(baseStyle)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get fuzzy matches with ranking
|
|
||||||
matches := fuzzy.RankFindFold(query, displayValues)
|
matches := fuzzy.RankFindFold(query, displayValues)
|
||||||
|
|
||||||
// Sort by score (best matches first)
|
|
||||||
sort.Sort(matches)
|
sort.Sort(matches)
|
||||||
|
|
||||||
// Reorder items based on fuzzy ranking
|
// Reorder items based on fuzzy ranking
|
||||||
rankedItems := make([]CompletionItemI, 0, len(matches))
|
rankedItems := make([]completions.CompletionSuggestion, 0, len(matches))
|
||||||
for _, match := range matches {
|
for _, match := range matches {
|
||||||
rankedItems = append(rankedItems, allItems[match.OriginalIndex])
|
rankedItems = append(rankedItems, allItems[match.OriginalIndex])
|
||||||
}
|
}
|
||||||
@@ -196,7 +116,7 @@ func (c *completionDialogComponent) getAllCompletions(query string) tea.Cmd {
|
|||||||
func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||||
var cmds []tea.Cmd
|
var cmds []tea.Cmd
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
case []CompletionItemI:
|
case []completions.CompletionSuggestion:
|
||||||
c.list.SetItems(msg)
|
c.list.SetItems(msg)
|
||||||
case tea.KeyMsg:
|
case tea.KeyMsg:
|
||||||
if c.pseudoSearchTextArea.Focused() {
|
if c.pseudoSearchTextArea.Focused() {
|
||||||
@@ -214,7 +134,7 @@ func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
u, cmd := c.list.Update(msg)
|
u, cmd := c.list.Update(msg)
|
||||||
c.list = u.(list.List[CompletionItemI])
|
c.list = u.(list.List[completions.CompletionSuggestion])
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -230,7 +150,7 @@ func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
width := lipgloss.Width(value)
|
width := lipgloss.Width(value)
|
||||||
triggerWidth := lipgloss.Width(c.trigger)
|
triggerWidth := lipgloss.Width(c.trigger)
|
||||||
// Only close on backspace when there are no characters left, unless we're back to just the trigger
|
// Only close on backspace when there are no characters left, unless we're back to just the trigger
|
||||||
if msg.String() != "backspace" || (width <= triggerWidth && value != c.trigger) {
|
if (msg.String() != "backspace" && msg.String() != "ctrl+h") || (width <= triggerWidth && value != c.trigger) {
|
||||||
return c, c.close()
|
return c, c.close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -248,11 +168,11 @@ func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
func (c *completionDialogComponent) View() string {
|
func (c *completionDialogComponent) View() string {
|
||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
baseStyle := styles.NewStyle().Foreground(t.Text())
|
|
||||||
c.list.SetMaxWidth(c.width)
|
c.list.SetMaxWidth(c.width)
|
||||||
|
|
||||||
return baseStyle.
|
return styles.NewStyle().
|
||||||
Padding(0, 0).
|
Padding(0, 1).
|
||||||
|
Foreground(t.Text()).
|
||||||
Background(t.BackgroundElement()).
|
Background(t.BackgroundElement()).
|
||||||
BorderStyle(lipgloss.ThickBorder()).
|
BorderStyle(lipgloss.ThickBorder()).
|
||||||
BorderLeft(true).
|
BorderLeft(true).
|
||||||
@@ -271,7 +191,7 @@ func (c *completionDialogComponent) IsEmpty() bool {
|
|||||||
return c.list.IsEmpty()
|
return c.list.IsEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *completionDialogComponent) complete(item CompletionItemI) tea.Cmd {
|
func (c *completionDialogComponent) complete(item completions.CompletionSuggestion) tea.Cmd {
|
||||||
value := c.pseudoSearchTextArea.Value()
|
value := c.pseudoSearchTextArea.Value()
|
||||||
return tea.Batch(
|
return tea.Batch(
|
||||||
util.CmdHandler(CompletionSelectedMsg{
|
util.CmdHandler(CompletionSelectedMsg{
|
||||||
@@ -290,7 +210,7 @@ func (c *completionDialogComponent) close() tea.Cmd {
|
|||||||
|
|
||||||
func NewCompletionDialogComponent(
|
func NewCompletionDialogComponent(
|
||||||
trigger string,
|
trigger string,
|
||||||
providers ...CompletionProvider,
|
providers ...completions.CompletionProvider,
|
||||||
) CompletionDialog {
|
) CompletionDialog {
|
||||||
ti := textarea.New()
|
ti := textarea.New()
|
||||||
ti.SetValue(trigger)
|
ti.SetValue(trigger)
|
||||||
@@ -301,11 +221,34 @@ func NewCompletionDialogComponent(
|
|||||||
emptyMessage = providers[0].GetEmptyMessage()
|
emptyMessage = providers[0].GetEmptyMessage()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Define render function for completion suggestions
|
||||||
|
renderFunc := func(item completions.CompletionSuggestion, selected bool, width int, baseStyle styles.Style) string {
|
||||||
|
t := theme.CurrentTheme()
|
||||||
|
style := baseStyle
|
||||||
|
|
||||||
|
if selected {
|
||||||
|
style = style.Background(t.BackgroundElement()).Foreground(t.Primary())
|
||||||
|
} else {
|
||||||
|
style = style.Background(t.BackgroundElement()).Foreground(t.Text())
|
||||||
|
}
|
||||||
|
|
||||||
|
// The item.Display string already has any inline colors from the provider
|
||||||
|
truncatedStr := truncate.String(item.Display(style), uint(width-4))
|
||||||
|
return style.Width(width - 4).Render(truncatedStr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Define selectable function - all completion suggestions are selectable
|
||||||
|
selectableFunc := func(item completions.CompletionSuggestion) bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
li := list.NewListComponent(
|
li := list.NewListComponent(
|
||||||
[]CompletionItemI{},
|
list.WithItems([]completions.CompletionSuggestion{}),
|
||||||
7,
|
list.WithMaxVisibleHeight[completions.CompletionSuggestion](7),
|
||||||
emptyMessage,
|
list.WithFallbackMessage[completions.CompletionSuggestion](emptyMessage),
|
||||||
false,
|
list.WithAlphaNumericKeys[completions.CompletionSuggestion](false),
|
||||||
|
list.WithRenderFunc(renderFunc),
|
||||||
|
list.WithSelectableFunc(selectableFunc),
|
||||||
)
|
)
|
||||||
|
|
||||||
c := &completionDialogComponent{
|
c := &completionDialogComponent{
|
||||||
@@ -318,7 +261,7 @@ func NewCompletionDialogComponent(
|
|||||||
|
|
||||||
// Load initial items from all providers
|
// Load initial items from all providers
|
||||||
go func() {
|
go func() {
|
||||||
allItems := make([]CompletionItemI, 0)
|
allItems := make([]completions.CompletionSuggestion, 0)
|
||||||
for _, provider := range providers {
|
for _, provider := range providers {
|
||||||
items, err := provider.GetChildEntries("")
|
items, err := provider.GetChildEntries("")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -4,18 +4,29 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
|
|
||||||
tea "github.com/charmbracelet/bubbletea/v2"
|
tea "github.com/charmbracelet/bubbletea/v2"
|
||||||
|
"github.com/sst/opencode/internal/completions"
|
||||||
"github.com/sst/opencode/internal/components/list"
|
"github.com/sst/opencode/internal/components/list"
|
||||||
"github.com/sst/opencode/internal/components/modal"
|
"github.com/sst/opencode/internal/components/modal"
|
||||||
"github.com/sst/opencode/internal/layout"
|
"github.com/sst/opencode/internal/layout"
|
||||||
|
"github.com/sst/opencode/internal/styles"
|
||||||
|
"github.com/sst/opencode/internal/theme"
|
||||||
"github.com/sst/opencode/internal/util"
|
"github.com/sst/opencode/internal/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
findDialogWidth = 76
|
||||||
|
)
|
||||||
|
|
||||||
type FindSelectedMsg struct {
|
type FindSelectedMsg struct {
|
||||||
FilePath string
|
FilePath string
|
||||||
}
|
}
|
||||||
|
|
||||||
type FindDialogCloseMsg struct{}
|
type FindDialogCloseMsg struct{}
|
||||||
|
|
||||||
|
type findInitialSuggestionsMsg struct {
|
||||||
|
suggestions []completions.CompletionSuggestion
|
||||||
|
}
|
||||||
|
|
||||||
type FindDialog interface {
|
type FindDialog interface {
|
||||||
layout.Modal
|
layout.Modal
|
||||||
tea.Model
|
tea.Model
|
||||||
@@ -25,32 +36,102 @@ type FindDialog interface {
|
|||||||
IsEmpty() bool
|
IsEmpty() bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// findItem is a custom list item for file suggestions
|
||||||
|
type findItem struct {
|
||||||
|
suggestion completions.CompletionSuggestion
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f findItem) Render(
|
||||||
|
selected bool,
|
||||||
|
width int,
|
||||||
|
baseStyle styles.Style,
|
||||||
|
) string {
|
||||||
|
t := theme.CurrentTheme()
|
||||||
|
|
||||||
|
itemStyle := baseStyle.
|
||||||
|
Background(t.BackgroundPanel()).
|
||||||
|
Foreground(t.TextMuted())
|
||||||
|
|
||||||
|
if selected {
|
||||||
|
itemStyle = itemStyle.Foreground(t.Primary())
|
||||||
|
}
|
||||||
|
|
||||||
|
return itemStyle.PaddingLeft(1).Render(f.suggestion.Display(itemStyle))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f findItem) Selectable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
type findDialogComponent struct {
|
type findDialogComponent struct {
|
||||||
completionProvider CompletionProvider
|
completionProvider completions.CompletionProvider
|
||||||
|
allSuggestions []completions.CompletionSuggestion
|
||||||
width, height int
|
width, height int
|
||||||
modal *modal.Modal
|
modal *modal.Modal
|
||||||
searchDialog *SearchDialog
|
searchDialog *SearchDialog
|
||||||
|
dialogWidth int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *findDialogComponent) Init() tea.Cmd {
|
func (f *findDialogComponent) Init() tea.Cmd {
|
||||||
return f.searchDialog.Init()
|
return tea.Batch(
|
||||||
|
f.loadInitialSuggestions(),
|
||||||
|
f.searchDialog.Init(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *findDialogComponent) loadInitialSuggestions() tea.Cmd {
|
||||||
|
return func() tea.Msg {
|
||||||
|
items, err := f.completionProvider.GetChildEntries("")
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to get initial completion items", "error", err)
|
||||||
|
return findInitialSuggestionsMsg{suggestions: []completions.CompletionSuggestion{}}
|
||||||
|
}
|
||||||
|
return findInitialSuggestionsMsg{suggestions: items}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *findDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
func (f *findDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
case []CompletionItemI:
|
case findInitialSuggestionsMsg:
|
||||||
// Convert CompletionItemI to list.ListItem
|
// Handle initial suggestions setup
|
||||||
items := make([]list.ListItem, len(msg))
|
f.allSuggestions = msg.suggestions
|
||||||
for i, item := range msg {
|
|
||||||
items[i] = item
|
// Calculate dialog width
|
||||||
|
f.dialogWidth = f.calculateDialogWidth()
|
||||||
|
|
||||||
|
// Initialize search dialog with calculated width
|
||||||
|
f.searchDialog = NewSearchDialog("Search files...", 10)
|
||||||
|
f.searchDialog.SetWidth(f.dialogWidth)
|
||||||
|
|
||||||
|
// Convert to list items
|
||||||
|
items := make([]list.Item, len(f.allSuggestions))
|
||||||
|
for i, suggestion := range f.allSuggestions {
|
||||||
|
items[i] = findItem{suggestion: suggestion}
|
||||||
|
}
|
||||||
|
f.searchDialog.SetItems(items)
|
||||||
|
|
||||||
|
// Update modal with calculated width
|
||||||
|
f.modal = modal.New(
|
||||||
|
modal.WithTitle("Find Files"),
|
||||||
|
modal.WithMaxWidth(f.dialogWidth+4),
|
||||||
|
)
|
||||||
|
|
||||||
|
return f, f.searchDialog.Init()
|
||||||
|
|
||||||
|
case []completions.CompletionSuggestion:
|
||||||
|
// Store suggestions and convert to findItem for the search dialog
|
||||||
|
f.allSuggestions = msg
|
||||||
|
items := make([]list.Item, len(msg))
|
||||||
|
for i, suggestion := range msg {
|
||||||
|
items[i] = findItem{suggestion: suggestion}
|
||||||
}
|
}
|
||||||
f.searchDialog.SetItems(items)
|
f.searchDialog.SetItems(items)
|
||||||
return f, nil
|
return f, nil
|
||||||
|
|
||||||
case SearchSelectionMsg:
|
case SearchSelectionMsg:
|
||||||
// Handle selection from search dialog
|
// Handle selection from search dialog - now we can directly access the suggestion
|
||||||
if item, ok := msg.Item.(CompletionItemI); ok {
|
if item, ok := msg.Item.(findItem); ok {
|
||||||
return f, f.selectFile(item)
|
return f, f.selectFile(item.suggestion)
|
||||||
}
|
}
|
||||||
return f, nil
|
return f, nil
|
||||||
|
|
||||||
@@ -63,9 +144,26 @@ func (f *findDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
items, err := f.completionProvider.GetChildEntries(msg.Query)
|
items, err := f.completionProvider.GetChildEntries(msg.Query)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Failed to get completion items", "error", err)
|
slog.Error("Failed to get completion items", "error", err)
|
||||||
|
return []completions.CompletionSuggestion{}
|
||||||
}
|
}
|
||||||
return items
|
return items
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case tea.WindowSizeMsg:
|
||||||
|
f.width = msg.Width
|
||||||
|
f.height = msg.Height
|
||||||
|
// Recalculate width based on new viewport size
|
||||||
|
oldWidth := f.dialogWidth
|
||||||
|
f.dialogWidth = f.calculateDialogWidth()
|
||||||
|
if oldWidth != f.dialogWidth {
|
||||||
|
f.searchDialog.SetWidth(f.dialogWidth)
|
||||||
|
// Update modal max width too
|
||||||
|
f.modal = modal.New(
|
||||||
|
modal.WithTitle("Find Files"),
|
||||||
|
modal.WithMaxWidth(f.dialogWidth+4),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
f.searchDialog.SetHeight(msg.Height)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Forward all other messages to the search dialog
|
// Forward all other messages to the search dialog
|
||||||
@@ -78,9 +176,17 @@ func (f *findDialogComponent) View() string {
|
|||||||
return f.searchDialog.View()
|
return f.searchDialog.View()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *findDialogComponent) calculateDialogWidth() int {
|
||||||
|
// Use fixed width unless viewport is smaller
|
||||||
|
if f.width > 0 && f.width < findDialogWidth+10 {
|
||||||
|
return f.width - 10
|
||||||
|
}
|
||||||
|
return findDialogWidth
|
||||||
|
}
|
||||||
|
|
||||||
func (f *findDialogComponent) SetWidth(width int) {
|
func (f *findDialogComponent) SetWidth(width int) {
|
||||||
f.width = width
|
f.width = width
|
||||||
f.searchDialog.SetWidth(width - 4)
|
f.searchDialog.SetWidth(f.dialogWidth)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *findDialogComponent) SetHeight(height int) {
|
func (f *findDialogComponent) SetHeight(height int) {
|
||||||
@@ -91,11 +197,11 @@ func (f *findDialogComponent) IsEmpty() bool {
|
|||||||
return f.searchDialog.GetQuery() == ""
|
return f.searchDialog.GetQuery() == ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *findDialogComponent) selectFile(item CompletionItemI) tea.Cmd {
|
func (f *findDialogComponent) selectFile(item completions.CompletionSuggestion) tea.Cmd {
|
||||||
return tea.Sequence(
|
return tea.Sequence(
|
||||||
f.Close(),
|
f.Close(),
|
||||||
util.CmdHandler(FindSelectedMsg{
|
util.CmdHandler(FindSelectedMsg{
|
||||||
FilePath: item.GetValue(),
|
FilePath: item.Value,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -110,30 +216,21 @@ func (f *findDialogComponent) Close() tea.Cmd {
|
|||||||
return util.CmdHandler(modal.CloseModalMsg{})
|
return util.CmdHandler(modal.CloseModalMsg{})
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewFindDialog(completionProvider CompletionProvider) FindDialog {
|
func NewFindDialog(completionProvider completions.CompletionProvider) FindDialog {
|
||||||
searchDialog := NewSearchDialog("Search files...", 10)
|
component := &findDialogComponent{
|
||||||
|
|
||||||
// Initialize with empty query to get initial items
|
|
||||||
go func() {
|
|
||||||
items, err := completionProvider.GetChildEntries("")
|
|
||||||
if err != nil {
|
|
||||||
slog.Error("Failed to get completion items", "error", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Convert CompletionItemI to list.ListItem
|
|
||||||
listItems := make([]list.ListItem, len(items))
|
|
||||||
for i, item := range items {
|
|
||||||
listItems[i] = item
|
|
||||||
}
|
|
||||||
searchDialog.SetItems(listItems)
|
|
||||||
}()
|
|
||||||
|
|
||||||
return &findDialogComponent{
|
|
||||||
completionProvider: completionProvider,
|
completionProvider: completionProvider,
|
||||||
searchDialog: searchDialog,
|
dialogWidth: findDialogWidth,
|
||||||
modal: modal.New(
|
allSuggestions: []completions.CompletionSuggestion{},
|
||||||
modal.WithTitle("Find Files"),
|
|
||||||
modal.WithMaxWidth(80),
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create search dialog and modal with fixed width
|
||||||
|
component.searchDialog = NewSearchDialog("Search files...", 10)
|
||||||
|
component.searchDialog.SetWidth(findDialogWidth)
|
||||||
|
|
||||||
|
component.modal = modal.New(
|
||||||
|
modal.WithTitle("Find Files"),
|
||||||
|
modal.WithMaxWidth(findDialogWidth+4),
|
||||||
|
)
|
||||||
|
|
||||||
|
return component
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package dialog
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"slices"
|
|
||||||
"sort"
|
"sort"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -24,6 +23,7 @@ const (
|
|||||||
numVisibleModels = 10
|
numVisibleModels = 10
|
||||||
minDialogWidth = 40
|
minDialogWidth = 40
|
||||||
maxDialogWidth = 80
|
maxDialogWidth = 80
|
||||||
|
maxRecentModels = 5
|
||||||
)
|
)
|
||||||
|
|
||||||
// ModelDialog interface for the model selection dialog
|
// ModelDialog interface for the model selection dialog
|
||||||
@@ -46,42 +46,41 @@ type ModelWithProvider struct {
|
|||||||
Provider opencode.Provider
|
Provider opencode.Provider
|
||||||
}
|
}
|
||||||
|
|
||||||
type ModelItem struct {
|
// modelItem is a custom list item for model selections
|
||||||
ModelName string
|
type modelItem struct {
|
||||||
ProviderName string
|
model ModelWithProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *ModelItem) Render(selected bool, width int, isFirstInViewport bool) string {
|
func (m modelItem) Render(
|
||||||
|
selected bool,
|
||||||
|
width int,
|
||||||
|
baseStyle styles.Style,
|
||||||
|
) string {
|
||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
|
|
||||||
|
itemStyle := baseStyle.
|
||||||
|
Background(t.BackgroundPanel()).
|
||||||
|
Foreground(t.Text())
|
||||||
|
|
||||||
if selected {
|
if selected {
|
||||||
displayText := fmt.Sprintf("%s (%s)", m.ModelName, m.ProviderName)
|
itemStyle = itemStyle.Foreground(t.Primary())
|
||||||
return styles.NewStyle().
|
|
||||||
Background(t.Primary()).
|
|
||||||
Foreground(t.BackgroundPanel()).
|
|
||||||
Width(width).
|
|
||||||
PaddingLeft(1).
|
|
||||||
Render(displayText)
|
|
||||||
} else {
|
|
||||||
modelStyle := styles.NewStyle().
|
|
||||||
Foreground(t.Text()).
|
|
||||||
Background(t.BackgroundPanel())
|
|
||||||
providerStyle := styles.NewStyle().
|
|
||||||
Foreground(t.TextMuted()).
|
|
||||||
Background(t.BackgroundPanel())
|
|
||||||
|
|
||||||
modelPart := modelStyle.Render(m.ModelName)
|
|
||||||
providerPart := providerStyle.Render(fmt.Sprintf(" (%s)", m.ProviderName))
|
|
||||||
|
|
||||||
combinedText := modelPart + providerPart
|
|
||||||
return styles.NewStyle().
|
|
||||||
Background(t.BackgroundPanel()).
|
|
||||||
PaddingLeft(1).
|
|
||||||
Render(combinedText)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
providerStyle := baseStyle.
|
||||||
|
Foreground(t.TextMuted()).
|
||||||
|
Background(t.BackgroundPanel())
|
||||||
|
|
||||||
|
modelPart := itemStyle.Render(m.model.Model.Name)
|
||||||
|
providerPart := providerStyle.Render(fmt.Sprintf(" %s", m.model.Provider.Name))
|
||||||
|
|
||||||
|
combinedText := modelPart + providerPart
|
||||||
|
return baseStyle.
|
||||||
|
Background(t.BackgroundPanel()).
|
||||||
|
PaddingLeft(1).
|
||||||
|
Render(combinedText)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *ModelItem) Selectable() bool {
|
func (m modelItem) Selectable() bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,26 +109,31 @@ func (m *modelDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
case SearchSelectionMsg:
|
case SearchSelectionMsg:
|
||||||
// Handle selection from search dialog
|
// Handle selection from search dialog
|
||||||
if modelItem, ok := msg.Item.(*ModelItem); ok {
|
if item, ok := msg.Item.(modelItem); ok {
|
||||||
// Find the corresponding ModelWithProvider
|
return m, tea.Sequence(
|
||||||
for _, model := range m.allModels {
|
util.CmdHandler(modal.CloseModalMsg{}),
|
||||||
if model.Model.Name == modelItem.ModelName && model.Provider.Name == modelItem.ProviderName {
|
util.CmdHandler(
|
||||||
return m, tea.Sequence(
|
app.ModelSelectedMsg{
|
||||||
util.CmdHandler(modal.CloseModalMsg{}),
|
Provider: item.model.Provider,
|
||||||
util.CmdHandler(
|
Model: item.model.Model,
|
||||||
app.ModelSelectedMsg{
|
}),
|
||||||
Provider: model.Provider,
|
)
|
||||||
Model: model.Model,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return m, util.CmdHandler(modal.CloseModalMsg{})
|
return m, util.CmdHandler(modal.CloseModalMsg{})
|
||||||
|
|
||||||
case SearchCancelledMsg:
|
case SearchCancelledMsg:
|
||||||
return m, util.CmdHandler(modal.CloseModalMsg{})
|
return m, util.CmdHandler(modal.CloseModalMsg{})
|
||||||
|
|
||||||
|
case SearchRemoveItemMsg:
|
||||||
|
if item, ok := msg.Item.(modelItem); ok {
|
||||||
|
if m.isModelInRecentSection(item.model, msg.Index) {
|
||||||
|
m.app.State.RemoveModelFromRecentlyUsed(item.model.Provider.ID, item.model.Model.ID)
|
||||||
|
m.app.SaveState()
|
||||||
|
items := m.buildDisplayList(m.searchDialog.GetQuery())
|
||||||
|
m.searchDialog.SetItems(items)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
|
||||||
case SearchQueryChangedMsg:
|
case SearchQueryChangedMsg:
|
||||||
// Update the list based on search query
|
// Update the list based on search query
|
||||||
items := m.buildDisplayList(msg.Query)
|
items := m.buildDisplayList(msg.Query)
|
||||||
@@ -152,13 +156,13 @@ func (m *modelDialog) View() string {
|
|||||||
return m.searchDialog.View()
|
return m.searchDialog.View()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *modelDialog) calculateOptimalWidth(modelItems []ModelItem) int {
|
func (m *modelDialog) calculateOptimalWidth(models []ModelWithProvider) int {
|
||||||
maxWidth := minDialogWidth
|
maxWidth := minDialogWidth
|
||||||
|
|
||||||
for _, item := range modelItems {
|
for _, model := range models {
|
||||||
// Calculate the width needed for this item: "ModelName (ProviderName)"
|
// Calculate the width needed for this item: "ModelName (ProviderName)"
|
||||||
// Add 4 for the parentheses, space, and some padding
|
// Add 4 for the parentheses, space, and some padding
|
||||||
itemWidth := len(item.ModelName) + len(item.ProviderName) + 4
|
itemWidth := len(model.Model.Name) + len(model.Provider.Name) + 4
|
||||||
if itemWidth > maxWidth {
|
if itemWidth > maxWidth {
|
||||||
maxWidth = itemWidth
|
maxWidth = itemWidth
|
||||||
}
|
}
|
||||||
@@ -187,14 +191,7 @@ func (m *modelDialog) setupAllModels() {
|
|||||||
m.sortModels()
|
m.sortModels()
|
||||||
|
|
||||||
// Calculate optimal width based on all models
|
// Calculate optimal width based on all models
|
||||||
modelItems := make([]ModelItem, len(m.allModels))
|
m.dialogWidth = m.calculateOptimalWidth(m.allModels)
|
||||||
for i, modelWithProvider := range m.allModels {
|
|
||||||
modelItems[i] = ModelItem{
|
|
||||||
ModelName: modelWithProvider.Model.Name,
|
|
||||||
ProviderName: modelWithProvider.Provider.Name,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
m.dialogWidth = m.calculateOptimalWidth(modelItems)
|
|
||||||
|
|
||||||
// Initialize search dialog
|
// Initialize search dialog
|
||||||
m.searchDialog = NewSearchDialog("Search models...", numVisibleModels)
|
m.searchDialog = NewSearchDialog("Search models...", numVisibleModels)
|
||||||
@@ -266,7 +263,7 @@ func (m *modelDialog) getModelUsageTime(providerID, modelID string) time.Time {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// buildDisplayList creates the list items based on search query
|
// buildDisplayList creates the list items based on search query
|
||||||
func (m *modelDialog) buildDisplayList(query string) []list.ListItem {
|
func (m *modelDialog) buildDisplayList(query string) []list.Item {
|
||||||
if query != "" {
|
if query != "" {
|
||||||
// Search mode: use fuzzy matching
|
// Search mode: use fuzzy matching
|
||||||
return m.buildSearchResults(query)
|
return m.buildSearchResults(query)
|
||||||
@@ -277,7 +274,7 @@ func (m *modelDialog) buildDisplayList(query string) []list.ListItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// buildSearchResults creates a flat list of search results using fuzzy matching
|
// buildSearchResults creates a flat list of search results using fuzzy matching
|
||||||
func (m *modelDialog) buildSearchResults(query string) []list.ListItem {
|
func (m *modelDialog) buildSearchResults(query string) []list.Item {
|
||||||
type modelMatch struct {
|
type modelMatch struct {
|
||||||
model ModelWithProvider
|
model ModelWithProvider
|
||||||
score int
|
score int
|
||||||
@@ -300,39 +297,33 @@ func (m *modelDialog) buildSearchResults(query string) []list.ListItem {
|
|||||||
matches := fuzzy.RankFindFold(query, modelNames)
|
matches := fuzzy.RankFindFold(query, modelNames)
|
||||||
sort.Sort(matches)
|
sort.Sort(matches)
|
||||||
|
|
||||||
items := []list.ListItem{}
|
items := []list.Item{}
|
||||||
|
seenModels := make(map[string]bool)
|
||||||
|
|
||||||
for _, match := range matches {
|
for _, match := range matches {
|
||||||
model := modelMap[match.Target]
|
model := modelMap[match.Target]
|
||||||
existingItem := slices.IndexFunc(items, func(item list.ListItem) bool {
|
// Create a unique key to avoid duplicates
|
||||||
castedItem := item.(*ModelItem)
|
key := fmt.Sprintf("%s:%s", model.Provider.ID, model.Model.ID)
|
||||||
return castedItem.ModelName == model.Model.Name &&
|
if seenModels[key] {
|
||||||
castedItem.ProviderName == model.Provider.Name
|
|
||||||
})
|
|
||||||
if existingItem != -1 {
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
items = append(items, &ModelItem{
|
seenModels[key] = true
|
||||||
ModelName: model.Model.Name,
|
items = append(items, modelItem{model: model})
|
||||||
ProviderName: model.Provider.Name,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return items
|
return items
|
||||||
}
|
}
|
||||||
|
|
||||||
// buildGroupedResults creates a grouped list with Recent section and provider groups
|
// buildGroupedResults creates a grouped list with Recent section and provider groups
|
||||||
func (m *modelDialog) buildGroupedResults() []list.ListItem {
|
func (m *modelDialog) buildGroupedResults() []list.Item {
|
||||||
var items []list.ListItem
|
var items []list.Item
|
||||||
|
|
||||||
// Add Recent section
|
// Add Recent section
|
||||||
recentModels := m.getRecentModels(5)
|
recentModels := m.getRecentModels(maxRecentModels)
|
||||||
if len(recentModels) > 0 {
|
if len(recentModels) > 0 {
|
||||||
items = append(items, list.HeaderItem("Recent"))
|
items = append(items, list.HeaderItem("Recent"))
|
||||||
for _, model := range recentModels {
|
for _, model := range recentModels {
|
||||||
items = append(items, &ModelItem{
|
items = append(items, modelItem{model: model})
|
||||||
ModelName: model.Model.Name,
|
|
||||||
ProviderName: model.Provider.Name,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -390,10 +381,7 @@ func (m *modelDialog) buildGroupedResults() []list.ListItem {
|
|||||||
|
|
||||||
// Add models in this provider group
|
// Add models in this provider group
|
||||||
for _, model := range models {
|
for _, model := range models {
|
||||||
items = append(items, &ModelItem{
|
items = append(items, modelItem{model: model})
|
||||||
ModelName: model.Model.Name,
|
|
||||||
ProviderName: model.Provider.Name,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -422,6 +410,28 @@ func (m *modelDialog) getRecentModels(limit int) []ModelWithProvider {
|
|||||||
return recentModels
|
return recentModels
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *modelDialog) isModelInRecentSection(model ModelWithProvider, index int) bool {
|
||||||
|
// Only check if we're in grouped mode (no search query)
|
||||||
|
if m.searchDialog.GetQuery() != "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
recentModels := m.getRecentModels(maxRecentModels)
|
||||||
|
if len(recentModels) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Index 0 is the "Recent" header, so recent models are at indices 1 to len(recentModels)
|
||||||
|
if index >= 1 && index <= len(recentModels) {
|
||||||
|
if index-1 < len(recentModels) {
|
||||||
|
recentModel := recentModels[index-1]
|
||||||
|
return recentModel.Provider.ID == model.Provider.ID && recentModel.Model.ID == model.Model.ID
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func (m *modelDialog) Render(background string) string {
|
func (m *modelDialog) Render(background string) string {
|
||||||
return m.modal.Render(m.View(), background)
|
return m.modal.Render(m.View(), background)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,496 +0,0 @@
|
|||||||
package dialog
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/charmbracelet/bubbles/v2/key"
|
|
||||||
"github.com/charmbracelet/bubbles/v2/viewport"
|
|
||||||
tea "github.com/charmbracelet/bubbletea/v2"
|
|
||||||
"github.com/charmbracelet/lipgloss/v2"
|
|
||||||
"github.com/sst/opencode/internal/styles"
|
|
||||||
"github.com/sst/opencode/internal/theme"
|
|
||||||
"github.com/sst/opencode/internal/util"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
type PermissionAction string
|
|
||||||
|
|
||||||
// Permission responses
|
|
||||||
const (
|
|
||||||
PermissionAllow PermissionAction = "allow"
|
|
||||||
PermissionAllowForSession PermissionAction = "allow_session"
|
|
||||||
PermissionDeny PermissionAction = "deny"
|
|
||||||
)
|
|
||||||
|
|
||||||
// PermissionResponseMsg represents the user's response to a permission request
|
|
||||||
type PermissionResponseMsg struct {
|
|
||||||
// Permission permission.PermissionRequest
|
|
||||||
Action PermissionAction
|
|
||||||
}
|
|
||||||
|
|
||||||
// PermissionDialogComponent interface for permission dialog component
|
|
||||||
type PermissionDialogComponent interface {
|
|
||||||
tea.Model
|
|
||||||
tea.ViewModel
|
|
||||||
// SetPermissions(permission permission.PermissionRequest) tea.Cmd
|
|
||||||
}
|
|
||||||
|
|
||||||
type permissionsMapping struct {
|
|
||||||
Left key.Binding
|
|
||||||
Right key.Binding
|
|
||||||
EnterSpace key.Binding
|
|
||||||
Allow key.Binding
|
|
||||||
AllowSession key.Binding
|
|
||||||
Deny key.Binding
|
|
||||||
Tab key.Binding
|
|
||||||
}
|
|
||||||
|
|
||||||
var permissionsKeys = permissionsMapping{
|
|
||||||
Left: key.NewBinding(
|
|
||||||
key.WithKeys("left"),
|
|
||||||
key.WithHelp("←", "switch options"),
|
|
||||||
),
|
|
||||||
Right: key.NewBinding(
|
|
||||||
key.WithKeys("right"),
|
|
||||||
key.WithHelp("→", "switch options"),
|
|
||||||
),
|
|
||||||
EnterSpace: key.NewBinding(
|
|
||||||
key.WithKeys("enter", " "),
|
|
||||||
key.WithHelp("enter/space", "confirm"),
|
|
||||||
),
|
|
||||||
Allow: key.NewBinding(
|
|
||||||
key.WithKeys("a"),
|
|
||||||
key.WithHelp("a", "allow"),
|
|
||||||
),
|
|
||||||
AllowSession: key.NewBinding(
|
|
||||||
key.WithKeys("s"),
|
|
||||||
key.WithHelp("s", "allow for session"),
|
|
||||||
),
|
|
||||||
Deny: key.NewBinding(
|
|
||||||
key.WithKeys("d"),
|
|
||||||
key.WithHelp("d", "deny"),
|
|
||||||
),
|
|
||||||
Tab: key.NewBinding(
|
|
||||||
key.WithKeys("tab"),
|
|
||||||
key.WithHelp("tab", "switch options"),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
|
|
||||||
// permissionDialogComponent is the implementation of PermissionDialog
|
|
||||||
type permissionDialogComponent struct {
|
|
||||||
width int
|
|
||||||
height int
|
|
||||||
// permission permission.PermissionRequest
|
|
||||||
windowSize tea.WindowSizeMsg
|
|
||||||
contentViewPort viewport.Model
|
|
||||||
selectedOption int // 0: Allow, 1: Allow for session, 2: Deny
|
|
||||||
|
|
||||||
diffCache map[string]string
|
|
||||||
markdownCache map[string]string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) Init() tea.Cmd {
|
|
||||||
return p.contentViewPort.Init()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|
||||||
var cmds []tea.Cmd
|
|
||||||
|
|
||||||
switch msg := msg.(type) {
|
|
||||||
case tea.WindowSizeMsg:
|
|
||||||
p.windowSize = msg
|
|
||||||
cmd := p.SetSize()
|
|
||||||
cmds = append(cmds, cmd)
|
|
||||||
p.markdownCache = make(map[string]string)
|
|
||||||
p.diffCache = make(map[string]string)
|
|
||||||
// case tea.KeyMsg:
|
|
||||||
// switch {
|
|
||||||
// case key.Matches(msg, permissionsKeys.Right) || key.Matches(msg, permissionsKeys.Tab):
|
|
||||||
// p.selectedOption = (p.selectedOption + 1) % 3
|
|
||||||
// return p, nil
|
|
||||||
// case key.Matches(msg, permissionsKeys.Left):
|
|
||||||
// p.selectedOption = (p.selectedOption + 2) % 3
|
|
||||||
// case key.Matches(msg, permissionsKeys.EnterSpace):
|
|
||||||
// return p, p.selectCurrentOption()
|
|
||||||
// case key.Matches(msg, permissionsKeys.Allow):
|
|
||||||
// return p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllow, Permission: p.permission})
|
|
||||||
// case key.Matches(msg, permissionsKeys.AllowSession):
|
|
||||||
// return p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllowForSession, Permission: p.permission})
|
|
||||||
// case key.Matches(msg, permissionsKeys.Deny):
|
|
||||||
// return p, util.CmdHandler(PermissionResponseMsg{Action: PermissionDeny, Permission: p.permission})
|
|
||||||
// default:
|
|
||||||
// // Pass other keys to viewport
|
|
||||||
// viewPort, cmd := p.contentViewPort.Update(msg)
|
|
||||||
// p.contentViewPort = viewPort
|
|
||||||
// cmds = append(cmds, cmd)
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
|
|
||||||
return p, tea.Batch(cmds...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) selectCurrentOption() tea.Cmd {
|
|
||||||
var action PermissionAction
|
|
||||||
|
|
||||||
switch p.selectedOption {
|
|
||||||
case 0:
|
|
||||||
action = PermissionAllow
|
|
||||||
case 1:
|
|
||||||
action = PermissionAllowForSession
|
|
||||||
case 2:
|
|
||||||
action = PermissionDeny
|
|
||||||
}
|
|
||||||
|
|
||||||
return util.CmdHandler(PermissionResponseMsg{Action: action}) // , Permission: p.permission})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) renderButtons() string {
|
|
||||||
t := theme.CurrentTheme()
|
|
||||||
baseStyle := styles.NewStyle().Foreground(t.Text())
|
|
||||||
|
|
||||||
allowStyle := baseStyle
|
|
||||||
allowSessionStyle := baseStyle
|
|
||||||
denyStyle := baseStyle
|
|
||||||
spacerStyle := baseStyle.Background(t.Background())
|
|
||||||
|
|
||||||
// Style the selected button
|
|
||||||
switch p.selectedOption {
|
|
||||||
case 0:
|
|
||||||
allowStyle = allowStyle.Background(t.Primary()).Foreground(t.Background())
|
|
||||||
allowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())
|
|
||||||
denyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())
|
|
||||||
case 1:
|
|
||||||
allowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())
|
|
||||||
allowSessionStyle = allowSessionStyle.Background(t.Primary()).Foreground(t.Background())
|
|
||||||
denyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())
|
|
||||||
case 2:
|
|
||||||
allowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())
|
|
||||||
allowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())
|
|
||||||
denyStyle = denyStyle.Background(t.Primary()).Foreground(t.Background())
|
|
||||||
}
|
|
||||||
|
|
||||||
allowButton := allowStyle.Padding(0, 1).Render("Allow (a)")
|
|
||||||
allowSessionButton := allowSessionStyle.Padding(0, 1).Render("Allow for session (s)")
|
|
||||||
denyButton := denyStyle.Padding(0, 1).Render("Deny (d)")
|
|
||||||
|
|
||||||
content := lipgloss.JoinHorizontal(
|
|
||||||
lipgloss.Left,
|
|
||||||
allowButton,
|
|
||||||
spacerStyle.Render(" "),
|
|
||||||
allowSessionButton,
|
|
||||||
spacerStyle.Render(" "),
|
|
||||||
denyButton,
|
|
||||||
spacerStyle.Render(" "),
|
|
||||||
)
|
|
||||||
|
|
||||||
remainingWidth := p.width - lipgloss.Width(content)
|
|
||||||
if remainingWidth > 0 {
|
|
||||||
content = spacerStyle.Render(strings.Repeat(" ", remainingWidth)) + content
|
|
||||||
}
|
|
||||||
return content
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) renderHeader() string {
|
|
||||||
return "NOT IMPLEMENTED"
|
|
||||||
// t := theme.CurrentTheme()
|
|
||||||
// baseStyle := styles.BaseStyle()
|
|
||||||
//
|
|
||||||
// toolKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render("Tool")
|
|
||||||
// toolValue := baseStyle.
|
|
||||||
// Foreground(t.Text()).
|
|
||||||
// Width(p.width - lipgloss.Width(toolKey)).
|
|
||||||
// Render(fmt.Sprintf(": %s", p.permission.ToolName))
|
|
||||||
//
|
|
||||||
// pathKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render("Path")
|
|
||||||
//
|
|
||||||
// // Get the current working directory to display relative path
|
|
||||||
// relativePath := p.permission.Path
|
|
||||||
// if filepath.IsAbs(relativePath) {
|
|
||||||
// if cwd, err := filepath.Rel(config.WorkingDirectory(), relativePath); err == nil {
|
|
||||||
// relativePath = cwd
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// pathValue := baseStyle.
|
|
||||||
// Foreground(t.Text()).
|
|
||||||
// Width(p.width - lipgloss.Width(pathKey)).
|
|
||||||
// Render(fmt.Sprintf(": %s", relativePath))
|
|
||||||
//
|
|
||||||
// headerParts := []string{
|
|
||||||
// lipgloss.JoinHorizontal(
|
|
||||||
// lipgloss.Left,
|
|
||||||
// toolKey,
|
|
||||||
// toolValue,
|
|
||||||
// ),
|
|
||||||
// baseStyle.Render(strings.Repeat(" ", p.width)),
|
|
||||||
// lipgloss.JoinHorizontal(
|
|
||||||
// lipgloss.Left,
|
|
||||||
// pathKey,
|
|
||||||
// pathValue,
|
|
||||||
// ),
|
|
||||||
// baseStyle.Render(strings.Repeat(" ", p.width)),
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// // Add tool-specific header information
|
|
||||||
// switch p.permission.ToolName {
|
|
||||||
// case "bash":
|
|
||||||
// headerParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render("Command"))
|
|
||||||
// case "edit":
|
|
||||||
// headerParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render("Diff"))
|
|
||||||
// case "write":
|
|
||||||
// headerParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render("Diff"))
|
|
||||||
// case "fetch":
|
|
||||||
// headerParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render("URL"))
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// return lipgloss.NewStyle().Background(t.Background()).Render(lipgloss.JoinVertical(lipgloss.Left, headerParts...))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) renderBashContent() string {
|
|
||||||
// t := theme.CurrentTheme()
|
|
||||||
// baseStyle := styles.BaseStyle()
|
|
||||||
//
|
|
||||||
// if pr, ok := p.permission.Params.(tools.BashPermissionsParams); ok {
|
|
||||||
// content := fmt.Sprintf("```bash\n%s\n```", pr.Command)
|
|
||||||
//
|
|
||||||
// // Use the cache for markdown rendering
|
|
||||||
// renderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {
|
|
||||||
// r := styles.GetMarkdownRenderer(p.width - 10)
|
|
||||||
// s, err := r.Render(content)
|
|
||||||
// return s
|
|
||||||
// })
|
|
||||||
//
|
|
||||||
// finalContent := baseStyle.
|
|
||||||
// Width(p.contentViewPort.Width).
|
|
||||||
// Render(renderedContent)
|
|
||||||
// p.contentViewPort.SetContent(finalContent)
|
|
||||||
// return p.styleViewport()
|
|
||||||
// }
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) renderEditContent() string {
|
|
||||||
// if pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {
|
|
||||||
// diff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {
|
|
||||||
// return diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))
|
|
||||||
// })
|
|
||||||
//
|
|
||||||
// p.contentViewPort.SetContent(diff)
|
|
||||||
// return p.styleViewport()
|
|
||||||
// }
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) renderPatchContent() string {
|
|
||||||
// if pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {
|
|
||||||
// diff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {
|
|
||||||
// return diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))
|
|
||||||
// })
|
|
||||||
//
|
|
||||||
// p.contentViewPort.SetContent(diff)
|
|
||||||
// return p.styleViewport()
|
|
||||||
// }
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) renderWriteContent() string {
|
|
||||||
// if pr, ok := p.permission.Params.(tools.WritePermissionsParams); ok {
|
|
||||||
// // Use the cache for diff rendering
|
|
||||||
// diff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {
|
|
||||||
// return diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))
|
|
||||||
// })
|
|
||||||
//
|
|
||||||
// p.contentViewPort.SetContent(diff)
|
|
||||||
// return p.styleViewport()
|
|
||||||
// }
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) renderFetchContent() string {
|
|
||||||
// t := theme.CurrentTheme()
|
|
||||||
// baseStyle := styles.BaseStyle()
|
|
||||||
//
|
|
||||||
// if pr, ok := p.permission.Params.(tools.FetchPermissionsParams); ok {
|
|
||||||
// content := fmt.Sprintf("```bash\n%s\n```", pr.URL)
|
|
||||||
//
|
|
||||||
// // Use the cache for markdown rendering
|
|
||||||
// renderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {
|
|
||||||
// r := styles.GetMarkdownRenderer(p.width - 10)
|
|
||||||
// s, err := r.Render(content)
|
|
||||||
// return s
|
|
||||||
// })
|
|
||||||
//
|
|
||||||
// finalContent := baseStyle.
|
|
||||||
// Width(p.contentViewPort.Width).
|
|
||||||
// Render(renderedContent)
|
|
||||||
// p.contentViewPort.SetContent(finalContent)
|
|
||||||
// return p.styleViewport()
|
|
||||||
// }
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) renderDefaultContent() string {
|
|
||||||
// t := theme.CurrentTheme()
|
|
||||||
// baseStyle := styles.BaseStyle()
|
|
||||||
//
|
|
||||||
// content := p.permission.Description
|
|
||||||
//
|
|
||||||
// // Use the cache for markdown rendering
|
|
||||||
// renderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {
|
|
||||||
// r := styles.GetMarkdownRenderer(p.width - 10)
|
|
||||||
// s, err := r.Render(content)
|
|
||||||
// return s
|
|
||||||
// })
|
|
||||||
//
|
|
||||||
// finalContent := baseStyle.
|
|
||||||
// Width(p.contentViewPort.Width).
|
|
||||||
// Render(renderedContent)
|
|
||||||
// p.contentViewPort.SetContent(finalContent)
|
|
||||||
//
|
|
||||||
// if renderedContent == "" {
|
|
||||||
// return ""
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
return p.styleViewport()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) styleViewport() string {
|
|
||||||
t := theme.CurrentTheme()
|
|
||||||
contentStyle := styles.NewStyle().Background(t.Background())
|
|
||||||
|
|
||||||
return contentStyle.Render(p.contentViewPort.View())
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) render() string {
|
|
||||||
return "NOT IMPLEMENTED"
|
|
||||||
// t := theme.CurrentTheme()
|
|
||||||
// baseStyle := styles.BaseStyle()
|
|
||||||
//
|
|
||||||
// title := baseStyle.
|
|
||||||
// Bold(true).
|
|
||||||
// Width(p.width - 4).
|
|
||||||
// Foreground(t.Primary()).
|
|
||||||
// Render("Permission Required")
|
|
||||||
// // Render header
|
|
||||||
// headerContent := p.renderHeader()
|
|
||||||
// // Render buttons
|
|
||||||
// buttons := p.renderButtons()
|
|
||||||
//
|
|
||||||
// // Calculate content height dynamically based on window size
|
|
||||||
// p.contentViewPort.Height = p.height - lipgloss.Height(headerContent) - lipgloss.Height(buttons) - 2 - lipgloss.Height(title)
|
|
||||||
// p.contentViewPort.Width = p.width - 4
|
|
||||||
//
|
|
||||||
// // Render content based on tool type
|
|
||||||
// var contentFinal string
|
|
||||||
// switch p.permission.ToolName {
|
|
||||||
// case "bash":
|
|
||||||
// contentFinal = p.renderBashContent()
|
|
||||||
// case "edit":
|
|
||||||
// contentFinal = p.renderEditContent()
|
|
||||||
// case "patch":
|
|
||||||
// contentFinal = p.renderPatchContent()
|
|
||||||
// case "write":
|
|
||||||
// contentFinal = p.renderWriteContent()
|
|
||||||
// case "fetch":
|
|
||||||
// contentFinal = p.renderFetchContent()
|
|
||||||
// default:
|
|
||||||
// contentFinal = p.renderDefaultContent()
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// content := lipgloss.JoinVertical(
|
|
||||||
// lipgloss.Top,
|
|
||||||
// title,
|
|
||||||
// baseStyle.Render(strings.Repeat(" ", lipgloss.Width(title))),
|
|
||||||
// headerContent,
|
|
||||||
// contentFinal,
|
|
||||||
// buttons,
|
|
||||||
// baseStyle.Render(strings.Repeat(" ", p.width-4)),
|
|
||||||
// )
|
|
||||||
//
|
|
||||||
// return baseStyle.
|
|
||||||
// Padding(1, 0, 0, 1).
|
|
||||||
// Border(lipgloss.RoundedBorder()).
|
|
||||||
// BorderBackground(t.Background()).
|
|
||||||
// BorderForeground(t.TextMuted()).
|
|
||||||
// Width(p.width).
|
|
||||||
// Height(p.height).
|
|
||||||
// Render(
|
|
||||||
// content,
|
|
||||||
// )
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) View() string {
|
|
||||||
return p.render()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *permissionDialogComponent) SetSize() tea.Cmd {
|
|
||||||
// if p.permission.ID == "" {
|
|
||||||
// return nil
|
|
||||||
// }
|
|
||||||
// switch p.permission.ToolName {
|
|
||||||
// case "bash":
|
|
||||||
// p.width = int(float64(p.windowSize.Width) * 0.4)
|
|
||||||
// p.height = int(float64(p.windowSize.Height) * 0.3)
|
|
||||||
// case "edit":
|
|
||||||
// p.width = int(float64(p.windowSize.Width) * 0.8)
|
|
||||||
// p.height = int(float64(p.windowSize.Height) * 0.8)
|
|
||||||
// case "write":
|
|
||||||
// p.width = int(float64(p.windowSize.Width) * 0.8)
|
|
||||||
// p.height = int(float64(p.windowSize.Height) * 0.8)
|
|
||||||
// case "fetch":
|
|
||||||
// p.width = int(float64(p.windowSize.Width) * 0.4)
|
|
||||||
// p.height = int(float64(p.windowSize.Height) * 0.3)
|
|
||||||
// default:
|
|
||||||
// p.width = int(float64(p.windowSize.Width) * 0.7)
|
|
||||||
// p.height = int(float64(p.windowSize.Height) * 0.5)
|
|
||||||
// }
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// func (p *permissionDialogCmp) SetPermissions(permission permission.PermissionRequest) tea.Cmd {
|
|
||||||
// p.permission = permission
|
|
||||||
// return p.SetSize()
|
|
||||||
// }
|
|
||||||
|
|
||||||
// Helper to get or set cached diff content
|
|
||||||
func (c *permissionDialogComponent) GetOrSetDiff(key string, generator func() (string, error)) string {
|
|
||||||
if cached, ok := c.diffCache[key]; ok {
|
|
||||||
return cached
|
|
||||||
}
|
|
||||||
|
|
||||||
content, err := generator()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Sprintf("Error formatting diff: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
c.diffCache[key] = content
|
|
||||||
|
|
||||||
return content
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper to get or set cached markdown content
|
|
||||||
func (c *permissionDialogComponent) GetOrSetMarkdown(key string, generator func() (string, error)) string {
|
|
||||||
if cached, ok := c.markdownCache[key]; ok {
|
|
||||||
return cached
|
|
||||||
}
|
|
||||||
|
|
||||||
content, err := generator()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Sprintf("Error rendering markdown: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
c.markdownCache[key] = content
|
|
||||||
|
|
||||||
return content
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPermissionDialogCmp() PermissionDialogComponent {
|
|
||||||
// Create viewport for content
|
|
||||||
contentViewport := viewport.New() // (0, 0)
|
|
||||||
|
|
||||||
return &permissionDialogComponent{
|
|
||||||
contentViewPort: contentViewport,
|
|
||||||
selectedOption: 0, // Default to "Allow"
|
|
||||||
diffCache: make(map[string]string),
|
|
||||||
markdownCache: make(map[string]string),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -17,17 +17,23 @@ type SearchQueryChangedMsg struct {
|
|||||||
|
|
||||||
// SearchSelectionMsg is emitted when an item is selected
|
// SearchSelectionMsg is emitted when an item is selected
|
||||||
type SearchSelectionMsg struct {
|
type SearchSelectionMsg struct {
|
||||||
Item interface{}
|
Item any
|
||||||
Index int
|
Index int
|
||||||
}
|
}
|
||||||
|
|
||||||
// SearchCancelledMsg is emitted when the search is cancelled
|
// SearchCancelledMsg is emitted when the search is cancelled
|
||||||
type SearchCancelledMsg struct{}
|
type SearchCancelledMsg struct{}
|
||||||
|
|
||||||
|
// SearchRemoveItemMsg is emitted when Ctrl+X is pressed to remove an item
|
||||||
|
type SearchRemoveItemMsg struct {
|
||||||
|
Item any
|
||||||
|
Index int
|
||||||
|
}
|
||||||
|
|
||||||
// SearchDialog is a reusable component that combines a text input with a list
|
// SearchDialog is a reusable component that combines a text input with a list
|
||||||
type SearchDialog struct {
|
type SearchDialog struct {
|
||||||
textInput textinput.Model
|
textInput textinput.Model
|
||||||
list list.List[list.ListItem]
|
list list.List[list.Item]
|
||||||
width int
|
width int
|
||||||
height int
|
height int
|
||||||
focused bool
|
focused bool
|
||||||
@@ -38,6 +44,7 @@ type searchKeyMap struct {
|
|||||||
Down key.Binding
|
Down key.Binding
|
||||||
Enter key.Binding
|
Enter key.Binding
|
||||||
Escape key.Binding
|
Escape key.Binding
|
||||||
|
Remove key.Binding
|
||||||
}
|
}
|
||||||
|
|
||||||
var searchKeys = searchKeyMap{
|
var searchKeys = searchKeyMap{
|
||||||
@@ -57,10 +64,14 @@ var searchKeys = searchKeyMap{
|
|||||||
key.WithKeys("esc"),
|
key.WithKeys("esc"),
|
||||||
key.WithHelp("esc", "cancel"),
|
key.WithHelp("esc", "cancel"),
|
||||||
),
|
),
|
||||||
|
Remove: key.NewBinding(
|
||||||
|
key.WithKeys("ctrl+x"),
|
||||||
|
key.WithHelp("ctrl+x", "remove from recent"),
|
||||||
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewSearchDialog creates a new SearchDialog
|
// NewSearchDialog creates a new SearchDialog
|
||||||
func NewSearchDialog(placeholder string, maxVisibleItems int) *SearchDialog {
|
func NewSearchDialog(placeholder string, maxVisibleHeight int) *SearchDialog {
|
||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
bgColor := t.BackgroundElement()
|
bgColor := t.BackgroundElement()
|
||||||
textColor := t.Text()
|
textColor := t.Text()
|
||||||
@@ -95,10 +106,18 @@ func NewSearchDialog(placeholder string, maxVisibleItems int) *SearchDialog {
|
|||||||
ti.Focus()
|
ti.Focus()
|
||||||
|
|
||||||
emptyList := list.NewListComponent(
|
emptyList := list.NewListComponent(
|
||||||
[]list.ListItem{},
|
list.WithItems([]list.Item{}),
|
||||||
maxVisibleItems,
|
list.WithMaxVisibleHeight[list.Item](maxVisibleHeight),
|
||||||
" No items",
|
list.WithFallbackMessage[list.Item](" No items"),
|
||||||
false,
|
list.WithAlphaNumericKeys[list.Item](false),
|
||||||
|
list.WithRenderFunc(
|
||||||
|
func(item list.Item, selected bool, width int, baseStyle styles.Style) string {
|
||||||
|
return item.Render(selected, width, baseStyle)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
list.WithSelectableFunc(func(item list.Item) bool {
|
||||||
|
return item.Selectable()
|
||||||
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
return &SearchDialog{
|
return &SearchDialog{
|
||||||
@@ -134,16 +153,23 @@ func (s *SearchDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
return s, func() tea.Msg { return SearchCancelledMsg{} }
|
return s, func() tea.Msg { return SearchCancelledMsg{} }
|
||||||
|
|
||||||
case key.Matches(msg, searchKeys.Enter):
|
case key.Matches(msg, searchKeys.Enter):
|
||||||
if selectedItem, idx := s.list.GetSelectedItem(); selectedItem != nil {
|
if selectedItem, idx := s.list.GetSelectedItem(); idx != -1 {
|
||||||
return s, func() tea.Msg {
|
return s, func() tea.Msg {
|
||||||
return SearchSelectionMsg{Item: selectedItem, Index: idx}
|
return SearchSelectionMsg{Item: selectedItem, Index: idx}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case key.Matches(msg, searchKeys.Remove):
|
||||||
|
if selectedItem, idx := s.list.GetSelectedItem(); idx != -1 {
|
||||||
|
return s, func() tea.Msg {
|
||||||
|
return SearchRemoveItemMsg{Item: selectedItem, Index: idx}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
case key.Matches(msg, searchKeys.Up):
|
case key.Matches(msg, searchKeys.Up):
|
||||||
var cmd tea.Cmd
|
var cmd tea.Cmd
|
||||||
listModel, cmd := s.list.Update(msg)
|
listModel, cmd := s.list.Update(msg)
|
||||||
s.list = listModel.(list.List[list.ListItem])
|
s.list = listModel.(list.List[list.Item])
|
||||||
if cmd != nil {
|
if cmd != nil {
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
}
|
}
|
||||||
@@ -151,7 +177,7 @@ func (s *SearchDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
case key.Matches(msg, searchKeys.Down):
|
case key.Matches(msg, searchKeys.Down):
|
||||||
var cmd tea.Cmd
|
var cmd tea.Cmd
|
||||||
listModel, cmd := s.list.Update(msg)
|
listModel, cmd := s.list.Update(msg)
|
||||||
s.list = listModel.(list.List[list.ListItem])
|
s.list = listModel.(list.List[list.Item])
|
||||||
if cmd != nil {
|
if cmd != nil {
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
}
|
}
|
||||||
@@ -177,7 +203,7 @@ func (s *SearchDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
func (s *SearchDialog) View() string {
|
func (s *SearchDialog) View() string {
|
||||||
s.list.SetMaxWidth(s.width)
|
s.list.SetMaxWidth(s.width)
|
||||||
listView := s.list.View()
|
listView := s.list.View()
|
||||||
listView = lipgloss.PlaceVertical(s.list.GetMaxVisibleItems(), lipgloss.Top, listView)
|
listView = lipgloss.PlaceVertical(s.list.GetMaxVisibleHeight(), lipgloss.Top, listView)
|
||||||
textinput := s.textInput.View()
|
textinput := s.textInput.View()
|
||||||
return textinput + "\n\n" + listView
|
return textinput + "\n\n" + listView
|
||||||
}
|
}
|
||||||
@@ -194,7 +220,7 @@ func (s *SearchDialog) SetHeight(height int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SetItems updates the list items
|
// SetItems updates the list items
|
||||||
func (s *SearchDialog) SetItems(items []list.ListItem) {
|
func (s *SearchDialog) SetItems(items []list.Item) {
|
||||||
s.list.SetItems(items)
|
s.list.SetItems(items)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,17 +28,26 @@ type SessionDialog interface {
|
|||||||
type sessionItem struct {
|
type sessionItem struct {
|
||||||
title string
|
title string
|
||||||
isDeleteConfirming bool
|
isDeleteConfirming bool
|
||||||
|
isCurrentSession bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s sessionItem) Render(selected bool, width int, isFirstInViewport bool) string {
|
func (s sessionItem) Render(
|
||||||
|
selected bool,
|
||||||
|
width int,
|
||||||
|
isFirstInViewport bool,
|
||||||
|
baseStyle styles.Style,
|
||||||
|
) string {
|
||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
baseStyle := styles.NewStyle()
|
|
||||||
|
|
||||||
var text string
|
var text string
|
||||||
if s.isDeleteConfirming {
|
if s.isDeleteConfirming {
|
||||||
text = "Press again to confirm delete"
|
text = "Press again to confirm delete"
|
||||||
} else {
|
} else {
|
||||||
text = s.title
|
if s.isCurrentSession {
|
||||||
|
text = "● " + s.title
|
||||||
|
} else {
|
||||||
|
text = s.title
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
truncatedStr := truncate.StringWithTail(text, uint(width-1), "...")
|
truncatedStr := truncate.StringWithTail(text, uint(width-1), "...")
|
||||||
@@ -52,6 +61,14 @@ func (s sessionItem) Render(selected bool, width int, isFirstInViewport bool) st
|
|||||||
Foreground(t.BackgroundElement()).
|
Foreground(t.BackgroundElement()).
|
||||||
Width(width).
|
Width(width).
|
||||||
PaddingLeft(1)
|
PaddingLeft(1)
|
||||||
|
} else if s.isCurrentSession {
|
||||||
|
// Different style for current session when selected
|
||||||
|
itemStyle = baseStyle.
|
||||||
|
Background(t.Primary()).
|
||||||
|
Foreground(t.BackgroundElement()).
|
||||||
|
Width(width).
|
||||||
|
PaddingLeft(1).
|
||||||
|
Bold(true)
|
||||||
} else {
|
} else {
|
||||||
// Normal selection
|
// Normal selection
|
||||||
itemStyle = baseStyle.
|
itemStyle = baseStyle.
|
||||||
@@ -66,6 +83,12 @@ func (s sessionItem) Render(selected bool, width int, isFirstInViewport bool) st
|
|||||||
itemStyle = baseStyle.
|
itemStyle = baseStyle.
|
||||||
Foreground(t.Error()).
|
Foreground(t.Error()).
|
||||||
PaddingLeft(1)
|
PaddingLeft(1)
|
||||||
|
} else if s.isCurrentSession {
|
||||||
|
// Highlight current session when not selected
|
||||||
|
itemStyle = baseStyle.
|
||||||
|
Foreground(t.Primary()).
|
||||||
|
PaddingLeft(1).
|
||||||
|
Bold(true)
|
||||||
} else {
|
} else {
|
||||||
itemStyle = baseStyle.
|
itemStyle = baseStyle.
|
||||||
PaddingLeft(1)
|
PaddingLeft(1)
|
||||||
@@ -190,6 +213,7 @@ func (s *sessionDialog) updateListItems() {
|
|||||||
item := sessionItem{
|
item := sessionItem{
|
||||||
title: sess.Title,
|
title: sess.Title,
|
||||||
isDeleteConfirming: s.deleteConfirmation == i,
|
isDeleteConfirming: s.deleteConfirmation == i,
|
||||||
|
isCurrentSession: s.app.Session != nil && s.app.Session.ID == sess.ID,
|
||||||
}
|
}
|
||||||
items = append(items, item)
|
items = append(items, item)
|
||||||
}
|
}
|
||||||
@@ -225,15 +249,23 @@ func NewSessionDialog(app *app.App) SessionDialog {
|
|||||||
items = append(items, sessionItem{
|
items = append(items, sessionItem{
|
||||||
title: sess.Title,
|
title: sess.Title,
|
||||||
isDeleteConfirming: false,
|
isDeleteConfirming: false,
|
||||||
|
isCurrentSession: app.Session != nil && app.Session.ID == sess.ID,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a generic list component
|
|
||||||
listComponent := list.NewListComponent(
|
listComponent := list.NewListComponent(
|
||||||
items,
|
list.WithItems(items),
|
||||||
10, // maxVisibleSessions
|
list.WithMaxVisibleHeight[sessionItem](10),
|
||||||
"No sessions available",
|
list.WithFallbackMessage[sessionItem]("No sessions available"),
|
||||||
true, // useAlphaNumericKeys
|
list.WithAlphaNumericKeys[sessionItem](true),
|
||||||
|
list.WithRenderFunc(
|
||||||
|
func(item sessionItem, selected bool, width int, baseStyle styles.Style) string {
|
||||||
|
return item.Render(selected, width, false, baseStyle)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
list.WithSelectableFunc(func(item sessionItem) bool {
|
||||||
|
return true
|
||||||
|
}),
|
||||||
)
|
)
|
||||||
listComponent.SetMaxWidth(layout.Current.Container.Width - 12)
|
listComponent.SetMaxWidth(layout.Current.Container.Width - 12)
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
list "github.com/sst/opencode/internal/components/list"
|
list "github.com/sst/opencode/internal/components/list"
|
||||||
"github.com/sst/opencode/internal/components/modal"
|
"github.com/sst/opencode/internal/components/modal"
|
||||||
"github.com/sst/opencode/internal/layout"
|
"github.com/sst/opencode/internal/layout"
|
||||||
|
"github.com/sst/opencode/internal/styles"
|
||||||
"github.com/sst/opencode/internal/theme"
|
"github.com/sst/opencode/internal/theme"
|
||||||
"github.com/sst/opencode/internal/util"
|
"github.com/sst/opencode/internal/util"
|
||||||
)
|
)
|
||||||
@@ -24,7 +25,7 @@ type themeDialog struct {
|
|||||||
height int
|
height int
|
||||||
|
|
||||||
modal *modal.Modal
|
modal *modal.Modal
|
||||||
list list.List[list.StringItem]
|
list list.List[list.Item]
|
||||||
originalTheme string
|
originalTheme string
|
||||||
themeApplied bool
|
themeApplied bool
|
||||||
}
|
}
|
||||||
@@ -42,16 +43,18 @@ func (t *themeDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
switch msg.String() {
|
switch msg.String() {
|
||||||
case "enter":
|
case "enter":
|
||||||
if item, idx := t.list.GetSelectedItem(); idx >= 0 {
|
if item, idx := t.list.GetSelectedItem(); idx >= 0 {
|
||||||
selectedTheme := string(item)
|
if stringItem, ok := item.(list.StringItem); ok {
|
||||||
if err := theme.SetTheme(selectedTheme); err != nil {
|
selectedTheme := string(stringItem)
|
||||||
// status.Error(err.Error())
|
if err := theme.SetTheme(selectedTheme); err != nil {
|
||||||
return t, nil
|
// status.Error(err.Error())
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
t.themeApplied = true
|
||||||
|
return t, tea.Sequence(
|
||||||
|
util.CmdHandler(modal.CloseModalMsg{}),
|
||||||
|
util.CmdHandler(ThemeSelectedMsg{ThemeName: selectedTheme}),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
t.themeApplied = true
|
|
||||||
return t, tea.Sequence(
|
|
||||||
util.CmdHandler(modal.CloseModalMsg{}),
|
|
||||||
util.CmdHandler(ThemeSelectedMsg{ThemeName: selectedTheme}),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -61,11 +64,13 @@ func (t *themeDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
|
|
||||||
var cmd tea.Cmd
|
var cmd tea.Cmd
|
||||||
listModel, cmd := t.list.Update(msg)
|
listModel, cmd := t.list.Update(msg)
|
||||||
t.list = listModel.(list.List[list.StringItem])
|
t.list = listModel.(list.List[list.Item])
|
||||||
|
|
||||||
if item, newIdx := t.list.GetSelectedItem(); newIdx >= 0 && newIdx != prevIdx {
|
if item, newIdx := t.list.GetSelectedItem(); newIdx >= 0 && newIdx != prevIdx {
|
||||||
theme.SetTheme(string(item))
|
if stringItem, ok := item.(list.StringItem); ok {
|
||||||
return t, util.CmdHandler(ThemeSelectedMsg{ThemeName: string(item)})
|
theme.SetTheme(string(stringItem))
|
||||||
|
return t, util.CmdHandler(ThemeSelectedMsg{ThemeName: string(stringItem)})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return t, cmd
|
return t, cmd
|
||||||
}
|
}
|
||||||
@@ -94,21 +99,32 @@ func NewThemeDialog() ThemeDialog {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
list := list.NewStringList(
|
// Convert themes to list items
|
||||||
themes,
|
items := make([]list.Item, len(themes))
|
||||||
10, // maxVisibleThemes
|
for i, theme := range themes {
|
||||||
"No themes available",
|
items[i] = list.StringItem(theme)
|
||||||
true,
|
}
|
||||||
|
|
||||||
|
listComponent := list.NewListComponent(
|
||||||
|
list.WithItems(items),
|
||||||
|
list.WithMaxVisibleHeight[list.Item](10),
|
||||||
|
list.WithFallbackMessage[list.Item]("No themes available"),
|
||||||
|
list.WithAlphaNumericKeys[list.Item](true),
|
||||||
|
list.WithRenderFunc(func(item list.Item, selected bool, width int, baseStyle styles.Style) string {
|
||||||
|
return item.Render(selected, width, baseStyle)
|
||||||
|
}),
|
||||||
|
list.WithSelectableFunc(func(item list.Item) bool {
|
||||||
|
return item.Selectable()
|
||||||
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
// Set the initial selection to the current theme
|
// Set the initial selection to the current theme
|
||||||
list.SetSelectedIndex(selectedIdx)
|
listComponent.SetSelectedIndex(selectedIdx)
|
||||||
|
|
||||||
// Set the max width for the list to match the modal width
|
// Set the max width for the list to match the modal width
|
||||||
list.SetMaxWidth(36) // 40 (modal max width) - 4 (modal padding)
|
listComponent.SetMaxWidth(36) // 40 (modal max width) - 4 (modal padding)
|
||||||
|
|
||||||
return &themeDialog{
|
return &themeDialog{
|
||||||
list: list,
|
list: listComponent,
|
||||||
modal: modal.New(modal.WithTitle("Select Theme"), modal.WithMaxWidth(40)),
|
modal: modal.New(modal.WithTitle("Select Theme"), modal.WithMaxWidth(40)),
|
||||||
originalTheme: currentTheme,
|
originalTheme: currentTheme,
|
||||||
themeApplied: false,
|
themeApplied: false,
|
||||||
|
|||||||
@@ -38,6 +38,10 @@ const (
|
|||||||
LineRemoved // Line removed from the old file
|
LineRemoved // Line removed from the old file
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ansiRegex = regexp.MustCompile(`\x1b(?:[@-Z\\-_]|\[[0-9?]*(?:;[0-9?]*)*[@-~])`)
|
||||||
|
)
|
||||||
|
|
||||||
// Segment represents a portion of a line for intra-line highlighting
|
// Segment represents a portion of a line for intra-line highlighting
|
||||||
type Segment struct {
|
type Segment struct {
|
||||||
Start int
|
Start int
|
||||||
@@ -548,7 +552,6 @@ func createStyles(t theme.Theme) (removedLineStyle, addedLineStyle, contextLineS
|
|||||||
// applyHighlighting applies intra-line highlighting to a piece of text
|
// applyHighlighting applies intra-line highlighting to a piece of text
|
||||||
func applyHighlighting(content string, segments []Segment, segmentType LineType, highlightBg compat.AdaptiveColor) string {
|
func applyHighlighting(content string, segments []Segment, segmentType LineType, highlightBg compat.AdaptiveColor) string {
|
||||||
// Find all ANSI sequences in the content
|
// Find all ANSI sequences in the content
|
||||||
ansiRegex := regexp.MustCompile(`\x1b(?:[@-Z\\-_]|\[[0-9?]*(?:;[0-9?]*)*[@-~])`)
|
|
||||||
ansiMatches := ansiRegex.FindAllStringIndex(content, -1)
|
ansiMatches := ansiRegex.FindAllStringIndex(content, -1)
|
||||||
|
|
||||||
// Build a mapping of visible character positions to their actual indices
|
// Build a mapping of visible character positions to their actual indices
|
||||||
|
|||||||
@@ -5,17 +5,88 @@ import (
|
|||||||
|
|
||||||
"github.com/charmbracelet/bubbles/v2/key"
|
"github.com/charmbracelet/bubbles/v2/key"
|
||||||
tea "github.com/charmbracelet/bubbletea/v2"
|
tea "github.com/charmbracelet/bubbletea/v2"
|
||||||
|
"github.com/charmbracelet/lipgloss/v2"
|
||||||
"github.com/muesli/reflow/truncate"
|
"github.com/muesli/reflow/truncate"
|
||||||
"github.com/sst/opencode/internal/styles"
|
"github.com/sst/opencode/internal/styles"
|
||||||
"github.com/sst/opencode/internal/theme"
|
"github.com/sst/opencode/internal/theme"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ListItem interface {
|
// Item interface that all list items must implement
|
||||||
Render(selected bool, width int, isFirstInViewport bool) string
|
type Item interface {
|
||||||
|
Render(selected bool, width int, baseStyle styles.Style) string
|
||||||
Selectable() bool
|
Selectable() bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type List[T ListItem] interface {
|
// RenderFunc defines how to render an item in the list
|
||||||
|
type RenderFunc[T any] func(item T, selected bool, width int, baseStyle styles.Style) string
|
||||||
|
|
||||||
|
// SelectableFunc defines whether an item is selectable
|
||||||
|
type SelectableFunc[T any] func(item T) bool
|
||||||
|
|
||||||
|
// Options holds configuration for the list component
|
||||||
|
type Options[T any] struct {
|
||||||
|
items []T
|
||||||
|
maxVisibleHeight int
|
||||||
|
fallbackMsg string
|
||||||
|
useAlphaNumericKeys bool
|
||||||
|
renderItem RenderFunc[T]
|
||||||
|
isSelectable SelectableFunc[T]
|
||||||
|
baseStyle styles.Style
|
||||||
|
}
|
||||||
|
|
||||||
|
// Option is a function that configures the list component
|
||||||
|
type Option[T any] func(*Options[T])
|
||||||
|
|
||||||
|
// WithItems sets the initial items for the list
|
||||||
|
func WithItems[T any](items []T) Option[T] {
|
||||||
|
return func(o *Options[T]) {
|
||||||
|
o.items = items
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithMaxVisibleHeight sets the maximum visible height in lines
|
||||||
|
func WithMaxVisibleHeight[T any](height int) Option[T] {
|
||||||
|
return func(o *Options[T]) {
|
||||||
|
o.maxVisibleHeight = height
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithFallbackMessage sets the message to show when the list is empty
|
||||||
|
func WithFallbackMessage[T any](msg string) Option[T] {
|
||||||
|
return func(o *Options[T]) {
|
||||||
|
o.fallbackMsg = msg
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithAlphaNumericKeys enables j/k navigation keys
|
||||||
|
func WithAlphaNumericKeys[T any](enabled bool) Option[T] {
|
||||||
|
return func(o *Options[T]) {
|
||||||
|
o.useAlphaNumericKeys = enabled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithRenderFunc sets the function to render items
|
||||||
|
func WithRenderFunc[T any](fn RenderFunc[T]) Option[T] {
|
||||||
|
return func(o *Options[T]) {
|
||||||
|
o.renderItem = fn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithSelectableFunc sets the function to determine if items are selectable
|
||||||
|
func WithSelectableFunc[T any](fn SelectableFunc[T]) Option[T] {
|
||||||
|
return func(o *Options[T]) {
|
||||||
|
o.isSelectable = fn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithStyle sets the base style that gets passed to render functions
|
||||||
|
func WithStyle[T any](style styles.Style) Option[T] {
|
||||||
|
return func(o *Options[T]) {
|
||||||
|
o.baseStyle = style
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type List[T any] interface {
|
||||||
tea.Model
|
tea.Model
|
||||||
tea.ViewModel
|
tea.ViewModel
|
||||||
SetMaxWidth(maxWidth int)
|
SetMaxWidth(maxWidth int)
|
||||||
@@ -25,19 +96,21 @@ type List[T ListItem] interface {
|
|||||||
SetSelectedIndex(idx int)
|
SetSelectedIndex(idx int)
|
||||||
SetEmptyMessage(msg string)
|
SetEmptyMessage(msg string)
|
||||||
IsEmpty() bool
|
IsEmpty() bool
|
||||||
GetMaxVisibleItems() int
|
GetMaxVisibleHeight() int
|
||||||
GetActualHeight() int
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type listComponent[T ListItem] struct {
|
type listComponent[T any] struct {
|
||||||
fallbackMsg string
|
fallbackMsg string
|
||||||
items []T
|
items []T
|
||||||
selectedIdx int
|
selectedIdx int
|
||||||
maxWidth int
|
maxWidth int
|
||||||
maxVisibleItems int
|
maxVisibleHeight int
|
||||||
useAlphaNumericKeys bool
|
useAlphaNumericKeys bool
|
||||||
width int
|
width int
|
||||||
height int
|
height int
|
||||||
|
renderItem RenderFunc[T]
|
||||||
|
isSelectable SelectableFunc[T]
|
||||||
|
baseStyle styles.Style
|
||||||
}
|
}
|
||||||
|
|
||||||
type listKeyMap struct {
|
type listKeyMap struct {
|
||||||
@@ -94,7 +167,7 @@ func (c *listComponent[T]) moveUp() {
|
|||||||
|
|
||||||
// Find the previous selectable item
|
// Find the previous selectable item
|
||||||
for i := c.selectedIdx - 1; i >= 0; i-- {
|
for i := c.selectedIdx - 1; i >= 0; i-- {
|
||||||
if c.items[i].Selectable() {
|
if c.isSelectable(c.items[i]) {
|
||||||
c.selectedIdx = i
|
c.selectedIdx = i
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -117,7 +190,7 @@ func (c *listComponent[T]) moveDown() {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.items[c.selectedIdx].Selectable() {
|
if c.isSelectable(c.items[c.selectedIdx]) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,7 +202,7 @@ func (c *listComponent[T]) moveDown() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *listComponent[T]) GetSelectedItem() (T, int) {
|
func (c *listComponent[T]) GetSelectedItem() (T, int) {
|
||||||
if len(c.items) > 0 && c.items[c.selectedIdx].Selectable() {
|
if len(c.items) > 0 && c.isSelectable(c.items[c.selectedIdx]) {
|
||||||
return c.items[c.selectedIdx], c.selectedIdx
|
return c.items[c.selectedIdx], c.selectedIdx
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,7 +215,7 @@ func (c *listComponent[T]) SetItems(items []T) {
|
|||||||
c.selectedIdx = 0
|
c.selectedIdx = 0
|
||||||
|
|
||||||
// Ensure initial selection is on a selectable item
|
// Ensure initial selection is on a selectable item
|
||||||
if len(items) > 0 && !items[0].Selectable() {
|
if len(items) > 0 && !c.isSelectable(items[0]) {
|
||||||
c.moveDown()
|
c.moveDown()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -169,48 +242,8 @@ func (c *listComponent[T]) SetSelectedIndex(idx int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *listComponent[T]) GetMaxVisibleItems() int {
|
func (c *listComponent[T]) GetMaxVisibleHeight() int {
|
||||||
return c.maxVisibleItems
|
return c.maxVisibleHeight
|
||||||
}
|
|
||||||
|
|
||||||
func (c *listComponent[T]) GetActualHeight() int {
|
|
||||||
items := c.items
|
|
||||||
if len(items) == 0 {
|
|
||||||
return 1 // For empty message
|
|
||||||
}
|
|
||||||
|
|
||||||
maxVisibleItems := min(c.maxVisibleItems, len(items))
|
|
||||||
startIdx := 0
|
|
||||||
|
|
||||||
if len(items) > maxVisibleItems {
|
|
||||||
halfVisible := maxVisibleItems / 2
|
|
||||||
if c.selectedIdx >= halfVisible && c.selectedIdx < len(items)-halfVisible {
|
|
||||||
startIdx = c.selectedIdx - halfVisible
|
|
||||||
} else if c.selectedIdx >= len(items)-halfVisible {
|
|
||||||
startIdx = len(items) - maxVisibleItems
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
endIdx := min(startIdx+maxVisibleItems, len(items))
|
|
||||||
|
|
||||||
height := 0
|
|
||||||
for i := startIdx; i < endIdx; i++ {
|
|
||||||
item := items[i]
|
|
||||||
isFirstInViewport := (i == startIdx)
|
|
||||||
|
|
||||||
// Check if this is a HeaderItem and calculate its height
|
|
||||||
if _, ok := any(item).(HeaderItem); ok {
|
|
||||||
if isFirstInViewport {
|
|
||||||
height += 1 // No top margin
|
|
||||||
} else {
|
|
||||||
height += 2 // With top margin
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
height += 1 // Regular items take 1 line
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return height
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *listComponent[T]) View() string {
|
func (c *listComponent[T]) View() string {
|
||||||
@@ -224,95 +257,88 @@ func (c *listComponent[T]) View() string {
|
|||||||
return c.fallbackMsg
|
return c.fallbackMsg
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate viewport based on actual heights, not item counts
|
// Calculate viewport based on actual heights
|
||||||
startIdx, endIdx := c.calculateViewport()
|
startIdx, endIdx := c.calculateViewport()
|
||||||
|
|
||||||
listItems := make([]string, 0, endIdx-startIdx)
|
listItems := make([]string, 0, endIdx-startIdx)
|
||||||
|
|
||||||
for i := startIdx; i < endIdx; i++ {
|
for i := startIdx; i < endIdx; i++ {
|
||||||
item := items[i]
|
item := items[i]
|
||||||
isFirstInViewport := (i == startIdx)
|
|
||||||
title := item.Render(i == c.selectedIdx, maxWidth, isFirstInViewport)
|
// Special handling for HeaderItem to remove top margin on first item
|
||||||
|
if i == startIdx {
|
||||||
|
// Check if this is a HeaderItem
|
||||||
|
if _, ok := any(item).(Item); ok {
|
||||||
|
if headerItem, isHeader := any(item).(HeaderItem); isHeader {
|
||||||
|
// Render header without top margin when it's first
|
||||||
|
t := theme.CurrentTheme()
|
||||||
|
truncatedStr := truncate.StringWithTail(string(headerItem), uint(maxWidth-1), "...")
|
||||||
|
headerStyle := c.baseStyle.
|
||||||
|
Foreground(t.Accent()).
|
||||||
|
Bold(true).
|
||||||
|
MarginBottom(0).
|
||||||
|
PaddingLeft(1)
|
||||||
|
listItems = append(listItems, headerStyle.Render(truncatedStr))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
title := c.renderItem(item, i == c.selectedIdx, maxWidth, c.baseStyle)
|
||||||
listItems = append(listItems, title)
|
listItems = append(listItems, title)
|
||||||
}
|
}
|
||||||
|
|
||||||
return strings.Join(listItems, "\n")
|
return strings.Join(listItems, "\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
// calculateViewport determines which items to show based on available height
|
// calculateViewport determines which items to show based on available space
|
||||||
func (c *listComponent[T]) calculateViewport() (startIdx, endIdx int) {
|
func (c *listComponent[T]) calculateViewport() (startIdx, endIdx int) {
|
||||||
items := c.items
|
items := c.items
|
||||||
if len(items) == 0 {
|
if len(items) == 0 {
|
||||||
return 0, 0
|
return 0, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to calculate height of an item at given position
|
// Calculate heights of all items
|
||||||
getItemHeight := func(idx int, isFirst bool) int {
|
itemHeights := make([]int, len(items))
|
||||||
if _, ok := any(items[idx]).(HeaderItem); ok {
|
for i, item := range items {
|
||||||
if isFirst {
|
rendered := c.renderItem(item, false, c.maxWidth, c.baseStyle)
|
||||||
return 1 // No top margin
|
itemHeights[i] = lipgloss.Height(rendered)
|
||||||
} else {
|
|
||||||
return 2 // With top margin
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return 1 // Regular items
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we have fewer items than max, show all
|
// Find the range of items that fit within maxVisibleHeight
|
||||||
if len(items) <= c.maxVisibleItems {
|
// Start by trying to center the selected item
|
||||||
return 0, len(items)
|
start := 0
|
||||||
|
end := len(items)
|
||||||
|
|
||||||
|
// Calculate height from start to selected
|
||||||
|
heightToSelected := 0
|
||||||
|
for i := 0; i <= c.selectedIdx && i < len(items); i++ {
|
||||||
|
heightToSelected += itemHeights[i]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to center the selected item in the viewport
|
// If selected item is beyond visible height, scroll to show it
|
||||||
// Start by trying to put selected item in the middle
|
if heightToSelected > c.maxVisibleHeight {
|
||||||
targetStart := c.selectedIdx - c.maxVisibleItems/2
|
// Start from selected and work backwards to find start
|
||||||
if targetStart < 0 {
|
currentHeight := itemHeights[c.selectedIdx]
|
||||||
targetStart = 0
|
start = c.selectedIdx
|
||||||
}
|
|
||||||
|
|
||||||
// Find the actual start and end indices that fit within our height budget
|
for i := c.selectedIdx - 1; i >= 0 && currentHeight+itemHeights[i] <= c.maxVisibleHeight; i-- {
|
||||||
bestStart := 0
|
currentHeight += itemHeights[i]
|
||||||
bestEnd := 0
|
start = i
|
||||||
bestHeight := 0
|
|
||||||
|
|
||||||
// Try different starting positions around our target
|
|
||||||
for start := max(0, targetStart-2); start <= min(len(items)-1, targetStart+2); start++ {
|
|
||||||
currentHeight := 0
|
|
||||||
end := start
|
|
||||||
|
|
||||||
for end < len(items) && currentHeight < c.maxVisibleItems {
|
|
||||||
itemHeight := getItemHeight(end, end == start)
|
|
||||||
if currentHeight+itemHeight > c.maxVisibleItems {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
currentHeight += itemHeight
|
|
||||||
end++
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if this viewport contains the selected item and is better than current best
|
|
||||||
if start <= c.selectedIdx && c.selectedIdx < end {
|
|
||||||
if currentHeight > bestHeight || (currentHeight == bestHeight && abs(start+end-2*c.selectedIdx) < abs(bestStart+bestEnd-2*c.selectedIdx)) {
|
|
||||||
bestStart = start
|
|
||||||
bestEnd = end
|
|
||||||
bestHeight = currentHeight
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If no good viewport found that contains selected item, just show from selected item
|
// Calculate end based on start
|
||||||
if bestEnd == 0 {
|
currentHeight := 0
|
||||||
bestStart = c.selectedIdx
|
for i := start; i < len(items); i++ {
|
||||||
currentHeight := 0
|
if currentHeight+itemHeights[i] > c.maxVisibleHeight {
|
||||||
for bestEnd = bestStart; bestEnd < len(items) && currentHeight < c.maxVisibleItems; bestEnd++ {
|
end = i
|
||||||
itemHeight := getItemHeight(bestEnd, bestEnd == bestStart)
|
break
|
||||||
if currentHeight+itemHeight > c.maxVisibleItems {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
currentHeight += itemHeight
|
|
||||||
}
|
}
|
||||||
|
currentHeight += itemHeights[i]
|
||||||
}
|
}
|
||||||
|
|
||||||
return bestStart, bestEnd
|
return start, end
|
||||||
}
|
}
|
||||||
|
|
||||||
func abs(x int) int {
|
func abs(x int) int {
|
||||||
@@ -329,27 +355,32 @@ func max(a, b int) int {
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewListComponent[T ListItem](
|
func NewListComponent[T any](opts ...Option[T]) List[T] {
|
||||||
items []T,
|
options := &Options[T]{
|
||||||
maxVisibleItems int,
|
baseStyle: styles.NewStyle(), // Default empty style
|
||||||
fallbackMsg string,
|
}
|
||||||
useAlphaNumericKeys bool,
|
|
||||||
) List[T] {
|
for _, opt := range opts {
|
||||||
|
opt(options)
|
||||||
|
}
|
||||||
|
|
||||||
return &listComponent[T]{
|
return &listComponent[T]{
|
||||||
fallbackMsg: fallbackMsg,
|
fallbackMsg: options.fallbackMsg,
|
||||||
items: items,
|
items: options.items,
|
||||||
maxVisibleItems: maxVisibleItems,
|
maxVisibleHeight: options.maxVisibleHeight,
|
||||||
useAlphaNumericKeys: useAlphaNumericKeys,
|
useAlphaNumericKeys: options.useAlphaNumericKeys,
|
||||||
selectedIdx: 0,
|
selectedIdx: 0,
|
||||||
|
renderItem: options.renderItem,
|
||||||
|
isSelectable: options.isSelectable,
|
||||||
|
baseStyle: options.baseStyle,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// StringItem is a simple implementation of ListItem for string values
|
// StringItem is a simple implementation of Item for string values
|
||||||
type StringItem string
|
type StringItem string
|
||||||
|
|
||||||
func (s StringItem) Render(selected bool, width int, isFirstInViewport bool) string {
|
func (s StringItem) Render(selected bool, width int, baseStyle styles.Style) string {
|
||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
baseStyle := styles.NewStyle()
|
|
||||||
|
|
||||||
truncatedStr := truncate.StringWithTail(string(s), uint(width-1), "...")
|
truncatedStr := truncate.StringWithTail(string(s), uint(width-1), "...")
|
||||||
|
|
||||||
@@ -376,23 +407,18 @@ func (s StringItem) Selectable() bool {
|
|||||||
// HeaderItem is a non-selectable header item for grouping
|
// HeaderItem is a non-selectable header item for grouping
|
||||||
type HeaderItem string
|
type HeaderItem string
|
||||||
|
|
||||||
func (h HeaderItem) Render(selected bool, width int, isFirstInViewport bool) string {
|
func (h HeaderItem) Render(selected bool, width int, baseStyle styles.Style) string {
|
||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
baseStyle := styles.NewStyle()
|
|
||||||
|
|
||||||
truncatedStr := truncate.StringWithTail(string(h), uint(width-1), "...")
|
truncatedStr := truncate.StringWithTail(string(h), uint(width-1), "...")
|
||||||
|
|
||||||
headerStyle := baseStyle.
|
headerStyle := baseStyle.
|
||||||
Foreground(t.Accent()).
|
Foreground(t.Accent()).
|
||||||
Bold(true).
|
Bold(true).
|
||||||
|
MarginTop(1).
|
||||||
MarginBottom(0).
|
MarginBottom(0).
|
||||||
PaddingLeft(1)
|
PaddingLeft(1)
|
||||||
|
|
||||||
// Only add top margin if this is not the first item in the viewport
|
|
||||||
if !isFirstInViewport {
|
|
||||||
headerStyle = headerStyle.MarginTop(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
return headerStyle.Render(truncatedStr)
|
return headerStyle.Render(truncatedStr)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -400,16 +426,6 @@ func (h HeaderItem) Selectable() bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewStringList creates a new list component with string items
|
// Ensure StringItem and HeaderItem implement Item
|
||||||
func NewStringList(
|
var _ Item = StringItem("")
|
||||||
items []string,
|
var _ Item = HeaderItem("")
|
||||||
maxVisibleItems int,
|
|
||||||
fallbackMsg string,
|
|
||||||
useAlphaNumericKeys bool,
|
|
||||||
) List[StringItem] {
|
|
||||||
stringItems := make([]StringItem, len(items))
|
|
||||||
for i, item := range items {
|
|
||||||
stringItems[i] = StringItem(item)
|
|
||||||
}
|
|
||||||
return NewListComponent(stringItems, maxVisibleItems, fallbackMsg, useAlphaNumericKeys)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
tea "github.com/charmbracelet/bubbletea/v2"
|
tea "github.com/charmbracelet/bubbletea/v2"
|
||||||
|
"github.com/sst/opencode/internal/styles"
|
||||||
)
|
)
|
||||||
|
|
||||||
// testItem is a simple test implementation of ListItem
|
// testItem is a simple test implementation of ListItem
|
||||||
@@ -11,10 +12,19 @@ type testItem struct {
|
|||||||
value string
|
value string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t testItem) Render(selected bool, width int) string {
|
func (t testItem) Render(
|
||||||
|
selected bool,
|
||||||
|
width int,
|
||||||
|
isFirstInViewport bool,
|
||||||
|
baseStyle styles.Style,
|
||||||
|
) string {
|
||||||
return t.value
|
return t.value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (t testItem) Selectable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// createTestList creates a list with test items for testing
|
// createTestList creates a list with test items for testing
|
||||||
func createTestList() *listComponent[testItem] {
|
func createTestList() *listComponent[testItem] {
|
||||||
items := []testItem{
|
items := []testItem{
|
||||||
@@ -22,7 +32,24 @@ func createTestList() *listComponent[testItem] {
|
|||||||
{value: "item2"},
|
{value: "item2"},
|
||||||
{value: "item3"},
|
{value: "item3"},
|
||||||
}
|
}
|
||||||
list := NewListComponent(items, 5, "empty", false)
|
list := NewListComponent(
|
||||||
|
WithItems(items),
|
||||||
|
WithMaxVisibleItems[testItem](5),
|
||||||
|
WithFallbackMessage[testItem]("empty"),
|
||||||
|
WithAlphaNumericKeys[testItem](false),
|
||||||
|
WithRenderFunc(
|
||||||
|
func(item testItem, selected bool, width int, baseStyle styles.Style) string {
|
||||||
|
return item.Render(selected, width, false, baseStyle)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
WithSelectableFunc(func(item testItem) bool {
|
||||||
|
return item.Selectable()
|
||||||
|
}),
|
||||||
|
WithHeightFunc(func(item testItem, isFirstInViewport bool) int {
|
||||||
|
return 1
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
return list.(*listComponent[testItem])
|
return list.(*listComponent[testItem])
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +82,23 @@ func TestJKKeyNavigation(t *testing.T) {
|
|||||||
{value: "item3"},
|
{value: "item3"},
|
||||||
}
|
}
|
||||||
// Create list with alpha keys enabled
|
// Create list with alpha keys enabled
|
||||||
list := NewListComponent(items, 5, "empty", true).(*listComponent[testItem])
|
list := NewListComponent(
|
||||||
|
WithItems(items),
|
||||||
|
WithMaxVisibleItems[testItem](5),
|
||||||
|
WithFallbackMessage[testItem]("empty"),
|
||||||
|
WithAlphaNumericKeys[testItem](true),
|
||||||
|
WithRenderFunc(
|
||||||
|
func(item testItem, selected bool, width int, baseStyle styles.Style) string {
|
||||||
|
return item.Render(selected, width, false, baseStyle)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
WithSelectableFunc(func(item testItem) bool {
|
||||||
|
return item.Selectable()
|
||||||
|
}),
|
||||||
|
WithHeightFunc(func(item testItem, isFirstInViewport bool) int {
|
||||||
|
return 1
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
// Test j key (down)
|
// Test j key (down)
|
||||||
jKey := tea.KeyPressMsg{Code: 'j', Text: "j"}
|
jKey := tea.KeyPressMsg{Code: 'j', Text: "j"}
|
||||||
@@ -131,7 +174,23 @@ func TestNavigationBoundaries(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestEmptyList(t *testing.T) {
|
func TestEmptyList(t *testing.T) {
|
||||||
emptyList := NewListComponent([]testItem{}, 5, "empty", false).(*listComponent[testItem])
|
emptyList := NewListComponent(
|
||||||
|
WithItems([]testItem{}),
|
||||||
|
WithMaxVisibleItems[testItem](5),
|
||||||
|
WithFallbackMessage[testItem]("empty"),
|
||||||
|
WithAlphaNumericKeys[testItem](false),
|
||||||
|
WithRenderFunc(
|
||||||
|
func(item testItem, selected bool, width int, baseStyle styles.Style) string {
|
||||||
|
return item.Render(selected, width, false, baseStyle)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
WithSelectableFunc(func(item testItem) bool {
|
||||||
|
return item.Selectable()
|
||||||
|
}),
|
||||||
|
WithHeightFunc(func(item testItem, isFirstInViewport bool) int {
|
||||||
|
return 1
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
// Test navigation on empty list (should not crash)
|
// Test navigation on empty list (should not crash)
|
||||||
downKey := tea.KeyPressMsg{Code: tea.KeyDown}
|
downKey := tea.KeyPressMsg{Code: tea.KeyDown}
|
||||||
|
|||||||
@@ -69,6 +69,15 @@ func (s *State) UpdateModelUsage(providerID, modelID string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *State) RemoveModelFromRecentlyUsed(providerID, modelID string) {
|
||||||
|
for i, usage := range s.RecentlyUsedModels {
|
||||||
|
if usage.ProviderID == providerID && usage.ModelID == modelID {
|
||||||
|
s.RecentlyUsedModels = append(s.RecentlyUsedModels[:i], s.RecentlyUsedModels[i+1:]...)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// SaveState writes the provided Config struct to the specified TOML file.
|
// SaveState writes the provided Config struct to the specified TOML file.
|
||||||
// It will create the file if it doesn't exist, or overwrite it if it does.
|
// It will create the file if it doesn't exist, or overwrite it if it does.
|
||||||
func SaveState(filePath string, state *State) error {
|
func SaveState(filePath string, state *State) error {
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ import (
|
|||||||
"github.com/sst/opencode/internal/util"
|
"github.com/sst/opencode/internal/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ANSI escape sequence regex
|
||||||
|
ansiRegex = regexp.MustCompile(`\x1b\[[0-9;]*m`)
|
||||||
|
)
|
||||||
|
|
||||||
// Split a string into lines, additionally returning the size of the widest line.
|
// Split a string into lines, additionally returning the size of the widest line.
|
||||||
func getLines(s string) (lines []string, widest int) {
|
func getLines(s string) (lines []string, widest int) {
|
||||||
lines = strings.Split(s, "\n")
|
lines = strings.Split(s, "\n")
|
||||||
@@ -272,9 +277,6 @@ func combineStyles(bgStyle ansiStyle, fgColor *compat.AdaptiveColor) string {
|
|||||||
|
|
||||||
// getStyleAtPosition extracts the active ANSI style at a given visual position
|
// getStyleAtPosition extracts the active ANSI style at a given visual position
|
||||||
func getStyleAtPosition(s string, targetPos int) ansiStyle {
|
func getStyleAtPosition(s string, targetPos int) ansiStyle {
|
||||||
// ANSI escape sequence regex
|
|
||||||
ansiRegex := regexp.MustCompile(`\x1b\[[0-9;]*m`)
|
|
||||||
|
|
||||||
visualPos := 0
|
visualPos := 0
|
||||||
currentStyle := ansiStyle{}
|
currentStyle := ansiStyle{}
|
||||||
|
|
||||||
|
|||||||
+158
-133
@@ -2,6 +2,7 @@ package tui
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
@@ -55,7 +56,6 @@ const (
|
|||||||
|
|
||||||
const interruptDebounceTimeout = 1 * time.Second
|
const interruptDebounceTimeout = 1 * time.Second
|
||||||
const exitDebounceTimeout = 1 * time.Second
|
const exitDebounceTimeout = 1 * time.Second
|
||||||
const fileViewerFullWidthCutoff = 160
|
|
||||||
|
|
||||||
type appModel struct {
|
type appModel struct {
|
||||||
width, height int
|
width, height int
|
||||||
@@ -65,9 +65,9 @@ type appModel struct {
|
|||||||
editor chat.EditorComponent
|
editor chat.EditorComponent
|
||||||
messages chat.MessagesComponent
|
messages chat.MessagesComponent
|
||||||
completions dialog.CompletionDialog
|
completions dialog.CompletionDialog
|
||||||
commandProvider dialog.CompletionProvider
|
commandProvider completions.CompletionProvider
|
||||||
fileProvider dialog.CompletionProvider
|
fileProvider completions.CompletionProvider
|
||||||
symbolsProvider dialog.CompletionProvider
|
symbolsProvider completions.CompletionProvider
|
||||||
showCompletionDialog bool
|
showCompletionDialog bool
|
||||||
leaderBinding *key.Binding
|
leaderBinding *key.Binding
|
||||||
// isLeaderSequence bool
|
// isLeaderSequence bool
|
||||||
@@ -76,10 +76,6 @@ type appModel struct {
|
|||||||
exitKeyState ExitKeyState
|
exitKeyState ExitKeyState
|
||||||
messagesRight bool
|
messagesRight bool
|
||||||
fileViewer fileviewer.Model
|
fileViewer fileviewer.Model
|
||||||
lastMouse tea.Mouse
|
|
||||||
fileViewerStart int
|
|
||||||
fileViewerEnd int
|
|
||||||
fileViewerHit bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a appModel) Init() tea.Cmd {
|
func (a appModel) Init() tea.Cmd {
|
||||||
@@ -114,11 +110,6 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
case tea.KeyPressMsg:
|
case tea.KeyPressMsg:
|
||||||
keyString := msg.String()
|
keyString := msg.String()
|
||||||
|
|
||||||
// Handle Ctrl+Z for suspend
|
|
||||||
if keyString == "ctrl+z" {
|
|
||||||
return a, tea.Suspend
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1. Handle active modal
|
// 1. Handle active modal
|
||||||
if a.modal != nil {
|
if a.modal != nil {
|
||||||
switch keyString {
|
switch keyString {
|
||||||
@@ -281,36 +272,27 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
return a, util.CmdHandler(commands.ExecuteCommandsMsg(matches))
|
return a, util.CmdHandler(commands.ExecuteCommandsMsg(matches))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fallback: suspend if ctrl+z is pressed and no user keybind matched
|
||||||
|
if keyString == "ctrl+z" {
|
||||||
|
return a, tea.Suspend
|
||||||
|
}
|
||||||
|
|
||||||
// 10. Fallback to editor. This is for other characters like backspace, tab, etc.
|
// 10. Fallback to editor. This is for other characters like backspace, tab, etc.
|
||||||
updatedEditor, cmd := a.editor.Update(msg)
|
updatedEditor, cmd := a.editor.Update(msg)
|
||||||
a.editor = updatedEditor.(chat.EditorComponent)
|
a.editor = updatedEditor.(chat.EditorComponent)
|
||||||
return a, cmd
|
return a, cmd
|
||||||
case tea.MouseWheelMsg:
|
case tea.MouseWheelMsg:
|
||||||
if a.modal != nil {
|
if a.modal != nil {
|
||||||
return a, nil
|
u, cmd := a.modal.Update(msg)
|
||||||
}
|
a.modal = u.(layout.Modal)
|
||||||
|
|
||||||
var cmd tea.Cmd
|
|
||||||
if a.fileViewerHit {
|
|
||||||
a.fileViewer, cmd = a.fileViewer.Update(msg)
|
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
} else {
|
return a, tea.Batch(cmds...)
|
||||||
updated, cmd := a.messages.Update(msg)
|
|
||||||
a.messages = updated.(chat.MessagesComponent)
|
|
||||||
cmds = append(cmds, cmd)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
updated, cmd := a.messages.Update(msg)
|
||||||
|
a.messages = updated.(chat.MessagesComponent)
|
||||||
|
cmds = append(cmds, cmd)
|
||||||
return a, tea.Batch(cmds...)
|
return a, tea.Batch(cmds...)
|
||||||
case tea.MouseMotionMsg:
|
|
||||||
a.lastMouse = msg.Mouse()
|
|
||||||
a.fileViewerHit = a.fileViewer.HasFile() &&
|
|
||||||
a.lastMouse.X > a.fileViewerStart &&
|
|
||||||
a.lastMouse.X < a.fileViewerEnd
|
|
||||||
case tea.MouseClickMsg:
|
|
||||||
a.lastMouse = msg.Mouse()
|
|
||||||
a.fileViewerHit = a.fileViewer.HasFile() &&
|
|
||||||
a.lastMouse.X > a.fileViewerStart &&
|
|
||||||
a.lastMouse.X < a.fileViewerEnd
|
|
||||||
case tea.BackgroundColorMsg:
|
case tea.BackgroundColorMsg:
|
||||||
styles.Terminal = &styles.TerminalInfo{
|
styles.Terminal = &styles.TerminalInfo{
|
||||||
Background: msg.Color,
|
Background: msg.Color,
|
||||||
@@ -352,7 +334,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
case app.SetEditorContentMsg:
|
case app.SetEditorContentMsg:
|
||||||
// Set the editor content without sending
|
// Set the editor content without sending
|
||||||
a.editor.SetValue(msg.Text)
|
a.editor.SetValueWithAttachments(msg.Text)
|
||||||
updated, cmd := a.editor.Focus()
|
updated, cmd := a.editor.Focus()
|
||||||
a.editor = updated.(chat.EditorComponent)
|
a.editor = updated.(chat.EditorComponent)
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
@@ -457,14 +439,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
case tea.WindowSizeMsg:
|
case tea.WindowSizeMsg:
|
||||||
msg.Height -= 2 // Make space for the status bar
|
msg.Height -= 2 // Make space for the status bar
|
||||||
a.width, a.height = msg.Width, msg.Height
|
a.width, a.height = msg.Width, msg.Height
|
||||||
container := min(a.width, 84)
|
container := min(a.width, app.MAX_CONTAINER_WIDTH)
|
||||||
if a.fileViewer.HasFile() {
|
|
||||||
if a.width < fileViewerFullWidthCutoff {
|
|
||||||
container = a.width
|
|
||||||
} else {
|
|
||||||
container = min(min(a.width, max(a.width/2, 50)), 84)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
layout.Current = &layout.LayoutInfo{
|
layout.Current = &layout.LayoutInfo{
|
||||||
Viewport: layout.Dimensions{
|
Viewport: layout.Dimensions{
|
||||||
Width: a.width,
|
Width: a.width,
|
||||||
@@ -474,30 +449,18 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
Width: container,
|
Width: container,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
mainWidth := layout.Current.Container.Width
|
|
||||||
a.messages.SetWidth(mainWidth - 4)
|
|
||||||
|
|
||||||
sideWidth := a.width - mainWidth
|
|
||||||
if a.width < fileViewerFullWidthCutoff {
|
|
||||||
sideWidth = a.width
|
|
||||||
}
|
|
||||||
a.fileViewerStart = mainWidth
|
|
||||||
a.fileViewerEnd = a.fileViewerStart + sideWidth
|
|
||||||
if a.messagesRight {
|
|
||||||
a.fileViewerStart = 0
|
|
||||||
a.fileViewerEnd = sideWidth
|
|
||||||
}
|
|
||||||
a.fileViewer, cmd = a.fileViewer.SetSize(sideWidth, layout.Current.Viewport.Height)
|
|
||||||
cmds = append(cmds, cmd)
|
|
||||||
case app.SessionSelectedMsg:
|
case app.SessionSelectedMsg:
|
||||||
messages, err := a.app.ListMessages(context.Background(), msg.ID)
|
messages, err := a.app.ListMessages(context.Background(), msg.ID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("Failed to list messages", "error", err)
|
slog.Error("Failed to list messages", "error", err.Error())
|
||||||
return a, toast.NewErrorToast("Failed to open session")
|
return a, toast.NewErrorToast("Failed to open session")
|
||||||
}
|
}
|
||||||
a.app.Session = msg
|
a.app.Session = msg
|
||||||
a.app.Messages = messages
|
a.app.Messages = messages
|
||||||
return a, util.CmdHandler(app.SessionLoadedMsg{})
|
return a, util.CmdHandler(app.SessionLoadedMsg{})
|
||||||
|
case app.SessionCreatedMsg:
|
||||||
|
a.app.Session = msg.Session
|
||||||
|
return a, util.CmdHandler(app.SessionLoadedMsg{})
|
||||||
case app.ModelSelectedMsg:
|
case app.ModelSelectedMsg:
|
||||||
a.app.Provider = &msg.Provider
|
a.app.Provider = &msg.Provider
|
||||||
a.app.Model = &msg.Model
|
a.app.Model = &msg.Model
|
||||||
@@ -565,48 +528,22 @@ func (a appModel) View() string {
|
|||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
|
|
||||||
var mainLayout string
|
var mainLayout string
|
||||||
mainWidth := layout.Current.Container.Width - 4
|
|
||||||
if a.app.Session.ID == "" {
|
if a.app.Session.ID == "" {
|
||||||
mainLayout = a.home(mainWidth)
|
mainLayout = a.home()
|
||||||
} else {
|
} else {
|
||||||
mainLayout = a.chat(mainWidth)
|
mainLayout = a.chat()
|
||||||
}
|
}
|
||||||
mainLayout = styles.NewStyle().
|
mainLayout = styles.NewStyle().
|
||||||
Background(t.Background()).
|
Background(t.Background()).
|
||||||
Padding(0, 2).
|
Padding(0, 2).
|
||||||
Render(mainLayout)
|
Render(mainLayout)
|
||||||
|
mainLayout = lipgloss.PlaceHorizontal(
|
||||||
mainHeight := lipgloss.Height(mainLayout)
|
a.width,
|
||||||
|
lipgloss.Center,
|
||||||
if a.fileViewer.HasFile() {
|
mainLayout,
|
||||||
file := a.fileViewer.View()
|
styles.WhitespaceStyle(t.Background()),
|
||||||
baseStyle := styles.NewStyle().Background(t.BackgroundPanel())
|
)
|
||||||
sidePanel := baseStyle.Height(mainHeight).Render(file)
|
|
||||||
if a.width >= fileViewerFullWidthCutoff {
|
|
||||||
if a.messagesRight {
|
|
||||||
mainLayout = lipgloss.JoinHorizontal(
|
|
||||||
lipgloss.Top,
|
|
||||||
sidePanel,
|
|
||||||
mainLayout,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
mainLayout = lipgloss.JoinHorizontal(
|
|
||||||
lipgloss.Top,
|
|
||||||
mainLayout,
|
|
||||||
sidePanel,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
mainLayout = sidePanel
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
mainLayout = lipgloss.PlaceHorizontal(
|
|
||||||
a.width,
|
|
||||||
lipgloss.Center,
|
|
||||||
mainLayout,
|
|
||||||
styles.WhitespaceStyle(t.Background()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
mainStyle := styles.NewStyle().Background(t.Background())
|
mainStyle := styles.NewStyle().Background(t.Background())
|
||||||
mainLayout = mainStyle.Render(mainLayout)
|
mainLayout = mainStyle.Render(mainLayout)
|
||||||
@@ -642,8 +579,9 @@ func (a appModel) openFile(filepath string) (tea.Model, tea.Cmd) {
|
|||||||
return a, cmd
|
return a, cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a appModel) home(width int) string {
|
func (a appModel) home() string {
|
||||||
t := theme.CurrentTheme()
|
t := theme.CurrentTheme()
|
||||||
|
effectiveWidth := a.width - 4
|
||||||
baseStyle := styles.NewStyle().Background(t.Background())
|
baseStyle := styles.NewStyle().Background(t.Background())
|
||||||
base := baseStyle.Render
|
base := baseStyle.Render
|
||||||
muted := styles.NewStyle().Foreground(t.TextMuted()).Background(t.Background()).Render
|
muted := styles.NewStyle().Foreground(t.TextMuted()).Background(t.Background()).Render
|
||||||
@@ -674,7 +612,7 @@ func (a appModel) home(width int) string {
|
|||||||
|
|
||||||
logoAndVersion := strings.Join([]string{logo, version}, "\n")
|
logoAndVersion := strings.Join([]string{logo, version}, "\n")
|
||||||
logoAndVersion = lipgloss.PlaceHorizontal(
|
logoAndVersion = lipgloss.PlaceHorizontal(
|
||||||
width,
|
effectiveWidth,
|
||||||
lipgloss.Center,
|
lipgloss.Center,
|
||||||
logoAndVersion,
|
logoAndVersion,
|
||||||
styles.WhitespaceStyle(t.Background()),
|
styles.WhitespaceStyle(t.Background()),
|
||||||
@@ -685,7 +623,7 @@ func (a appModel) home(width int) string {
|
|||||||
cmdcomp.WithLimit(6),
|
cmdcomp.WithLimit(6),
|
||||||
)
|
)
|
||||||
cmds := lipgloss.PlaceHorizontal(
|
cmds := lipgloss.PlaceHorizontal(
|
||||||
width,
|
effectiveWidth,
|
||||||
lipgloss.Center,
|
lipgloss.Center,
|
||||||
commandsView.View(),
|
commandsView.View(),
|
||||||
styles.WhitespaceStyle(t.Background()),
|
styles.WhitespaceStyle(t.Background()),
|
||||||
@@ -697,19 +635,16 @@ func (a appModel) home(width int) string {
|
|||||||
lines = append(lines, logoAndVersion)
|
lines = append(lines, logoAndVersion)
|
||||||
lines = append(lines, "")
|
lines = append(lines, "")
|
||||||
lines = append(lines, "")
|
lines = append(lines, "")
|
||||||
// lines = append(lines, base("cwd ")+muted(cwd))
|
|
||||||
// lines = append(lines, base("config ")+muted(config))
|
|
||||||
// lines = append(lines, "")
|
|
||||||
lines = append(lines, cmds)
|
lines = append(lines, cmds)
|
||||||
lines = append(lines, "")
|
lines = append(lines, "")
|
||||||
lines = append(lines, "")
|
lines = append(lines, "")
|
||||||
|
|
||||||
mainHeight := lipgloss.Height(strings.Join(lines, "\n"))
|
mainHeight := lipgloss.Height(strings.Join(lines, "\n"))
|
||||||
|
|
||||||
editorWidth := min(width, 80)
|
editorView := a.editor.View()
|
||||||
editorView := a.editor.View(editorWidth)
|
editorWidth := lipgloss.Width(editorView)
|
||||||
editorView = lipgloss.PlaceHorizontal(
|
editorView = lipgloss.PlaceHorizontal(
|
||||||
width,
|
effectiveWidth,
|
||||||
lipgloss.Center,
|
lipgloss.Center,
|
||||||
editorView,
|
editorView,
|
||||||
styles.WhitespaceStyle(t.Background()),
|
styles.WhitespaceStyle(t.Background()),
|
||||||
@@ -719,7 +654,7 @@ func (a appModel) home(width int) string {
|
|||||||
editorLines := a.editor.Lines()
|
editorLines := a.editor.Lines()
|
||||||
|
|
||||||
mainLayout := lipgloss.Place(
|
mainLayout := lipgloss.Place(
|
||||||
width,
|
effectiveWidth,
|
||||||
a.height,
|
a.height,
|
||||||
lipgloss.Center,
|
lipgloss.Center,
|
||||||
lipgloss.Center,
|
lipgloss.Center,
|
||||||
@@ -727,14 +662,14 @@ func (a appModel) home(width int) string {
|
|||||||
styles.WhitespaceStyle(t.Background()),
|
styles.WhitespaceStyle(t.Background()),
|
||||||
)
|
)
|
||||||
|
|
||||||
editorX := (width - editorWidth) / 2
|
editorX := (effectiveWidth - editorWidth) / 2
|
||||||
editorY := (a.height / 2) + (mainHeight / 2) - 2
|
editorY := (a.height / 2) + (mainHeight / 2) - 2
|
||||||
|
|
||||||
if editorLines > 1 {
|
if editorLines > 1 {
|
||||||
mainLayout = layout.PlaceOverlay(
|
mainLayout = layout.PlaceOverlay(
|
||||||
editorX,
|
editorX,
|
||||||
editorY,
|
editorY,
|
||||||
a.editor.Content(editorWidth),
|
a.editor.Content(),
|
||||||
mainLayout,
|
mainLayout,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -755,23 +690,31 @@ func (a appModel) home(width int) string {
|
|||||||
return mainLayout
|
return mainLayout
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a appModel) chat(width int) string {
|
func (a appModel) chat() string {
|
||||||
editorView := a.editor.View(width)
|
effectiveWidth := a.width - 4
|
||||||
|
t := theme.CurrentTheme()
|
||||||
|
editorView := a.editor.View()
|
||||||
lines := a.editor.Lines()
|
lines := a.editor.Lines()
|
||||||
messagesView := a.messages.View(width, a.height-5)
|
messagesView := a.messages.View()
|
||||||
|
|
||||||
editorWidth := lipgloss.Width(editorView)
|
editorWidth := lipgloss.Width(editorView)
|
||||||
editorHeight := max(lines, 5)
|
editorHeight := max(lines, 5)
|
||||||
|
editorView = lipgloss.PlaceHorizontal(
|
||||||
|
effectiveWidth,
|
||||||
|
lipgloss.Center,
|
||||||
|
editorView,
|
||||||
|
styles.WhitespaceStyle(t.Background()),
|
||||||
|
)
|
||||||
|
|
||||||
mainLayout := messagesView + "\n" + editorView
|
mainLayout := messagesView + "\n" + editorView
|
||||||
editorX := (a.width - editorWidth) / 2
|
editorX := (effectiveWidth - editorWidth) / 2
|
||||||
|
|
||||||
if lines > 1 {
|
if lines > 1 {
|
||||||
editorY := a.height - editorHeight
|
editorY := a.height - editorHeight
|
||||||
mainLayout = layout.PlaceOverlay(
|
mainLayout = layout.PlaceOverlay(
|
||||||
editorX,
|
editorX,
|
||||||
editorY,
|
editorY,
|
||||||
a.editor.Content(width),
|
a.editor.Content(),
|
||||||
mainLayout,
|
mainLayout,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -806,6 +749,10 @@ func (a appModel) executeCommand(command commands.Command) (tea.Model, tea.Cmd)
|
|||||||
updated, cmd := a.app.SwitchMode()
|
updated, cmd := a.app.SwitchMode()
|
||||||
a.app = updated
|
a.app = updated
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
|
case commands.SwitchModeReverseCommand:
|
||||||
|
updated, cmd := a.app.SwitchModeReverse()
|
||||||
|
a.app = updated
|
||||||
|
cmds = append(cmds, cmd)
|
||||||
case commands.EditorOpenCommand:
|
case commands.EditorOpenCommand:
|
||||||
if a.app.IsBusy() {
|
if a.app.IsBusy() {
|
||||||
// status.Warn("Agent is working, please wait...")
|
// status.Warn("Agent is working, please wait...")
|
||||||
@@ -897,6 +844,56 @@ func (a appModel) executeCommand(command commands.Command) (tea.Model, tea.Cmd)
|
|||||||
}
|
}
|
||||||
// TODO: block until compaction is complete
|
// TODO: block until compaction is complete
|
||||||
a.app.CompactSession(context.Background())
|
a.app.CompactSession(context.Background())
|
||||||
|
case commands.SessionExportCommand:
|
||||||
|
if a.app.Session.ID == "" {
|
||||||
|
return a, toast.NewErrorToast("No active session to export.")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use current conversation history
|
||||||
|
messages := a.app.Messages
|
||||||
|
if len(messages) == 0 {
|
||||||
|
return a, toast.NewInfoToast("No messages to export.")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format to Markdown
|
||||||
|
markdownContent := formatConversationToMarkdown(messages)
|
||||||
|
|
||||||
|
// Check if EDITOR is set
|
||||||
|
editor := os.Getenv("EDITOR")
|
||||||
|
if editor == "" {
|
||||||
|
return a, toast.NewErrorToast("No EDITOR set, can't open editor")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create and write to temp file
|
||||||
|
tmpfile, err := os.CreateTemp("", "conversation-*.md")
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to create temp file", "error", err)
|
||||||
|
return a, toast.NewErrorToast("Failed to create temporary file.")
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = tmpfile.WriteString(markdownContent)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to write to temp file", "error", err)
|
||||||
|
tmpfile.Close()
|
||||||
|
os.Remove(tmpfile.Name())
|
||||||
|
return a, toast.NewErrorToast("Failed to write conversation to file.")
|
||||||
|
}
|
||||||
|
tmpfile.Close()
|
||||||
|
|
||||||
|
// Open in editor
|
||||||
|
c := exec.Command(editor, tmpfile.Name())
|
||||||
|
c.Stdin = os.Stdin
|
||||||
|
c.Stdout = os.Stdout
|
||||||
|
c.Stderr = os.Stderr
|
||||||
|
cmd = tea.ExecProcess(c, func(err error) tea.Msg {
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to open editor for conversation", "error", err)
|
||||||
|
}
|
||||||
|
// Clean up the file after editor closes
|
||||||
|
os.Remove(tmpfile.Name())
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
cmds = append(cmds, cmd)
|
||||||
case commands.ToolDetailsCommand:
|
case commands.ToolDetailsCommand:
|
||||||
message := "Tool details are now visible"
|
message := "Tool details are now visible"
|
||||||
if a.messages.ToolDetailsVisible() {
|
if a.messages.ToolDetailsVisible() {
|
||||||
@@ -910,12 +907,11 @@ func (a appModel) executeCommand(command commands.Command) (tea.Model, tea.Cmd)
|
|||||||
case commands.ThemeListCommand:
|
case commands.ThemeListCommand:
|
||||||
themeDialog := dialog.NewThemeDialog()
|
themeDialog := dialog.NewThemeDialog()
|
||||||
a.modal = themeDialog
|
a.modal = themeDialog
|
||||||
case commands.FileListCommand:
|
// case commands.FileListCommand:
|
||||||
a.editor.Blur()
|
// a.editor.Blur()
|
||||||
provider := completions.NewFileContextGroup(a.app)
|
// findDialog := dialog.NewFindDialog(a.fileProvider)
|
||||||
findDialog := dialog.NewFindDialog(provider)
|
// cmds = append(cmds, findDialog.Init())
|
||||||
findDialog.SetWidth(layout.Current.Container.Width - 8)
|
// a.modal = findDialog
|
||||||
a.modal = findDialog
|
|
||||||
case commands.FileCloseCommand:
|
case commands.FileCloseCommand:
|
||||||
a.fileViewer, cmd = a.fileViewer.Clear()
|
a.fileViewer, cmd = a.fileViewer.Clear()
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
@@ -948,11 +944,11 @@ func (a appModel) executeCommand(command commands.Command) (tea.Model, tea.Cmd)
|
|||||||
a.editor = updated.(chat.EditorComponent)
|
a.editor = updated.(chat.EditorComponent)
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
case commands.MessagesFirstCommand:
|
case commands.MessagesFirstCommand:
|
||||||
updated, cmd := a.messages.First()
|
updated, cmd := a.messages.GotoTop()
|
||||||
a.messages = updated.(chat.MessagesComponent)
|
a.messages = updated.(chat.MessagesComponent)
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
case commands.MessagesLastCommand:
|
case commands.MessagesLastCommand:
|
||||||
updated, cmd := a.messages.Last()
|
updated, cmd := a.messages.GotoBottom()
|
||||||
a.messages = updated.(chat.MessagesComponent)
|
a.messages = updated.(chat.MessagesComponent)
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
case commands.MessagesPageUpCommand:
|
case commands.MessagesPageUpCommand:
|
||||||
@@ -991,26 +987,14 @@ func (a appModel) executeCommand(command commands.Command) (tea.Model, tea.Cmd)
|
|||||||
a.messages = updated.(chat.MessagesComponent)
|
a.messages = updated.(chat.MessagesComponent)
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
}
|
}
|
||||||
case commands.MessagesPreviousCommand:
|
|
||||||
updated, cmd := a.messages.Previous()
|
|
||||||
a.messages = updated.(chat.MessagesComponent)
|
|
||||||
cmds = append(cmds, cmd)
|
|
||||||
case commands.MessagesNextCommand:
|
|
||||||
updated, cmd := a.messages.Next()
|
|
||||||
a.messages = updated.(chat.MessagesComponent)
|
|
||||||
cmds = append(cmds, cmd)
|
|
||||||
case commands.MessagesLayoutToggleCommand:
|
case commands.MessagesLayoutToggleCommand:
|
||||||
a.messagesRight = !a.messagesRight
|
a.messagesRight = !a.messagesRight
|
||||||
a.app.State.MessagesRight = a.messagesRight
|
a.app.State.MessagesRight = a.messagesRight
|
||||||
a.app.SaveState()
|
a.app.SaveState()
|
||||||
case commands.MessagesCopyCommand:
|
case commands.MessagesCopyCommand:
|
||||||
selected := a.messages.Selected()
|
updated, cmd := a.messages.CopyLastMessage()
|
||||||
if selected != "" {
|
a.messages = updated.(chat.MessagesComponent)
|
||||||
cmd = a.app.SetClipboard(selected)
|
cmds = append(cmds, cmd)
|
||||||
cmds = append(cmds, cmd)
|
|
||||||
cmd = toast.NewSuccessToast("Message copied to clipboard")
|
|
||||||
cmds = append(cmds, cmd)
|
|
||||||
}
|
|
||||||
case commands.MessagesRevertCommand:
|
case commands.MessagesRevertCommand:
|
||||||
case commands.AppExitCommand:
|
case commands.AppExitCommand:
|
||||||
return a, tea.Quit
|
return a, tea.Quit
|
||||||
@@ -1053,3 +1037,44 @@ func NewModel(app *app.App) tea.Model {
|
|||||||
|
|
||||||
return model
|
return model
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func formatConversationToMarkdown(messages []app.Message) string {
|
||||||
|
var builder strings.Builder
|
||||||
|
|
||||||
|
builder.WriteString("# Conversation History\n\n")
|
||||||
|
|
||||||
|
for _, msg := range messages {
|
||||||
|
builder.WriteString("---\n\n")
|
||||||
|
|
||||||
|
var role string
|
||||||
|
var timestamp time.Time
|
||||||
|
|
||||||
|
switch info := msg.Info.(type) {
|
||||||
|
case opencode.UserMessage:
|
||||||
|
role = "User"
|
||||||
|
timestamp = time.UnixMilli(int64(info.Time.Created))
|
||||||
|
case opencode.AssistantMessage:
|
||||||
|
role = "Assistant"
|
||||||
|
timestamp = time.UnixMilli(int64(info.Time.Created))
|
||||||
|
default:
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.WriteString(
|
||||||
|
fmt.Sprintf("**%s** (*%s*)\n\n", role, timestamp.Format("2006-01-02 15:04:05")),
|
||||||
|
)
|
||||||
|
|
||||||
|
for _, part := range msg.Parts {
|
||||||
|
switch p := part.(type) {
|
||||||
|
case opencode.TextPart:
|
||||||
|
builder.WriteString(p.Text + "\n\n")
|
||||||
|
case opencode.FilePart:
|
||||||
|
builder.WriteString(fmt.Sprintf("[File: %s]\n\n", p.Filename))
|
||||||
|
case opencode.ToolPart:
|
||||||
|
builder.WriteString(fmt.Sprintf("[Tool: %s]\n\n", p.Tool))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder.String()
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
configured_endpoints: 22
|
configured_endpoints: 22
|
||||||
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-05150c78e0e6e97b0ce97ed685ebcf1cb01dc839beccb99e9d3ead5b783cfd47.yml
|
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-8792f91dd070f7b4ee671fc86e8a03976dc7fb6ee49f8c99ad989e1597003774.yml
|
||||||
openapi_spec_hash: 833a5b6d53d98dc2beac2c4c394b20d5
|
openapi_spec_hash: fe9dc3a074be560de0b97df9b5af2c1b
|
||||||
config_hash: 3695cfc829cfaae14490850b4a1ed282
|
config_hash: b7f3d9742335715c458494988498b183
|
||||||
|
|||||||
+12
-15
@@ -49,14 +49,11 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
client := opencode.NewClient()
|
client := opencode.NewClient()
|
||||||
stream := client.Event.ListStreaming(context.TODO())
|
sessions, err := client.Session.List(context.TODO())
|
||||||
for stream.Next() {
|
|
||||||
fmt.Printf("%+v\n", stream.Current())
|
|
||||||
}
|
|
||||||
err := stream.Err()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err.Error())
|
panic(err.Error())
|
||||||
}
|
}
|
||||||
|
fmt.Printf("%+v\n", sessions)
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -145,7 +142,7 @@ client := opencode.NewClient(
|
|||||||
option.WithHeader("X-Some-Header", "custom_header_info"),
|
option.WithHeader("X-Some-Header", "custom_header_info"),
|
||||||
)
|
)
|
||||||
|
|
||||||
client.Event.List(context.TODO(), ...,
|
client.Session.List(context.TODO(), ...,
|
||||||
// Override the header
|
// Override the header
|
||||||
option.WithHeader("X-Some-Header", "some_other_custom_header_info"),
|
option.WithHeader("X-Some-Header", "some_other_custom_header_info"),
|
||||||
// Add an undocumented field to the request body, using sjson syntax
|
// Add an undocumented field to the request body, using sjson syntax
|
||||||
@@ -174,14 +171,14 @@ When the API returns a non-success status code, we return an error with type
|
|||||||
To handle errors, we recommend that you use the `errors.As` pattern:
|
To handle errors, we recommend that you use the `errors.As` pattern:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
stream := client.Event.ListStreaming(context.TODO())
|
_, err := client.Session.List(context.TODO())
|
||||||
if stream.Err() != nil {
|
if err != nil {
|
||||||
var apierr *opencode.Error
|
var apierr *opencode.Error
|
||||||
if errors.As(stream.Err(), &apierr) {
|
if errors.As(err, &apierr) {
|
||||||
println(string(apierr.DumpRequest(true))) // Prints the serialized HTTP request
|
println(string(apierr.DumpRequest(true))) // Prints the serialized HTTP request
|
||||||
println(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response
|
println(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response
|
||||||
}
|
}
|
||||||
panic(stream.Err().Error()) // GET "/event": 400 Bad Request { ... }
|
panic(err.Error()) // GET "/session": 400 Bad Request { ... }
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -199,7 +196,7 @@ To set a per-retry timeout, use `option.WithRequestTimeout()`.
|
|||||||
// This sets the timeout for the request, including all the retries.
|
// This sets the timeout for the request, including all the retries.
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
client.Event.ListStreaming(
|
client.Session.List(
|
||||||
ctx,
|
ctx,
|
||||||
// This sets the per-retry timeout
|
// This sets the per-retry timeout
|
||||||
option.WithRequestTimeout(20*time.Second),
|
option.WithRequestTimeout(20*time.Second),
|
||||||
@@ -234,7 +231,7 @@ client := opencode.NewClient(
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Override per-request:
|
// Override per-request:
|
||||||
client.Event.ListStreaming(context.TODO(), option.WithMaxRetries(5))
|
client.Session.List(context.TODO(), option.WithMaxRetries(5))
|
||||||
```
|
```
|
||||||
|
|
||||||
### Accessing raw response data (e.g. response headers)
|
### Accessing raw response data (e.g. response headers)
|
||||||
@@ -245,11 +242,11 @@ you need to examine response headers, status codes, or other details.
|
|||||||
```go
|
```go
|
||||||
// Create a variable to store the HTTP response
|
// Create a variable to store the HTTP response
|
||||||
var response *http.Response
|
var response *http.Response
|
||||||
stream := client.Event.ListStreaming(context.TODO(), option.WithResponseInto(&response))
|
sessions, err := client.Session.List(context.TODO(), option.WithResponseInto(&response))
|
||||||
if stream.Err() != nil {
|
if err != nil {
|
||||||
// handle error
|
// handle error
|
||||||
}
|
}
|
||||||
fmt.Printf("%+v\n", events)
|
fmt.Printf("%+v\n", sessions)
|
||||||
|
|
||||||
fmt.Printf("Status Code: %d\n", response.StatusCode)
|
fmt.Printf("Status Code: %d\n", response.StatusCode)
|
||||||
fmt.Printf("Headers: %+#v\n", response.Header)
|
fmt.Printf("Headers: %+#v\n", response.Header)
|
||||||
|
|||||||
+10
-7
@@ -21,6 +21,9 @@ Response Types:
|
|||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#App">App</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#App">App</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#LogLevel">LogLevel</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#LogLevel">LogLevel</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Mode">Mode</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Mode">Mode</a>
|
||||||
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Model">Model</a>
|
||||||
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Provider">Provider</a>
|
||||||
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppProvidersResponse">AppProvidersResponse</a>
|
||||||
|
|
||||||
Methods:
|
Methods:
|
||||||
|
|
||||||
@@ -28,6 +31,7 @@ Methods:
|
|||||||
- <code title="post /app/init">client.App.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppService.Init">Init</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
- <code title="post /app/init">client.App.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppService.Init">Init</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
||||||
- <code title="post /log">client.App.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppService.Log">Log</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppLogParams">AppLogParams</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
- <code title="post /log">client.App.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppService.Log">Log</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppLogParams">AppLogParams</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
||||||
- <code title="get /mode">client.App.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppService.Modes">Modes</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) ([]<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Mode">Mode</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
- <code title="get /mode">client.App.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppService.Modes">Modes</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) ([]<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Mode">Mode</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
||||||
|
- <code title="get /config/providers">client.App.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppService.Providers">Providers</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppProvidersResponse">AppProvidersResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
||||||
|
|
||||||
# Find
|
# Find
|
||||||
|
|
||||||
@@ -59,17 +63,15 @@ Methods:
|
|||||||
Response Types:
|
Response Types:
|
||||||
|
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Config">Config</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Config">Config</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Keybinds">Keybinds</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#KeybindsConfig">KeybindsConfig</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#McpLocal">McpLocal</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#LayoutConfig">LayoutConfig</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#McpRemote">McpRemote</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#McpLocalConfig">McpLocalConfig</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Model">Model</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#McpRemoteConfig">McpRemoteConfig</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Provider">Provider</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#ModeConfig">ModeConfig</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#ConfigProvidersResponse">ConfigProvidersResponse</a>
|
|
||||||
|
|
||||||
Methods:
|
Methods:
|
||||||
|
|
||||||
- <code title="get /config">client.Config.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#ConfigService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Config">Config</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
- <code title="get /config">client.Config.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#ConfigService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Config">Config</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
||||||
- <code title="get /config/providers">client.Config.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#ConfigService.Providers">Providers</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#ConfigProvidersResponse">ConfigProvidersResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
|
|
||||||
|
|
||||||
# Session
|
# Session
|
||||||
|
|
||||||
@@ -85,6 +87,7 @@ Response Types:
|
|||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Message">Message</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Message">Message</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Part">Part</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Part">Part</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>
|
||||||
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SnapshotPart">SnapshotPart</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#StepFinishPart">StepFinishPart</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#StepFinishPart">StepFinishPart</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#StepStartPart">StepStartPart</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#StepStartPart">StepStartPart</a>
|
||||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#TextPart">TextPart</a>
|
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#TextPart">TextPart</a>
|
||||||
|
|||||||
@@ -63,6 +63,14 @@ func (r *AppService) Modes(ctx context.Context, opts ...option.RequestOption) (r
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// List all providers
|
||||||
|
func (r *AppService) Providers(ctx context.Context, opts ...option.RequestOption) (res *AppProvidersResponse, err error) {
|
||||||
|
opts = append(r.Options[:], opts...)
|
||||||
|
path := "config/providers"
|
||||||
|
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
type App struct {
|
type App struct {
|
||||||
Git bool `json:"git,required"`
|
Git bool `json:"git,required"`
|
||||||
Hostname string `json:"hostname,required"`
|
Hostname string `json:"hostname,required"`
|
||||||
@@ -203,6 +211,145 @@ func (r modeModelJSON) RawJSON() string {
|
|||||||
return r.raw
|
return r.raw
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Model struct {
|
||||||
|
ID string `json:"id,required"`
|
||||||
|
Attachment bool `json:"attachment,required"`
|
||||||
|
Cost ModelCost `json:"cost,required"`
|
||||||
|
Limit ModelLimit `json:"limit,required"`
|
||||||
|
Name string `json:"name,required"`
|
||||||
|
Options map[string]interface{} `json:"options,required"`
|
||||||
|
Reasoning bool `json:"reasoning,required"`
|
||||||
|
ReleaseDate string `json:"release_date,required"`
|
||||||
|
Temperature bool `json:"temperature,required"`
|
||||||
|
ToolCall bool `json:"tool_call,required"`
|
||||||
|
JSON modelJSON `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// modelJSON contains the JSON metadata for the struct [Model]
|
||||||
|
type modelJSON struct {
|
||||||
|
ID apijson.Field
|
||||||
|
Attachment apijson.Field
|
||||||
|
Cost apijson.Field
|
||||||
|
Limit apijson.Field
|
||||||
|
Name apijson.Field
|
||||||
|
Options apijson.Field
|
||||||
|
Reasoning apijson.Field
|
||||||
|
ReleaseDate apijson.Field
|
||||||
|
Temperature apijson.Field
|
||||||
|
ToolCall apijson.Field
|
||||||
|
raw string
|
||||||
|
ExtraFields map[string]apijson.Field
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Model) UnmarshalJSON(data []byte) (err error) {
|
||||||
|
return apijson.UnmarshalRoot(data, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r modelJSON) RawJSON() string {
|
||||||
|
return r.raw
|
||||||
|
}
|
||||||
|
|
||||||
|
type ModelCost struct {
|
||||||
|
Input float64 `json:"input,required"`
|
||||||
|
Output float64 `json:"output,required"`
|
||||||
|
CacheRead float64 `json:"cache_read"`
|
||||||
|
CacheWrite float64 `json:"cache_write"`
|
||||||
|
JSON modelCostJSON `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// modelCostJSON contains the JSON metadata for the struct [ModelCost]
|
||||||
|
type modelCostJSON struct {
|
||||||
|
Input apijson.Field
|
||||||
|
Output apijson.Field
|
||||||
|
CacheRead apijson.Field
|
||||||
|
CacheWrite apijson.Field
|
||||||
|
raw string
|
||||||
|
ExtraFields map[string]apijson.Field
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ModelCost) UnmarshalJSON(data []byte) (err error) {
|
||||||
|
return apijson.UnmarshalRoot(data, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r modelCostJSON) RawJSON() string {
|
||||||
|
return r.raw
|
||||||
|
}
|
||||||
|
|
||||||
|
type ModelLimit struct {
|
||||||
|
Context float64 `json:"context,required"`
|
||||||
|
Output float64 `json:"output,required"`
|
||||||
|
JSON modelLimitJSON `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// modelLimitJSON contains the JSON metadata for the struct [ModelLimit]
|
||||||
|
type modelLimitJSON struct {
|
||||||
|
Context apijson.Field
|
||||||
|
Output apijson.Field
|
||||||
|
raw string
|
||||||
|
ExtraFields map[string]apijson.Field
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ModelLimit) UnmarshalJSON(data []byte) (err error) {
|
||||||
|
return apijson.UnmarshalRoot(data, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r modelLimitJSON) RawJSON() string {
|
||||||
|
return r.raw
|
||||||
|
}
|
||||||
|
|
||||||
|
type Provider struct {
|
||||||
|
ID string `json:"id,required"`
|
||||||
|
Env []string `json:"env,required"`
|
||||||
|
Models map[string]Model `json:"models,required"`
|
||||||
|
Name string `json:"name,required"`
|
||||||
|
API string `json:"api"`
|
||||||
|
Npm string `json:"npm"`
|
||||||
|
JSON providerJSON `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// providerJSON contains the JSON metadata for the struct [Provider]
|
||||||
|
type providerJSON struct {
|
||||||
|
ID apijson.Field
|
||||||
|
Env apijson.Field
|
||||||
|
Models apijson.Field
|
||||||
|
Name apijson.Field
|
||||||
|
API apijson.Field
|
||||||
|
Npm apijson.Field
|
||||||
|
raw string
|
||||||
|
ExtraFields map[string]apijson.Field
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Provider) UnmarshalJSON(data []byte) (err error) {
|
||||||
|
return apijson.UnmarshalRoot(data, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r providerJSON) RawJSON() string {
|
||||||
|
return r.raw
|
||||||
|
}
|
||||||
|
|
||||||
|
type AppProvidersResponse struct {
|
||||||
|
Default map[string]string `json:"default,required"`
|
||||||
|
Providers []Provider `json:"providers,required"`
|
||||||
|
JSON appProvidersResponseJSON `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// appProvidersResponseJSON contains the JSON metadata for the struct
|
||||||
|
// [AppProvidersResponse]
|
||||||
|
type appProvidersResponseJSON struct {
|
||||||
|
Default apijson.Field
|
||||||
|
Providers apijson.Field
|
||||||
|
raw string
|
||||||
|
ExtraFields map[string]apijson.Field
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *AppProvidersResponse) UnmarshalJSON(data []byte) (err error) {
|
||||||
|
return apijson.UnmarshalRoot(data, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r appProvidersResponseJSON) RawJSON() string {
|
||||||
|
return r.raw
|
||||||
|
}
|
||||||
|
|
||||||
type AppLogParams struct {
|
type AppLogParams struct {
|
||||||
// Log level
|
// Log level
|
||||||
Level param.Field[AppLogParamsLevel] `json:"level,required"`
|
Level param.Field[AppLogParamsLevel] `json:"level,required"`
|
||||||
|
|||||||
@@ -107,3 +107,25 @@ func TestAppModes(t *testing.T) {
|
|||||||
t.Fatalf("err should be nil: %s", err.Error())
|
t.Fatalf("err should be nil: %s", err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAppProviders(t *testing.T) {
|
||||||
|
t.Skip("skipped: tests are disabled for the time being")
|
||||||
|
baseURL := "http://localhost:4010"
|
||||||
|
if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok {
|
||||||
|
baseURL = envURL
|
||||||
|
}
|
||||||
|
if !testutil.CheckTestServer(t, baseURL) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
client := opencode.NewClient(
|
||||||
|
option.WithBaseURL(baseURL),
|
||||||
|
)
|
||||||
|
_, err := client.App.Providers(context.TODO())
|
||||||
|
if err != nil {
|
||||||
|
var apierr *opencode.Error
|
||||||
|
if errors.As(err, &apierr) {
|
||||||
|
t.Log(string(apierr.DumpRequest(true)))
|
||||||
|
}
|
||||||
|
t.Fatalf("err should be nil: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ func TestUserAgentHeader(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
client.Event.ListStreaming(context.Background())
|
client.Session.List(context.Background())
|
||||||
if userAgent != fmt.Sprintf("Opencode/Go %s", internal.PackageVersion) {
|
if userAgent != fmt.Sprintf("Opencode/Go %s", internal.PackageVersion) {
|
||||||
t.Errorf("Expected User-Agent to be correct, but got: %#v", userAgent)
|
t.Errorf("Expected User-Agent to be correct, but got: %#v", userAgent)
|
||||||
}
|
}
|
||||||
@@ -61,11 +61,7 @@ func TestRetryAfter(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
stream := client.Event.ListStreaming(context.Background())
|
_, err := client.Session.List(context.Background())
|
||||||
for stream.Next() {
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
err := stream.Err()
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Error("Expected there to be a cancel error")
|
t.Error("Expected there to be a cancel error")
|
||||||
}
|
}
|
||||||
@@ -99,11 +95,7 @@ func TestDeleteRetryCountHeader(t *testing.T) {
|
|||||||
}),
|
}),
|
||||||
option.WithHeaderDel("X-Stainless-Retry-Count"),
|
option.WithHeaderDel("X-Stainless-Retry-Count"),
|
||||||
)
|
)
|
||||||
stream := client.Event.ListStreaming(context.Background())
|
_, err := client.Session.List(context.Background())
|
||||||
for stream.Next() {
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
err := stream.Err()
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Error("Expected there to be a cancel error")
|
t.Error("Expected there to be a cancel error")
|
||||||
}
|
}
|
||||||
@@ -132,11 +124,7 @@ func TestOverwriteRetryCountHeader(t *testing.T) {
|
|||||||
}),
|
}),
|
||||||
option.WithHeader("X-Stainless-Retry-Count", "42"),
|
option.WithHeader("X-Stainless-Retry-Count", "42"),
|
||||||
)
|
)
|
||||||
stream := client.Event.ListStreaming(context.Background())
|
_, err := client.Session.List(context.Background())
|
||||||
for stream.Next() {
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
err := stream.Err()
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Error("Expected there to be a cancel error")
|
t.Error("Expected there to be a cancel error")
|
||||||
}
|
}
|
||||||
@@ -164,11 +152,7 @@ func TestRetryAfterMs(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
stream := client.Event.ListStreaming(context.Background())
|
_, err := client.Session.List(context.Background())
|
||||||
for stream.Next() {
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
err := stream.Err()
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Error("Expected there to be a cancel error")
|
t.Error("Expected there to be a cancel error")
|
||||||
}
|
}
|
||||||
@@ -190,11 +174,7 @@ func TestContextCancel(t *testing.T) {
|
|||||||
)
|
)
|
||||||
cancelCtx, cancel := context.WithCancel(context.Background())
|
cancelCtx, cancel := context.WithCancel(context.Background())
|
||||||
cancel()
|
cancel()
|
||||||
stream := client.Event.ListStreaming(cancelCtx)
|
_, err := client.Session.List(cancelCtx)
|
||||||
for stream.Next() {
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
err := stream.Err()
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Error("Expected there to be a cancel error")
|
t.Error("Expected there to be a cancel error")
|
||||||
}
|
}
|
||||||
@@ -213,11 +193,7 @@ func TestContextCancelDelay(t *testing.T) {
|
|||||||
)
|
)
|
||||||
cancelCtx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
|
cancelCtx, cancel := context.WithTimeout(context.Background(), 2*time.Millisecond)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
stream := client.Event.ListStreaming(cancelCtx)
|
_, err := client.Session.List(cancelCtx)
|
||||||
for stream.Next() {
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
err := stream.Err()
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Error("expected there to be a cancel error")
|
t.Error("expected there to be a cancel error")
|
||||||
}
|
}
|
||||||
@@ -242,11 +218,7 @@ func TestContextDeadline(t *testing.T) {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
stream := client.Event.ListStreaming(deadlineCtx)
|
_, err := client.Session.List(deadlineCtx)
|
||||||
for stream.Next() {
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
err := stream.Err()
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Error("expected there to be a deadline error")
|
t.Error("expected there to be a deadline error")
|
||||||
}
|
}
|
||||||
|
|||||||
+81
-226
@@ -40,14 +40,6 @@ func (r *ConfigService) Get(ctx context.Context, opts ...option.RequestOption) (
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// List all providers
|
|
||||||
func (r *ConfigService) Providers(ctx context.Context, opts ...option.RequestOption) (res *ConfigProvidersResponse, err error) {
|
|
||||||
opts = append(r.Options[:], opts...)
|
|
||||||
path := "config/providers"
|
|
||||||
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
// JSON schema reference for configuration validation
|
// JSON schema reference for configuration validation
|
||||||
Schema string `json:"$schema"`
|
Schema string `json:"$schema"`
|
||||||
@@ -62,12 +54,15 @@ type Config struct {
|
|||||||
// Additional instruction files or patterns to include
|
// Additional instruction files or patterns to include
|
||||||
Instructions []string `json:"instructions"`
|
Instructions []string `json:"instructions"`
|
||||||
// Custom keybind configurations
|
// Custom keybind configurations
|
||||||
Keybinds Keybinds `json:"keybinds"`
|
Keybinds KeybindsConfig `json:"keybinds"`
|
||||||
|
// Layout to use for the TUI
|
||||||
|
Layout LayoutConfig `json:"layout"`
|
||||||
// Minimum log level to write to log files
|
// Minimum log level to write to log files
|
||||||
LogLevel LogLevel `json:"log_level"`
|
LogLevel LogLevel `json:"log_level"`
|
||||||
// MCP (Model Context Protocol) server configurations
|
// MCP (Model Context Protocol) server configurations
|
||||||
Mcp map[string]ConfigMcp `json:"mcp"`
|
Mcp map[string]ConfigMcp `json:"mcp"`
|
||||||
Mode ConfigMode `json:"mode"`
|
// Modes configuration, see https://opencode.ai/docs/modes
|
||||||
|
Mode ConfigMode `json:"mode"`
|
||||||
// Model to use in the format of provider/model, eg anthropic/claude-2
|
// Model to use in the format of provider/model, eg anthropic/claude-2
|
||||||
Model string `json:"model"`
|
Model string `json:"model"`
|
||||||
// Custom provider configurations and model overrides
|
// Custom provider configurations and model overrides
|
||||||
@@ -91,6 +86,7 @@ type configJSON struct {
|
|||||||
Experimental apijson.Field
|
Experimental apijson.Field
|
||||||
Instructions apijson.Field
|
Instructions apijson.Field
|
||||||
Keybinds apijson.Field
|
Keybinds apijson.Field
|
||||||
|
Layout apijson.Field
|
||||||
LogLevel apijson.Field
|
LogLevel apijson.Field
|
||||||
Mcp apijson.Field
|
Mcp apijson.Field
|
||||||
Mode apijson.Field
|
Mode apijson.Field
|
||||||
@@ -243,12 +239,12 @@ func (r *ConfigMcp) UnmarshalJSON(data []byte) (err error) {
|
|||||||
// AsUnion returns a [ConfigMcpUnion] interface which you can cast to the specific
|
// AsUnion returns a [ConfigMcpUnion] interface which you can cast to the specific
|
||||||
// types for more type safety.
|
// types for more type safety.
|
||||||
//
|
//
|
||||||
// Possible runtime types of the union are [McpLocal], [McpRemote].
|
// Possible runtime types of the union are [McpLocalConfig], [McpRemoteConfig].
|
||||||
func (r ConfigMcp) AsUnion() ConfigMcpUnion {
|
func (r ConfigMcp) AsUnion() ConfigMcpUnion {
|
||||||
return r.union
|
return r.union
|
||||||
}
|
}
|
||||||
|
|
||||||
// Union satisfied by [McpLocal] or [McpRemote].
|
// Union satisfied by [McpLocalConfig] or [McpRemoteConfig].
|
||||||
type ConfigMcpUnion interface {
|
type ConfigMcpUnion interface {
|
||||||
implementsConfigMcp()
|
implementsConfigMcp()
|
||||||
}
|
}
|
||||||
@@ -259,12 +255,12 @@ func init() {
|
|||||||
"type",
|
"type",
|
||||||
apijson.UnionVariant{
|
apijson.UnionVariant{
|
||||||
TypeFilter: gjson.JSON,
|
TypeFilter: gjson.JSON,
|
||||||
Type: reflect.TypeOf(McpLocal{}),
|
Type: reflect.TypeOf(McpLocalConfig{}),
|
||||||
DiscriminatorValue: "local",
|
DiscriminatorValue: "local",
|
||||||
},
|
},
|
||||||
apijson.UnionVariant{
|
apijson.UnionVariant{
|
||||||
TypeFilter: gjson.JSON,
|
TypeFilter: gjson.JSON,
|
||||||
Type: reflect.TypeOf(McpRemote{}),
|
Type: reflect.TypeOf(McpRemoteConfig{}),
|
||||||
DiscriminatorValue: "remote",
|
DiscriminatorValue: "remote",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -286,10 +282,11 @@ func (r ConfigMcpType) IsKnown() bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Modes configuration, see https://opencode.ai/docs/modes
|
||||||
type ConfigMode struct {
|
type ConfigMode struct {
|
||||||
Build ConfigModeBuild `json:"build"`
|
Build ModeConfig `json:"build"`
|
||||||
Plan ConfigModePlan `json:"plan"`
|
Plan ModeConfig `json:"plan"`
|
||||||
ExtraFields map[string]ConfigMode `json:"-,extras"`
|
ExtraFields map[string]ModeConfig `json:"-,extras"`
|
||||||
JSON configModeJSON `json:"-"`
|
JSON configModeJSON `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -309,54 +306,6 @@ func (r configModeJSON) RawJSON() string {
|
|||||||
return r.raw
|
return r.raw
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConfigModeBuild struct {
|
|
||||||
Model string `json:"model"`
|
|
||||||
Prompt string `json:"prompt"`
|
|
||||||
Tools map[string]bool `json:"tools"`
|
|
||||||
JSON configModeBuildJSON `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// configModeBuildJSON contains the JSON metadata for the struct [ConfigModeBuild]
|
|
||||||
type configModeBuildJSON struct {
|
|
||||||
Model apijson.Field
|
|
||||||
Prompt apijson.Field
|
|
||||||
Tools apijson.Field
|
|
||||||
raw string
|
|
||||||
ExtraFields map[string]apijson.Field
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *ConfigModeBuild) UnmarshalJSON(data []byte) (err error) {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r configModeBuildJSON) RawJSON() string {
|
|
||||||
return r.raw
|
|
||||||
}
|
|
||||||
|
|
||||||
type ConfigModePlan struct {
|
|
||||||
Model string `json:"model"`
|
|
||||||
Prompt string `json:"prompt"`
|
|
||||||
Tools map[string]bool `json:"tools"`
|
|
||||||
JSON configModePlanJSON `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// configModePlanJSON contains the JSON metadata for the struct [ConfigModePlan]
|
|
||||||
type configModePlanJSON struct {
|
|
||||||
Model apijson.Field
|
|
||||||
Prompt apijson.Field
|
|
||||||
Tools apijson.Field
|
|
||||||
raw string
|
|
||||||
ExtraFields map[string]apijson.Field
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *ConfigModePlan) UnmarshalJSON(data []byte) (err error) {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r configModePlanJSON) RawJSON() string {
|
|
||||||
return r.raw
|
|
||||||
}
|
|
||||||
|
|
||||||
type ConfigProvider struct {
|
type ConfigProvider struct {
|
||||||
Models map[string]ConfigProviderModel `json:"models,required"`
|
Models map[string]ConfigProviderModel `json:"models,required"`
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
@@ -495,7 +444,7 @@ func (r ConfigShare) IsKnown() bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
type Keybinds struct {
|
type KeybindsConfig struct {
|
||||||
// Exit the application
|
// Exit the application
|
||||||
AppExit string `json:"app_exit,required"`
|
AppExit string `json:"app_exit,required"`
|
||||||
// Show help dialog
|
// Show help dialog
|
||||||
@@ -548,6 +497,8 @@ type Keybinds struct {
|
|||||||
ProjectInit string `json:"project_init,required"`
|
ProjectInit string `json:"project_init,required"`
|
||||||
// Compact the session
|
// Compact the session
|
||||||
SessionCompact string `json:"session_compact,required"`
|
SessionCompact string `json:"session_compact,required"`
|
||||||
|
// Export session to editor
|
||||||
|
SessionExport string `json:"session_export,required"`
|
||||||
// Interrupt current session
|
// Interrupt current session
|
||||||
SessionInterrupt string `json:"session_interrupt,required"`
|
SessionInterrupt string `json:"session_interrupt,required"`
|
||||||
// List all sessions
|
// List all sessions
|
||||||
@@ -560,15 +511,17 @@ type Keybinds struct {
|
|||||||
SessionUnshare string `json:"session_unshare,required"`
|
SessionUnshare string `json:"session_unshare,required"`
|
||||||
// Switch mode
|
// Switch mode
|
||||||
SwitchMode string `json:"switch_mode,required"`
|
SwitchMode string `json:"switch_mode,required"`
|
||||||
|
// Switch mode reverse
|
||||||
|
SwitchModeReverse string `json:"switch_mode_reverse,required"`
|
||||||
// List available themes
|
// List available themes
|
||||||
ThemeList string `json:"theme_list,required"`
|
ThemeList string `json:"theme_list,required"`
|
||||||
// Toggle tool details
|
// Toggle tool details
|
||||||
ToolDetails string `json:"tool_details,required"`
|
ToolDetails string `json:"tool_details,required"`
|
||||||
JSON keybindsJSON `json:"-"`
|
JSON keybindsConfigJSON `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// keybindsJSON contains the JSON metadata for the struct [Keybinds]
|
// keybindsConfigJSON contains the JSON metadata for the struct [KeybindsConfig]
|
||||||
type keybindsJSON struct {
|
type keybindsConfigJSON struct {
|
||||||
AppExit apijson.Field
|
AppExit apijson.Field
|
||||||
AppHelp apijson.Field
|
AppHelp apijson.Field
|
||||||
EditorOpen apijson.Field
|
EditorOpen apijson.Field
|
||||||
@@ -595,40 +548,57 @@ type keybindsJSON struct {
|
|||||||
ModelList apijson.Field
|
ModelList apijson.Field
|
||||||
ProjectInit apijson.Field
|
ProjectInit apijson.Field
|
||||||
SessionCompact apijson.Field
|
SessionCompact apijson.Field
|
||||||
|
SessionExport apijson.Field
|
||||||
SessionInterrupt apijson.Field
|
SessionInterrupt apijson.Field
|
||||||
SessionList apijson.Field
|
SessionList apijson.Field
|
||||||
SessionNew apijson.Field
|
SessionNew apijson.Field
|
||||||
SessionShare apijson.Field
|
SessionShare apijson.Field
|
||||||
SessionUnshare apijson.Field
|
SessionUnshare apijson.Field
|
||||||
SwitchMode apijson.Field
|
SwitchMode apijson.Field
|
||||||
|
SwitchModeReverse apijson.Field
|
||||||
ThemeList apijson.Field
|
ThemeList apijson.Field
|
||||||
ToolDetails apijson.Field
|
ToolDetails apijson.Field
|
||||||
raw string
|
raw string
|
||||||
ExtraFields map[string]apijson.Field
|
ExtraFields map[string]apijson.Field
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Keybinds) UnmarshalJSON(data []byte) (err error) {
|
func (r *KeybindsConfig) UnmarshalJSON(data []byte) (err error) {
|
||||||
return apijson.UnmarshalRoot(data, r)
|
return apijson.UnmarshalRoot(data, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r keybindsJSON) RawJSON() string {
|
func (r keybindsConfigJSON) RawJSON() string {
|
||||||
return r.raw
|
return r.raw
|
||||||
}
|
}
|
||||||
|
|
||||||
type McpLocal struct {
|
type LayoutConfig string
|
||||||
|
|
||||||
|
const (
|
||||||
|
LayoutConfigAuto LayoutConfig = "auto"
|
||||||
|
LayoutConfigStretch LayoutConfig = "stretch"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (r LayoutConfig) IsKnown() bool {
|
||||||
|
switch r {
|
||||||
|
case LayoutConfigAuto, LayoutConfigStretch:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
type McpLocalConfig struct {
|
||||||
// Command and arguments to run the MCP server
|
// Command and arguments to run the MCP server
|
||||||
Command []string `json:"command,required"`
|
Command []string `json:"command,required"`
|
||||||
// Type of MCP server connection
|
// Type of MCP server connection
|
||||||
Type McpLocalType `json:"type,required"`
|
Type McpLocalConfigType `json:"type,required"`
|
||||||
// Enable or disable the MCP server on startup
|
// Enable or disable the MCP server on startup
|
||||||
Enabled bool `json:"enabled"`
|
Enabled bool `json:"enabled"`
|
||||||
// Environment variables to set when running the MCP server
|
// Environment variables to set when running the MCP server
|
||||||
Environment map[string]string `json:"environment"`
|
Environment map[string]string `json:"environment"`
|
||||||
JSON mcpLocalJSON `json:"-"`
|
JSON mcpLocalConfigJSON `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpLocalJSON contains the JSON metadata for the struct [McpLocal]
|
// mcpLocalConfigJSON contains the JSON metadata for the struct [McpLocalConfig]
|
||||||
type mcpLocalJSON struct {
|
type mcpLocalConfigJSON struct {
|
||||||
Command apijson.Field
|
Command apijson.Field
|
||||||
Type apijson.Field
|
Type apijson.Field
|
||||||
Enabled apijson.Field
|
Enabled apijson.Field
|
||||||
@@ -637,43 +607,43 @@ type mcpLocalJSON struct {
|
|||||||
ExtraFields map[string]apijson.Field
|
ExtraFields map[string]apijson.Field
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *McpLocal) UnmarshalJSON(data []byte) (err error) {
|
func (r *McpLocalConfig) UnmarshalJSON(data []byte) (err error) {
|
||||||
return apijson.UnmarshalRoot(data, r)
|
return apijson.UnmarshalRoot(data, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r mcpLocalJSON) RawJSON() string {
|
func (r mcpLocalConfigJSON) RawJSON() string {
|
||||||
return r.raw
|
return r.raw
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r McpLocal) implementsConfigMcp() {}
|
func (r McpLocalConfig) implementsConfigMcp() {}
|
||||||
|
|
||||||
// Type of MCP server connection
|
// Type of MCP server connection
|
||||||
type McpLocalType string
|
type McpLocalConfigType string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
McpLocalTypeLocal McpLocalType = "local"
|
McpLocalConfigTypeLocal McpLocalConfigType = "local"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (r McpLocalType) IsKnown() bool {
|
func (r McpLocalConfigType) IsKnown() bool {
|
||||||
switch r {
|
switch r {
|
||||||
case McpLocalTypeLocal:
|
case McpLocalConfigTypeLocal:
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
type McpRemote struct {
|
type McpRemoteConfig struct {
|
||||||
// Type of MCP server connection
|
// Type of MCP server connection
|
||||||
Type McpRemoteType `json:"type,required"`
|
Type McpRemoteConfigType `json:"type,required"`
|
||||||
// URL of the remote MCP server
|
// URL of the remote MCP server
|
||||||
URL string `json:"url,required"`
|
URL string `json:"url,required"`
|
||||||
// Enable or disable the MCP server on startup
|
// Enable or disable the MCP server on startup
|
||||||
Enabled bool `json:"enabled"`
|
Enabled bool `json:"enabled"`
|
||||||
JSON mcpRemoteJSON `json:"-"`
|
JSON mcpRemoteConfigJSON `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// mcpRemoteJSON contains the JSON metadata for the struct [McpRemote]
|
// mcpRemoteConfigJSON contains the JSON metadata for the struct [McpRemoteConfig]
|
||||||
type mcpRemoteJSON struct {
|
type mcpRemoteConfigJSON struct {
|
||||||
Type apijson.Field
|
Type apijson.Field
|
||||||
URL apijson.Field
|
URL apijson.Field
|
||||||
Enabled apijson.Field
|
Enabled apijson.Field
|
||||||
@@ -681,166 +651,51 @@ type mcpRemoteJSON struct {
|
|||||||
ExtraFields map[string]apijson.Field
|
ExtraFields map[string]apijson.Field
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *McpRemote) UnmarshalJSON(data []byte) (err error) {
|
func (r *McpRemoteConfig) UnmarshalJSON(data []byte) (err error) {
|
||||||
return apijson.UnmarshalRoot(data, r)
|
return apijson.UnmarshalRoot(data, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r mcpRemoteJSON) RawJSON() string {
|
func (r mcpRemoteConfigJSON) RawJSON() string {
|
||||||
return r.raw
|
return r.raw
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r McpRemote) implementsConfigMcp() {}
|
func (r McpRemoteConfig) implementsConfigMcp() {}
|
||||||
|
|
||||||
// Type of MCP server connection
|
// Type of MCP server connection
|
||||||
type McpRemoteType string
|
type McpRemoteConfigType string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
McpRemoteTypeRemote McpRemoteType = "remote"
|
McpRemoteConfigTypeRemote McpRemoteConfigType = "remote"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (r McpRemoteType) IsKnown() bool {
|
func (r McpRemoteConfigType) IsKnown() bool {
|
||||||
switch r {
|
switch r {
|
||||||
case McpRemoteTypeRemote:
|
case McpRemoteConfigTypeRemote:
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
type Model struct {
|
type ModeConfig struct {
|
||||||
ID string `json:"id,required"`
|
Model string `json:"model"`
|
||||||
Attachment bool `json:"attachment,required"`
|
Prompt string `json:"prompt"`
|
||||||
Cost ModelCost `json:"cost,required"`
|
Tools map[string]bool `json:"tools"`
|
||||||
Limit ModelLimit `json:"limit,required"`
|
JSON modeConfigJSON `json:"-"`
|
||||||
Name string `json:"name,required"`
|
|
||||||
Options map[string]interface{} `json:"options,required"`
|
|
||||||
Reasoning bool `json:"reasoning,required"`
|
|
||||||
ReleaseDate string `json:"release_date,required"`
|
|
||||||
Temperature bool `json:"temperature,required"`
|
|
||||||
ToolCall bool `json:"tool_call,required"`
|
|
||||||
JSON modelJSON `json:"-"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// modelJSON contains the JSON metadata for the struct [Model]
|
// modeConfigJSON contains the JSON metadata for the struct [ModeConfig]
|
||||||
type modelJSON struct {
|
type modeConfigJSON struct {
|
||||||
ID apijson.Field
|
Model apijson.Field
|
||||||
Attachment apijson.Field
|
Prompt apijson.Field
|
||||||
Cost apijson.Field
|
Tools apijson.Field
|
||||||
Limit apijson.Field
|
|
||||||
Name apijson.Field
|
|
||||||
Options apijson.Field
|
|
||||||
Reasoning apijson.Field
|
|
||||||
ReleaseDate apijson.Field
|
|
||||||
Temperature apijson.Field
|
|
||||||
ToolCall apijson.Field
|
|
||||||
raw string
|
raw string
|
||||||
ExtraFields map[string]apijson.Field
|
ExtraFields map[string]apijson.Field
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Model) UnmarshalJSON(data []byte) (err error) {
|
func (r *ModeConfig) UnmarshalJSON(data []byte) (err error) {
|
||||||
return apijson.UnmarshalRoot(data, r)
|
return apijson.UnmarshalRoot(data, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r modelJSON) RawJSON() string {
|
func (r modeConfigJSON) RawJSON() string {
|
||||||
return r.raw
|
|
||||||
}
|
|
||||||
|
|
||||||
type ModelCost struct {
|
|
||||||
Input float64 `json:"input,required"`
|
|
||||||
Output float64 `json:"output,required"`
|
|
||||||
CacheRead float64 `json:"cache_read"`
|
|
||||||
CacheWrite float64 `json:"cache_write"`
|
|
||||||
JSON modelCostJSON `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// modelCostJSON contains the JSON metadata for the struct [ModelCost]
|
|
||||||
type modelCostJSON struct {
|
|
||||||
Input apijson.Field
|
|
||||||
Output apijson.Field
|
|
||||||
CacheRead apijson.Field
|
|
||||||
CacheWrite apijson.Field
|
|
||||||
raw string
|
|
||||||
ExtraFields map[string]apijson.Field
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *ModelCost) UnmarshalJSON(data []byte) (err error) {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r modelCostJSON) RawJSON() string {
|
|
||||||
return r.raw
|
|
||||||
}
|
|
||||||
|
|
||||||
type ModelLimit struct {
|
|
||||||
Context float64 `json:"context,required"`
|
|
||||||
Output float64 `json:"output,required"`
|
|
||||||
JSON modelLimitJSON `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// modelLimitJSON contains the JSON metadata for the struct [ModelLimit]
|
|
||||||
type modelLimitJSON struct {
|
|
||||||
Context apijson.Field
|
|
||||||
Output apijson.Field
|
|
||||||
raw string
|
|
||||||
ExtraFields map[string]apijson.Field
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *ModelLimit) UnmarshalJSON(data []byte) (err error) {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r modelLimitJSON) RawJSON() string {
|
|
||||||
return r.raw
|
|
||||||
}
|
|
||||||
|
|
||||||
type Provider struct {
|
|
||||||
ID string `json:"id,required"`
|
|
||||||
Env []string `json:"env,required"`
|
|
||||||
Models map[string]Model `json:"models,required"`
|
|
||||||
Name string `json:"name,required"`
|
|
||||||
API string `json:"api"`
|
|
||||||
Npm string `json:"npm"`
|
|
||||||
JSON providerJSON `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// providerJSON contains the JSON metadata for the struct [Provider]
|
|
||||||
type providerJSON struct {
|
|
||||||
ID apijson.Field
|
|
||||||
Env apijson.Field
|
|
||||||
Models apijson.Field
|
|
||||||
Name apijson.Field
|
|
||||||
API apijson.Field
|
|
||||||
Npm apijson.Field
|
|
||||||
raw string
|
|
||||||
ExtraFields map[string]apijson.Field
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Provider) UnmarshalJSON(data []byte) (err error) {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r providerJSON) RawJSON() string {
|
|
||||||
return r.raw
|
|
||||||
}
|
|
||||||
|
|
||||||
type ConfigProvidersResponse struct {
|
|
||||||
Default map[string]string `json:"default,required"`
|
|
||||||
Providers []Provider `json:"providers,required"`
|
|
||||||
JSON configProvidersResponseJSON `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// configProvidersResponseJSON contains the JSON metadata for the struct
|
|
||||||
// [ConfigProvidersResponse]
|
|
||||||
type configProvidersResponseJSON struct {
|
|
||||||
Default apijson.Field
|
|
||||||
Providers apijson.Field
|
|
||||||
raw string
|
|
||||||
ExtraFields map[string]apijson.Field
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *ConfigProvidersResponse) UnmarshalJSON(data []byte) (err error) {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r configProvidersResponseJSON) RawJSON() string {
|
|
||||||
return r.raw
|
return r.raw
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,25 +34,3 @@ func TestConfigGet(t *testing.T) {
|
|||||||
t.Fatalf("err should be nil: %s", err.Error())
|
t.Fatalf("err should be nil: %s", err.Error())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestConfigProviders(t *testing.T) {
|
|
||||||
t.Skip("skipped: tests are disabled for the time being")
|
|
||||||
baseURL := "http://localhost:4010"
|
|
||||||
if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok {
|
|
||||||
baseURL = envURL
|
|
||||||
}
|
|
||||||
if !testutil.CheckTestServer(t, baseURL) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
client := opencode.NewClient(
|
|
||||||
option.WithBaseURL(baseURL),
|
|
||||||
)
|
|
||||||
_, err := client.Config.Providers(context.TODO())
|
|
||||||
if err != nil {
|
|
||||||
var apierr *opencode.Error
|
|
||||||
if errors.As(err, &apierr) {
|
|
||||||
t.Log(string(apierr.DumpRequest(true)))
|
|
||||||
}
|
|
||||||
t.Fatalf("err should be nil: %s", err.Error())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+65
-59
@@ -659,13 +659,13 @@ func (r *Part) UnmarshalJSON(data []byte) (err error) {
|
|||||||
// for more type safety.
|
// for more type safety.
|
||||||
//
|
//
|
||||||
// Possible runtime types of the union are [TextPart], [FilePart], [ToolPart],
|
// Possible runtime types of the union are [TextPart], [FilePart], [ToolPart],
|
||||||
// [StepStartPart], [StepFinishPart], [PartObject].
|
// [StepStartPart], [StepFinishPart], [SnapshotPart].
|
||||||
func (r Part) AsUnion() PartUnion {
|
func (r Part) AsUnion() PartUnion {
|
||||||
return r.union
|
return r.union
|
||||||
}
|
}
|
||||||
|
|
||||||
// Union satisfied by [TextPart], [FilePart], [ToolPart], [StepStartPart],
|
// Union satisfied by [TextPart], [FilePart], [ToolPart], [StepStartPart],
|
||||||
// [StepFinishPart] or [PartObject].
|
// [StepFinishPart] or [SnapshotPart].
|
||||||
type PartUnion interface {
|
type PartUnion interface {
|
||||||
implementsPart()
|
implementsPart()
|
||||||
}
|
}
|
||||||
@@ -673,78 +673,40 @@ type PartUnion interface {
|
|||||||
func init() {
|
func init() {
|
||||||
apijson.RegisterUnion(
|
apijson.RegisterUnion(
|
||||||
reflect.TypeOf((*PartUnion)(nil)).Elem(),
|
reflect.TypeOf((*PartUnion)(nil)).Elem(),
|
||||||
"",
|
"type",
|
||||||
apijson.UnionVariant{
|
apijson.UnionVariant{
|
||||||
TypeFilter: gjson.JSON,
|
TypeFilter: gjson.JSON,
|
||||||
Type: reflect.TypeOf(TextPart{}),
|
Type: reflect.TypeOf(TextPart{}),
|
||||||
|
DiscriminatorValue: "text",
|
||||||
},
|
},
|
||||||
apijson.UnionVariant{
|
apijson.UnionVariant{
|
||||||
TypeFilter: gjson.JSON,
|
TypeFilter: gjson.JSON,
|
||||||
Type: reflect.TypeOf(FilePart{}),
|
Type: reflect.TypeOf(FilePart{}),
|
||||||
|
DiscriminatorValue: "file",
|
||||||
},
|
},
|
||||||
apijson.UnionVariant{
|
apijson.UnionVariant{
|
||||||
TypeFilter: gjson.JSON,
|
TypeFilter: gjson.JSON,
|
||||||
Type: reflect.TypeOf(ToolPart{}),
|
Type: reflect.TypeOf(ToolPart{}),
|
||||||
|
DiscriminatorValue: "tool",
|
||||||
},
|
},
|
||||||
apijson.UnionVariant{
|
apijson.UnionVariant{
|
||||||
TypeFilter: gjson.JSON,
|
TypeFilter: gjson.JSON,
|
||||||
Type: reflect.TypeOf(StepStartPart{}),
|
Type: reflect.TypeOf(StepStartPart{}),
|
||||||
|
DiscriminatorValue: "step-start",
|
||||||
},
|
},
|
||||||
apijson.UnionVariant{
|
apijson.UnionVariant{
|
||||||
TypeFilter: gjson.JSON,
|
TypeFilter: gjson.JSON,
|
||||||
Type: reflect.TypeOf(StepFinishPart{}),
|
Type: reflect.TypeOf(StepFinishPart{}),
|
||||||
|
DiscriminatorValue: "step-finish",
|
||||||
},
|
},
|
||||||
apijson.UnionVariant{
|
apijson.UnionVariant{
|
||||||
TypeFilter: gjson.JSON,
|
TypeFilter: gjson.JSON,
|
||||||
Type: reflect.TypeOf(PartObject{}),
|
Type: reflect.TypeOf(SnapshotPart{}),
|
||||||
|
DiscriminatorValue: "snapshot",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
type PartObject struct {
|
|
||||||
ID string `json:"id,required"`
|
|
||||||
MessageID string `json:"messageID,required"`
|
|
||||||
SessionID string `json:"sessionID,required"`
|
|
||||||
Snapshot string `json:"snapshot,required"`
|
|
||||||
Type PartObjectType `json:"type,required"`
|
|
||||||
JSON partObjectJSON `json:"-"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// partObjectJSON contains the JSON metadata for the struct [PartObject]
|
|
||||||
type partObjectJSON struct {
|
|
||||||
ID apijson.Field
|
|
||||||
MessageID apijson.Field
|
|
||||||
SessionID apijson.Field
|
|
||||||
Snapshot apijson.Field
|
|
||||||
Type apijson.Field
|
|
||||||
raw string
|
|
||||||
ExtraFields map[string]apijson.Field
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *PartObject) UnmarshalJSON(data []byte) (err error) {
|
|
||||||
return apijson.UnmarshalRoot(data, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r partObjectJSON) RawJSON() string {
|
|
||||||
return r.raw
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r PartObject) implementsPart() {}
|
|
||||||
|
|
||||||
type PartObjectType string
|
|
||||||
|
|
||||||
const (
|
|
||||||
PartObjectTypeSnapshot PartObjectType = "snapshot"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (r PartObjectType) IsKnown() bool {
|
|
||||||
switch r {
|
|
||||||
case PartObjectTypeSnapshot:
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
type PartType string
|
type PartType string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -862,6 +824,50 @@ func (r sessionShareJSON) RawJSON() string {
|
|||||||
return r.raw
|
return r.raw
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SnapshotPart struct {
|
||||||
|
ID string `json:"id,required"`
|
||||||
|
MessageID string `json:"messageID,required"`
|
||||||
|
SessionID string `json:"sessionID,required"`
|
||||||
|
Snapshot string `json:"snapshot,required"`
|
||||||
|
Type SnapshotPartType `json:"type,required"`
|
||||||
|
JSON snapshotPartJSON `json:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// snapshotPartJSON contains the JSON metadata for the struct [SnapshotPart]
|
||||||
|
type snapshotPartJSON struct {
|
||||||
|
ID apijson.Field
|
||||||
|
MessageID apijson.Field
|
||||||
|
SessionID apijson.Field
|
||||||
|
Snapshot apijson.Field
|
||||||
|
Type apijson.Field
|
||||||
|
raw string
|
||||||
|
ExtraFields map[string]apijson.Field
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SnapshotPart) UnmarshalJSON(data []byte) (err error) {
|
||||||
|
return apijson.UnmarshalRoot(data, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r snapshotPartJSON) RawJSON() string {
|
||||||
|
return r.raw
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r SnapshotPart) implementsPart() {}
|
||||||
|
|
||||||
|
type SnapshotPartType string
|
||||||
|
|
||||||
|
const (
|
||||||
|
SnapshotPartTypeSnapshot SnapshotPartType = "snapshot"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (r SnapshotPartType) IsKnown() bool {
|
||||||
|
switch r {
|
||||||
|
case SnapshotPartTypeSnapshot:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
type StepFinishPart struct {
|
type StepFinishPart struct {
|
||||||
ID string `json:"id,required"`
|
ID string `json:"id,required"`
|
||||||
Cost float64 `json:"cost,required"`
|
Cost float64 `json:"cost,required"`
|
||||||
|
|||||||
@@ -23,13 +23,10 @@ func TestUsage(t *testing.T) {
|
|||||||
client := opencode.NewClient(
|
client := opencode.NewClient(
|
||||||
option.WithBaseURL(baseURL),
|
option.WithBaseURL(baseURL),
|
||||||
)
|
)
|
||||||
stream := client.Event.ListStreaming(context.TODO())
|
sessions, err := client.Session.List(context.TODO())
|
||||||
for stream.Next() {
|
|
||||||
t.Logf("%+v\n", stream.Current())
|
|
||||||
}
|
|
||||||
err := stream.Err()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error(err)
|
t.Error(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
t.Logf("%+v\n", sessions)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ export default defineConfig({
|
|||||||
solidJs(),
|
solidJs(),
|
||||||
starlight({
|
starlight({
|
||||||
title: "opencode",
|
title: "opencode",
|
||||||
|
lastUpdated: true,
|
||||||
expressiveCode: { themes: ["github-light", "github-dark"] },
|
expressiveCode: { themes: ["github-light", "github-dark"] },
|
||||||
social: [
|
social: [
|
||||||
{ icon: "github", label: "GitHub", href: config.github },
|
{ icon: "github", label: "GitHub", href: config.github },
|
||||||
|
|||||||
@@ -27,6 +27,7 @@
|
|||||||
"marked": "15.0.12",
|
"marked": "15.0.12",
|
||||||
"marked-shiki": "1.2.0",
|
"marked-shiki": "1.2.0",
|
||||||
"rehype-autolink-headings": "7.1.0",
|
"rehype-autolink-headings": "7.1.0",
|
||||||
|
"remeda": "2.26.0",
|
||||||
"sharp": "0.32.5",
|
"sharp": "0.32.5",
|
||||||
"shiki": "3.4.2",
|
"shiki": "3.4.2",
|
||||||
"solid-js": "1.9.7",
|
"solid-js": "1.9.7",
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 540 KiB After Width: | Height: | Size: 592 KiB |
@@ -1,6 +1,7 @@
|
|||||||
import { For, Show, onMount, Suspense, onCleanup, createMemo, createSignal, SuspenseList, createEffect } from "solid-js"
|
import { For, Show, onMount, Suspense, onCleanup, createMemo, createSignal, SuspenseList, createEffect } from "solid-js"
|
||||||
import { DateTime } from "luxon"
|
import { DateTime } from "luxon"
|
||||||
import { createStore, reconcile, unwrap } from "solid-js/store"
|
import { createStore, reconcile, unwrap } from "solid-js/store"
|
||||||
|
import { mapValues } from "remeda"
|
||||||
import { IconArrowDown } from "./icons"
|
import { IconArrowDown } from "./icons"
|
||||||
import { IconOpencode } from "./icons/custom"
|
import { IconOpencode } from "./icons/custom"
|
||||||
import styles from "./share.module.css"
|
import styles from "./share.module.css"
|
||||||
@@ -60,7 +61,7 @@ export default function Share(props: {
|
|||||||
const [store, setStore] = createStore<{
|
const [store, setStore] = createStore<{
|
||||||
info?: Session.Info
|
info?: Session.Info
|
||||||
messages: Record<string, MessageWithParts>
|
messages: Record<string, MessageWithParts>
|
||||||
}>({ info: props.info, messages: props.messages })
|
}>({ info: props.info, messages: mapValues(props.messages, (x: any) => "metadata" in x ? fromV1(x) : x) })
|
||||||
const messages = createMemo(() => Object.values(store.messages).toSorted((a, b) => a.id?.localeCompare(b.id)))
|
const messages = createMemo(() => Object.values(store.messages).toSorted((a, b) => a.id?.localeCompare(b.id)))
|
||||||
const [connectionStatus, setConnectionStatus] = createSignal<[Status, string?]>(["disconnected", "Disconnected"])
|
const [connectionStatus, setConnectionStatus] = createSignal<[Status, string?]>(["disconnected", "Disconnected"])
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
@@ -340,6 +341,7 @@ export default function Share(props: {
|
|||||||
const filteredParts = createMemo(() =>
|
const filteredParts = createMemo(() =>
|
||||||
msg.parts.filter((x, index) => {
|
msg.parts.filter((x, index) => {
|
||||||
if (x.type === "step-start" && index > 0) return false
|
if (x.type === "step-start" && index > 0) return false
|
||||||
|
if (x.type === "snapshot") return false
|
||||||
if (x.type === "step-finish") return false
|
if (x.type === "step-finish") return false
|
||||||
if (x.type === "text" && x.synthetic === true) return false
|
if (x.type === "text" && x.synthetic === true) return false
|
||||||
if (x.type === "tool" && x.tool === "todoread") return false
|
if (x.type === "tool" && x.tool === "todoread") return false
|
||||||
|
|||||||
@@ -58,3 +58,11 @@ export function IconMeta(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
|||||||
</svg>
|
</svg>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// https://icones.js.org/collection/ri?s=robot&icon=ri:robot-2-line
|
||||||
|
export function IconRobot(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
||||||
|
return (
|
||||||
|
<svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path fill="currentColor" d="M13.5 2c0 .444-.193.843-.5 1.118V5h5a3 3 0 0 1 3 3v10a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3h5V3.118A1.5 1.5 0 1 1 13.5 2M6 7a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8a1 1 0 0 0-1-1zm-4 3H0v6h2zm20 0h2v6h-2zM9 14.5a1.5 1.5 0 1 0 0-3a1.5 1.5 0 0 0 0 3m6 0a1.5 1.5 0 1 0 0-3a1.5 1.5 0 0 0 0 3" /></svg>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { codeToHtml } from "shiki"
|
import { codeToHtml, bundledLanguages } from "shiki"
|
||||||
import { createResource, Suspense } from "solid-js"
|
import { createResource, Suspense } from "solid-js"
|
||||||
import { transformerNotationDiff } from "@shikijs/transformers"
|
import { transformerNotationDiff } from "@shikijs/transformers"
|
||||||
import style from "./content-code.module.css"
|
import style from "./content-code.module.css"
|
||||||
@@ -15,7 +15,7 @@ export function ContentCode(props: Props) {
|
|||||||
// TODO: For testing delays
|
// TODO: For testing delays
|
||||||
// await new Promise((resolve) => setTimeout(resolve, 3000))
|
// await new Promise((resolve) => setTimeout(resolve, 3000))
|
||||||
return (await codeToHtml(code || "", {
|
return (await codeToHtml(code || "", {
|
||||||
lang: lang || "text",
|
lang: lang && lang in bundledLanguages ? lang : "text",
|
||||||
themes: {
|
themes: {
|
||||||
light: "github-light",
|
light: "github-light",
|
||||||
dark: "github-dark",
|
dark: "github-dark",
|
||||||
|
|||||||
@@ -23,6 +23,20 @@
|
|||||||
grid-template-columns: 1fr 1fr;
|
grid-template-columns: 1fr 1fr;
|
||||||
align-items: stretch;
|
align-items: stretch;
|
||||||
|
|
||||||
|
&:first-child {
|
||||||
|
[data-slot="before"],
|
||||||
|
[data-slot="after"] {
|
||||||
|
padding-top: 0.25rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&:last-child {
|
||||||
|
[data-slot="before"],
|
||||||
|
[data-slot="after"] {
|
||||||
|
padding-bottom: 0.25rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[data-slot="before"],
|
[data-slot="before"],
|
||||||
[data-slot="after"] {
|
[data-slot="after"] {
|
||||||
position: relative;
|
position: relative;
|
||||||
@@ -75,46 +89,16 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* .diff > .row:first-child [data-section="cell"]:first-child { */
|
|
||||||
/* padding-top: 0.5rem; */
|
|
||||||
/* } */
|
|
||||||
/**/
|
|
||||||
/* .diff > .row:last-child [data-section="cell"]:last-child { */
|
|
||||||
/* padding-bottom: 0.5rem; */
|
|
||||||
/* } */
|
|
||||||
/**/
|
|
||||||
/* [data-section="cell"] { */
|
|
||||||
/* position: relative; */
|
|
||||||
/* flex: 1; */
|
|
||||||
/* display: flex; */
|
|
||||||
/* flex-direction: column; */
|
|
||||||
/**/
|
|
||||||
/* width: 100%; */
|
|
||||||
/* padding: 0.1875rem 0.5rem 0.1875rem 2.2ch; */
|
|
||||||
/* margin: 0; */
|
|
||||||
/**/
|
|
||||||
/* &[data-display-mobile="true"] { */
|
|
||||||
/* display: none; */
|
|
||||||
/* } */
|
|
||||||
/**/
|
|
||||||
/* pre { */
|
|
||||||
/* --shiki-dark-bg: var(--sl-color-bg-surface) !important; */
|
|
||||||
/* background-color: var(--sl-color-bg-surface) !important; */
|
|
||||||
/**/
|
|
||||||
/* white-space: pre-wrap; */
|
|
||||||
/* word-break: break-word; */
|
|
||||||
/**/
|
|
||||||
/* code > span:empty::before { */
|
|
||||||
/* content: "\00a0"; */
|
|
||||||
/* white-space: pre; */
|
|
||||||
/* display: inline-block; */
|
|
||||||
/* width: 0; */
|
|
||||||
/* } */
|
|
||||||
/* } */
|
|
||||||
/* } */
|
|
||||||
|
|
||||||
[data-component="mobile"] {
|
[data-component="mobile"] {
|
||||||
|
|
||||||
|
& > [data-component="diff-block"]:first-child > div {
|
||||||
|
padding-top: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
& > [data-component="diff-block"]:last-child > div {
|
||||||
|
padding-bottom: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
& > [data-component="diff-block"] > div {
|
& > [data-component="diff-block"] > div {
|
||||||
padding: 0 1rem 0 2.2ch;
|
padding: 0 1rem 0 2.2ch;
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { type Component, createMemo } from "solid-js"
|
|
||||||
import { parsePatch } from "diff"
|
import { parsePatch } from "diff"
|
||||||
|
import { createMemo } from "solid-js"
|
||||||
import { ContentCode } from "./content-code"
|
import { ContentCode } from "./content-code"
|
||||||
import styles from "./content-diff.module.css"
|
import styles from "./content-diff.module.css"
|
||||||
|
|
||||||
@@ -90,8 +90,8 @@ export function ContentDiff(props: Props) {
|
|||||||
i++
|
i++
|
||||||
} else if (prefix === " ") {
|
} else if (prefix === " ") {
|
||||||
diffRows.push({
|
diffRows.push({
|
||||||
left: content,
|
left: content === "" ? " " : content,
|
||||||
right: content,
|
right: content === "" ? " " : content,
|
||||||
type: "unchanged",
|
type: "unchanged",
|
||||||
})
|
})
|
||||||
i++
|
i++
|
||||||
|
|||||||
@@ -1,21 +1,13 @@
|
|||||||
.root {
|
.root {
|
||||||
border: 1px solid var(--sl-color-blue-high);
|
|
||||||
padding: 0.5rem calc(0.5rem + 3px);
|
|
||||||
border-radius: 0.25rem;
|
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
align-self: flex-start;
|
|
||||||
|
|
||||||
&[data-highlight="true"] {
|
|
||||||
background-color: var(--sl-color-blue-low);
|
|
||||||
}
|
|
||||||
|
|
||||||
[data-slot="expand-button"] {
|
[data-slot="expand-button"] {
|
||||||
flex: 0 0 auto;
|
flex: 0 0 auto;
|
||||||
padding: 2px 0;
|
padding: 2px 0;
|
||||||
font-size: 0.75rem;
|
font-size: 0.857em;
|
||||||
}
|
}
|
||||||
|
|
||||||
[data-slot="markdown"] {
|
[data-slot="markdown"] {
|
||||||
@@ -29,7 +21,7 @@
|
|||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
font-size: 0.875rem;
|
font-size: 1em;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
|
|
||||||
p,
|
p,
|
||||||
@@ -61,7 +53,7 @@
|
|||||||
h4,
|
h4,
|
||||||
h5,
|
h5,
|
||||||
h6 {
|
h6 {
|
||||||
font-size: 0.875rem;
|
font-size: 1em;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
margin-bottom: 0.5rem;
|
margin-bottom: 0.5rem;
|
||||||
}
|
}
|
||||||
@@ -75,7 +67,7 @@
|
|||||||
background-color: var(--sl-color-bg-surface) !important;
|
background-color: var(--sl-color-bg-surface) !important;
|
||||||
padding: 0.5rem 0.75rem;
|
padding: 0.5rem 0.75rem;
|
||||||
line-height: 1.6;
|
line-height: 1.6;
|
||||||
font-size: 0.75rem;
|
font-size: 0.857em;
|
||||||
white-space: pre-wrap;
|
white-space: pre-wrap;
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import style from "./content-markdown.module.css"
|
|
||||||
import { createResource, createSignal } from "solid-js"
|
|
||||||
import { createOverflow } from "./common"
|
|
||||||
import { transformerNotationDiff } from "@shikijs/transformers"
|
|
||||||
import { marked } from "marked"
|
import { marked } from "marked"
|
||||||
import markedShiki from "marked-shiki"
|
|
||||||
import { codeToHtml } from "shiki"
|
import { codeToHtml } from "shiki"
|
||||||
|
import markedShiki from "marked-shiki"
|
||||||
|
import { createOverflow } from "./common"
|
||||||
|
import { CopyButton } from "./copy-button"
|
||||||
|
import { createResource, createSignal } from "solid-js"
|
||||||
|
import { transformerNotationDiff } from "@shikijs/transformers"
|
||||||
|
import style from "./content-markdown.module.css"
|
||||||
|
|
||||||
const markedWithShiki = marked.use(
|
const markedWithShiki = marked.use(
|
||||||
markedShiki({
|
markedShiki({
|
||||||
@@ -54,6 +55,7 @@ export function ContentMarkdown(props: Props) {
|
|||||||
{expanded() ? "Show less" : "Show more"}
|
{expanded() ? "Show less" : "Show more"}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
<CopyButton text={props.text} />
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
color: var(--sl-color-text);
|
color: var(--sl-color-text);
|
||||||
background-color: var(--sl-color-bg-surface);
|
background-color: var(--sl-color-bg-surface);
|
||||||
padding: 0.5rem calc(0.5rem + 3px);
|
padding: 0.5rem calc(0.5rem + 3px);
|
||||||
|
padding-right: calc(1rem + 18px);
|
||||||
border-radius: 0.25rem;
|
border-radius: 0.25rem;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
.root {
|
||||||
|
position: absolute;
|
||||||
|
opacity: 0;
|
||||||
|
visibility: hidden;
|
||||||
|
transition: opacity 0.15s ease;
|
||||||
|
|
||||||
|
button {
|
||||||
|
cursor: pointer;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
padding: 0.125rem;
|
||||||
|
background-color: var(--sl-color-bg);
|
||||||
|
color: var(--sl-color-text-secondary);
|
||||||
|
|
||||||
|
svg {
|
||||||
|
display: block;
|
||||||
|
width: 1rem;
|
||||||
|
height: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&[data-copied="true"] {
|
||||||
|
color: var(--sl-color-green-high);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Show copy button when parent is hovered */
|
||||||
|
*:hover > .root {
|
||||||
|
opacity: 1;
|
||||||
|
visibility: visible;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { createSignal } from "solid-js"
|
||||||
|
import { IconClipboard, IconCheckCircle } from "../icons"
|
||||||
|
import styles from "./copy-button.module.css"
|
||||||
|
|
||||||
|
interface CopyButtonProps {
|
||||||
|
text: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CopyButton(props: CopyButtonProps) {
|
||||||
|
const [copied, setCopied] = createSignal(false)
|
||||||
|
|
||||||
|
function handleCopyClick() {
|
||||||
|
if (props.text) {
|
||||||
|
navigator.clipboard.writeText(props.text)
|
||||||
|
.catch((err) => console.error("Copy failed", err))
|
||||||
|
|
||||||
|
setCopied(true)
|
||||||
|
setTimeout(() => setCopied(false), 2000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div data-component="copy-button" class={styles.root}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleCopyClick}
|
||||||
|
data-copied={copied() ? true : undefined}
|
||||||
|
>
|
||||||
|
{copied()
|
||||||
|
? <IconCheckCircle width={16} height={16} />
|
||||||
|
: <IconClipboard width={16} height={16} />
|
||||||
|
}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -103,7 +103,7 @@
|
|||||||
[data-component="content"] {
|
[data-component="content"] {
|
||||||
flex: 1 1 auto;
|
flex: 1 1 auto;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
padding: 0 0 0.375rem;
|
padding: 0 0 1rem;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
@@ -135,6 +135,20 @@
|
|||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
flex-grow: 1;
|
flex-grow: 1;
|
||||||
max-width: var(--md-tool-width);
|
max-width: var(--md-tool-width);
|
||||||
|
|
||||||
|
& > [data-component="assistant-text-markdown"] {
|
||||||
|
align-self: flex-start;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
border: 1px solid var(--sl-color-blue-high);
|
||||||
|
padding: 0.5rem calc(0.5rem + 3px);
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
position: relative;
|
||||||
|
|
||||||
|
[data-component="copy-button"] {
|
||||||
|
top: 0.5rem;
|
||||||
|
right: calc(0.5rem - 1px);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
[data-component="step-start"] {
|
[data-component="step-start"] {
|
||||||
@@ -142,7 +156,6 @@
|
|||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
gap: 0.375rem;
|
gap: 0.375rem;
|
||||||
padding-bottom: 1rem;
|
|
||||||
|
|
||||||
[data-slot="provider"] {
|
[data-slot="provider"] {
|
||||||
line-height: 18px;
|
line-height: 18px;
|
||||||
@@ -237,6 +250,32 @@
|
|||||||
&[data-tool="edit"] {
|
&[data-tool="edit"] {
|
||||||
[data-component="tool-result"] {
|
[data-component="tool-result"] {
|
||||||
max-width: var(--lg-tool-width);
|
max-width: var(--lg-tool-width);
|
||||||
|
align-items: stretch;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
&[data-tool="task"] {
|
||||||
|
[data-component="tool-input"] {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
max-width: var(--md-tool-width);
|
||||||
|
display: -webkit-box;
|
||||||
|
-webkit-line-clamp: 3;
|
||||||
|
-webkit-box-orient: vertical;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
[data-component="tool-output"] {
|
||||||
|
max-width: var(--sm-tool-width);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
border: 1px solid var(--sl-color-divider);
|
||||||
|
padding: 0.5rem calc(0.5rem + 3px);
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
position: relative;
|
||||||
|
|
||||||
|
[data-component="copy-button"] {
|
||||||
|
top: 0.5rem;
|
||||||
|
right: calc(0.5rem - 1px);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,25 +19,25 @@ import {
|
|||||||
IconMagnifyingGlass,
|
IconMagnifyingGlass,
|
||||||
IconDocumentMagnifyingGlass,
|
IconDocumentMagnifyingGlass,
|
||||||
} from "../icons"
|
} from "../icons"
|
||||||
import { IconMeta, IconOpenAI, IconGemini, IconAnthropic } from "../icons/custom"
|
import { IconMeta, IconRobot, IconOpenAI, IconGemini, IconAnthropic } from "../icons/custom"
|
||||||
import { formatDuration } from "../share/common"
|
|
||||||
import { ContentCode } from "./content-code"
|
import { ContentCode } from "./content-code"
|
||||||
import { ContentDiff } from "./content-diff"
|
import { ContentDiff } from "./content-diff"
|
||||||
import { ContentText } from "./content-text"
|
import { ContentText } from "./content-text"
|
||||||
import { ContentError } from "./content-error"
|
|
||||||
import { ContentMarkdown } from "./content-markdown"
|
|
||||||
import { ContentBash } from "./content-bash"
|
import { ContentBash } from "./content-bash"
|
||||||
|
import { ContentError } from "./content-error"
|
||||||
|
import { formatDuration } from "../share/common"
|
||||||
|
import { ContentMarkdown } from "./content-markdown"
|
||||||
import type { MessageV2 } from "opencode/session/message-v2"
|
import type { MessageV2 } from "opencode/session/message-v2"
|
||||||
import type { Diagnostic } from "vscode-languageserver-types"
|
import type { Diagnostic } from "vscode-languageserver-types"
|
||||||
|
|
||||||
import styles from "./part.module.css"
|
import styles from "./part.module.css"
|
||||||
|
|
||||||
const MIN_DURATION = 2
|
const MIN_DURATION = 2000
|
||||||
|
|
||||||
export interface PartProps {
|
export interface PartProps {
|
||||||
index: number
|
index: number
|
||||||
message: MessageV2.Info
|
message: MessageV2.Info
|
||||||
part: MessageV2.AssistantPart | MessageV2.UserPart
|
part: MessageV2.Part
|
||||||
last: boolean
|
last: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,7 +114,7 @@ export function Part(props: PartProps) {
|
|||||||
<IconGlobeAlt width={18} height={18} />
|
<IconGlobeAlt width={18} height={18} />
|
||||||
</Match>
|
</Match>
|
||||||
<Match when={props.part.type === "tool" && props.part.tool === "task"}>
|
<Match when={props.part.type === "tool" && props.part.tool === "task"}>
|
||||||
<IconRectangleStack width={18} height={18} />
|
<IconRobot width={18} height={18} />
|
||||||
</Match>
|
</Match>
|
||||||
<Match when={true}>
|
<Match when={true}>
|
||||||
<IconSparkles width={18} height={18} />
|
<IconSparkles width={18} height={18} />
|
||||||
@@ -131,12 +131,13 @@ export function Part(props: PartProps) {
|
|||||||
{props.message.role === "user" && props.part.type === "text" && (
|
{props.message.role === "user" && props.part.type === "text" && (
|
||||||
<div data-component="user-text">
|
<div data-component="user-text">
|
||||||
<ContentText text={props.part.text} expand={props.last} />
|
<ContentText text={props.part.text} expand={props.last} />
|
||||||
<Spacer />
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{props.message.role === "assistant" && props.part.type === "text" && (
|
{props.message.role === "assistant" && props.part.type === "text" && (
|
||||||
<div data-component="assistant-text">
|
<div data-component="assistant-text">
|
||||||
<ContentMarkdown expand={props.last} text={props.part.text} />
|
<div data-component="assistant-text-markdown">
|
||||||
|
<ContentMarkdown expand={props.last} text={props.part.text} />
|
||||||
|
</div>
|
||||||
{props.last && props.message.role === "assistant" && props.message.time.completed && (
|
{props.last && props.message.role === "assistant" && props.message.time.completed && (
|
||||||
<Footer
|
<Footer
|
||||||
title={DateTime.fromMillis(props.message.time.completed).toLocaleString(
|
title={DateTime.fromMillis(props.message.time.completed).toLocaleString(
|
||||||
@@ -146,7 +147,6 @@ export function Part(props: PartProps) {
|
|||||||
{DateTime.fromMillis(props.message.time.completed).toLocaleString(DateTime.DATETIME_MED)}
|
{DateTime.fromMillis(props.message.time.completed).toLocaleString(DateTime.DATETIME_MED)}
|
||||||
</Footer>
|
</Footer>
|
||||||
)}
|
)}
|
||||||
<Spacer />
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{props.message.role === "user" && props.part.type === "file" && (
|
{props.message.role === "user" && props.part.type === "file" && (
|
||||||
@@ -245,6 +245,14 @@ export function Part(props: PartProps) {
|
|||||||
state={props.part.state}
|
state={props.part.state}
|
||||||
/>
|
/>
|
||||||
</Match>
|
</Match>
|
||||||
|
<Match when={props.part.tool === "task"}>
|
||||||
|
<TaskTool
|
||||||
|
id={props.part.id}
|
||||||
|
tool={props.part.tool}
|
||||||
|
message={props.message}
|
||||||
|
state={props.part.state}
|
||||||
|
/>
|
||||||
|
</Match>
|
||||||
<Match when={true}>
|
<Match when={true}>
|
||||||
<FallbackTool
|
<FallbackTool
|
||||||
message={props.message}
|
message={props.message}
|
||||||
@@ -256,11 +264,10 @@ export function Part(props: PartProps) {
|
|||||||
</Switch>
|
</Switch>
|
||||||
</div>
|
</div>
|
||||||
<ToolFooter
|
<ToolFooter
|
||||||
time={
|
time={DateTime.fromMillis(props.part.state.time.end)
|
||||||
DateTime.fromMillis(props.part.state.time.start)
|
.diff(DateTime.fromMillis(props.part.state.time.start))
|
||||||
.diff(DateTime.fromMillis(props.part.state.time.end))
|
.toMillis()}
|
||||||
.toMillis()
|
/>
|
||||||
} />
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -636,12 +643,25 @@ function Footer(props: ParentProps<{ title: string }>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function ToolFooter(props: { time: number }) {
|
function ToolFooter(props: { time: number }) {
|
||||||
return props.time > MIN_DURATION ? (
|
return props.time > MIN_DURATION && <Footer title={`${props.time}ms`}>{formatDuration(props.time)}</Footer>
|
||||||
<Footer title={`${props.time}ms`}>
|
}
|
||||||
{formatDuration(props.time)}
|
|
||||||
</Footer>
|
function TaskTool(props: ToolProps) {
|
||||||
) : (
|
return (
|
||||||
<Spacer />
|
<>
|
||||||
|
<div data-component="tool-title">
|
||||||
|
<span data-slot="name">Task</span>
|
||||||
|
<span data-slot="target">{props.state.input.description}</span>
|
||||||
|
</div>
|
||||||
|
<div data-component="tool-input">
|
||||||
|
“{props.state.input.prompt}”
|
||||||
|
</div>
|
||||||
|
<ResultsButton showCopy="Show output" hideCopy="Hide output">
|
||||||
|
<div data-component="tool-output">
|
||||||
|
<ContentMarkdown expand text={props.state.output} />
|
||||||
|
</div>
|
||||||
|
</ResultsButton>
|
||||||
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,12 +5,11 @@ description: Using the opencode JSON config.
|
|||||||
|
|
||||||
You can configure opencode using a JSON config file.
|
You can configure opencode using a JSON config file.
|
||||||
|
|
||||||
```json title="opencode config"
|
```json title="opencode.json"
|
||||||
{
|
{
|
||||||
"$schema": "https://opencode.ai/config.json",
|
"$schema": "https://opencode.ai/config.json",
|
||||||
"theme": "opencode",
|
"theme": "opencode",
|
||||||
"model": "anthropic/claude-sonnet-4-20250514",
|
"model": "anthropic/claude-sonnet-4-20250514",
|
||||||
"autoshare": false,
|
|
||||||
"autoupdate": true
|
"autoupdate": true
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -93,6 +92,24 @@ You can configure the theme you want to use in your opencode config through the
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### Layout
|
||||||
|
|
||||||
|
You can configure the layout of the TUI with the `layout` option.
|
||||||
|
|
||||||
|
```json title="opencode.json"
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"layout": "stretch"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This takes:
|
||||||
|
|
||||||
|
- `"auto"`: Centers content with padding. This is the default.
|
||||||
|
- `"stretch"`: Uses full terminal width.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### Logging
|
### Logging
|
||||||
|
|
||||||
Logs are written to:
|
Logs are written to:
|
||||||
@@ -118,8 +135,28 @@ With the following options:
|
|||||||
| `WARN` | Warnings and errors only |
|
| `WARN` | Warnings and errors only |
|
||||||
| `ERROR` | Errors only |
|
| `ERROR` | Errors only |
|
||||||
|
|
||||||
The **default** log level is `INFO`. If you are running opencode locally in
|
The **default** log level is `INFO`. If you are running opencode locally in development mode it's set to `DEBUG`.
|
||||||
development mode it's set to `DEBUG`.
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Sharing
|
||||||
|
|
||||||
|
You can configure the [share](/docs/share) feature through the `share` option.
|
||||||
|
|
||||||
|
```json title="opencode.json"
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"share": "manual"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This takes:
|
||||||
|
|
||||||
|
- `"manual"` - Allow manual sharing via commands (default)
|
||||||
|
- `"auto"` - Automatically share new conversations
|
||||||
|
- `"disabled"` - Disable sharing entirely
|
||||||
|
|
||||||
|
By default, sharing is set to manual mode where you need to explicitly share conversations using the `/share` command.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -138,6 +175,19 @@ You can customize your keybinds through the `keybinds` option.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### Autoupdate
|
||||||
|
|
||||||
|
opencode will automatically download any new updates when it starts up. You can disable this with the `autoupdate` option.
|
||||||
|
|
||||||
|
```json title="opencode.json"
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"autoupdate": false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### MCP servers
|
### MCP servers
|
||||||
|
|
||||||
You can configure MCP servers you want to use through the `mcp` option.
|
You can configure MCP servers you want to use through the `mcp` option.
|
||||||
@@ -153,6 +203,22 @@ You can configure MCP servers you want to use through the `mcp` option.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### Instructions
|
||||||
|
|
||||||
|
You can configure the instructions for the model you're using through the `instructions` option.
|
||||||
|
|
||||||
|
```json title="opencode.json"
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This takes an array of paths and glob patterns to instruction files. [Learn more
|
||||||
|
about rules here](/docs/rules).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
### Disabled providers
|
### Disabled providers
|
||||||
|
|
||||||
You can disable providers that are loaded automatically through the `disabled_providers` option. This is useful when you want to prevent certain providers from being loaded even if their credentials are available.
|
You can disable providers that are loaded automatically through the `disabled_providers` option. This is useful when you want to prevent certain providers from being loaded even if their credentials are available.
|
||||||
@@ -188,7 +254,9 @@ Use `{env:VARIABLE_NAME}` to substitute environment variables:
|
|||||||
"model": "{env:OPENCODE_MODEL}",
|
"model": "{env:OPENCODE_MODEL}",
|
||||||
"provider": {
|
"provider": {
|
||||||
"anthropic": {
|
"anthropic": {
|
||||||
"api_key": "{env:ANTHROPIC_API_KEY}"
|
"options": {
|
||||||
|
"apiKey": "{env:ANTHROPIC_API_KEY}"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -208,7 +276,9 @@ Use `{file:path/to/file}` to substitute the contents of a file:
|
|||||||
"instructions": ["{file:./custom-instructions.md}"],
|
"instructions": ["{file:./custom-instructions.md}"],
|
||||||
"provider": {
|
"provider": {
|
||||||
"openai": {
|
"openai": {
|
||||||
"api_key": "{file:~/.secrets/openai-key}"
|
"options": {
|
||||||
|
"apiKey": "{file:~/.secrets/openai-key}"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ Since opencode is open source and does not store any of your code or context dat
|
|||||||
|
|
||||||
**opencode does not store your code or context data.** All processing happens locally or through direct API calls to your AI provider.
|
**opencode does not store your code or context data.** All processing happens locally or through direct API calls to your AI provider.
|
||||||
|
|
||||||
The only caveat here is the optional `/share` feature that must be manually enabled.
|
The only caveat here is the optional `/share` feature.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -33,6 +33,17 @@ If a user enables the `/share` feature, the conversation and the data associated
|
|||||||
|
|
||||||
The data is currently served through our CDN's edge network, and is cached on the edge near your users.
|
The data is currently served through our CDN's edge network, and is cached on the edge near your users.
|
||||||
|
|
||||||
|
We recommend you disable this for your trial.
|
||||||
|
|
||||||
|
```json title="opencode.json"
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"share": "disabled"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
[Learn more about sharing](/docs/share).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Code ownership
|
### Code ownership
|
||||||
@@ -51,9 +62,37 @@ pricing and implementation options.
|
|||||||
|
|
||||||
### SSO
|
### SSO
|
||||||
|
|
||||||
SSO integration can be implemented for enterprise deployments after your trial. Currently users manage and configure individual API keys locally.
|
SSO integration can be implemented for enterprise deployments after your trial.
|
||||||
|
This will allow your team's session data and shared conversations to be protected
|
||||||
|
by your enterprise's authentication system.
|
||||||
|
|
||||||
This can be switched to a centralized authentication system that your organization uses.
|
---
|
||||||
|
|
||||||
|
### Private NPM
|
||||||
|
|
||||||
|
opencode supports private npm registries through Bun's native `.npmrc` file support. If your organization uses a private registry, such as JFrog Artifactory, Nexus, or similar, ensure developers are authenticated before running opencode.
|
||||||
|
|
||||||
|
To set up authentication with your private registry:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm login --registry=https://your-company.jfrog.io/api/npm/npm-virtual/
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates `~/.npmrc` with authentication details. opencode will automatically
|
||||||
|
pick this up.
|
||||||
|
|
||||||
|
:::caution
|
||||||
|
You must be logged into the private registry before running opencode.
|
||||||
|
:::
|
||||||
|
|
||||||
|
Alternatively, you can manually configure a `.npmrc` file:
|
||||||
|
|
||||||
|
```bash title="~/.npmrc"
|
||||||
|
registry=https://your-company.jfrog.io/api/npm/npm-virtual/
|
||||||
|
//your-company.jfrog.io/api/npm/npm-virtual/:_authToken=${NPM_AUTH_TOKEN}
|
||||||
|
```
|
||||||
|
|
||||||
|
Developers must be logged into the private registry before running opencode to ensure packages can be installed from your enterprise registry.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -9,32 +9,45 @@ opencode has a list of keybinds that you can customize through the opencode conf
|
|||||||
{
|
{
|
||||||
"$schema": "https://opencode.ai/config.json",
|
"$schema": "https://opencode.ai/config.json",
|
||||||
"keybinds": {
|
"keybinds": {
|
||||||
|
|
||||||
"leader": "ctrl+x",
|
"leader": "ctrl+x",
|
||||||
"help": "<leader>h",
|
"app_help": "<leader>h",
|
||||||
|
"switch_mode": "tab",
|
||||||
|
|
||||||
"editor_open": "<leader>e",
|
"editor_open": "<leader>e",
|
||||||
|
|
||||||
"session_new": "<leader>n",
|
"session_new": "<leader>n",
|
||||||
"session_list": "<leader>l",
|
"session_list": "<leader>l",
|
||||||
"session_share": "<leader>s",
|
"session_share": "<leader>s",
|
||||||
|
"session_unshare": "<leader>u",
|
||||||
"session_interrupt": "esc",
|
"session_interrupt": "esc",
|
||||||
"session_compact": "<leader>c",
|
"session_compact": "<leader>c",
|
||||||
|
|
||||||
"tool_details": "<leader>d",
|
"tool_details": "<leader>d",
|
||||||
"model_list": "<leader>m",
|
"model_list": "<leader>m",
|
||||||
"theme_list": "<leader>t",
|
"theme_list": "<leader>t",
|
||||||
"project_init": "<leader>i",
|
"project_init": "<leader>i",
|
||||||
|
|
||||||
|
"file_list": "<leader>f",
|
||||||
|
"file_close": "esc",
|
||||||
|
"file_diff_toggle": "<leader>v",
|
||||||
|
|
||||||
"input_clear": "ctrl+c",
|
"input_clear": "ctrl+c",
|
||||||
"input_paste": "ctrl+v",
|
"input_paste": "ctrl+v",
|
||||||
"input_submit": "enter",
|
"input_submit": "enter",
|
||||||
"input_newline": "shift+enter,ctrl+j",
|
"input_newline": "shift+enter,ctrl+j",
|
||||||
"history_previous": "up",
|
|
||||||
"history_next": "down",
|
|
||||||
"messages_page_up": "pgup",
|
"messages_page_up": "pgup",
|
||||||
"messages_page_down": "pgdown",
|
"messages_page_down": "pgdown",
|
||||||
"messages_half_page_up": "ctrl+alt+u",
|
"messages_half_page_up": "ctrl+alt+u",
|
||||||
"messages_half_page_down": "ctrl+alt+d",
|
"messages_half_page_down": "ctrl+alt+d",
|
||||||
"messages_previous": "ctrl+alt+k",
|
"messages_previous": "ctrl+up",
|
||||||
"messages_next": "ctrl+alt+j",
|
"messages_next": "ctrl+down",
|
||||||
"messages_first": "ctrl+g",
|
"messages_first": "ctrl+g",
|
||||||
"messages_last": "ctrl+alt+g",
|
"messages_last": "ctrl+alt+g",
|
||||||
|
"messages_layout_toggle": "<leader>p",
|
||||||
|
"messages_copy": "<leader>y",
|
||||||
|
"messages_revert": "<leader>r",
|
||||||
"app_exit": "ctrl+c,<leader>q"
|
"app_exit": "ctrl+c,<leader>q"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,7 +49,10 @@ Add a remote MCP servers under `mcp.remotemcp`.
|
|||||||
"remotemcp": {
|
"remotemcp": {
|
||||||
"type": "remote",
|
"type": "remote",
|
||||||
"url": "https://my-mcp-server.com",
|
"url": "https://my-mcp-server.com",
|
||||||
"enabled": true
|
"enabled": true,
|
||||||
|
"headers": {
|
||||||
|
"Authorization": "Bearer MY_API_KEY"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,12 +27,32 @@ You can add custom providers by specifying the npm package for the provider and
|
|||||||
{
|
{
|
||||||
"$schema": "https://opencode.ai/config.json",
|
"$schema": "https://opencode.ai/config.json",
|
||||||
"provider": {
|
"provider": {
|
||||||
"openrouter": {
|
"moonshot": {
|
||||||
"name": "OpenRouter",
|
"npm": "@ai-sdk/openai-compatible",
|
||||||
|
"options": {
|
||||||
|
"baseURL": "https://api.moonshot.ai/v1"
|
||||||
|
},
|
||||||
"models": {
|
"models": {
|
||||||
"weirdo/some-weird-model": {
|
"kimi-k2-0711-preview": {}
|
||||||
"name": "Claude 3.5 Sonnet"
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Base URL
|
||||||
|
|
||||||
|
You can customize the base URL for any provider by setting the `baseURL` option. This is useful when using proxy services or custom endpoints.
|
||||||
|
|
||||||
|
```json title="opencode.json" {6}
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"provider": {
|
||||||
|
"anthropic": {
|
||||||
|
"options": {
|
||||||
|
"baseURL": "https://api.anthropic.com/v1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -44,7 +64,7 @@ You can add custom providers by specifying the npm package for the provider and
|
|||||||
### Local
|
### Local
|
||||||
|
|
||||||
You can configure local model like ones served through LM Studio or Ollama. To
|
You can configure local model like ones served through LM Studio or Ollama. To
|
||||||
do so, you'll need to specify a couple of things.
|
do so, you'll need to specify a couple of things.
|
||||||
|
|
||||||
Here's an example of configuring a local model from LM Studio:
|
Here's an example of configuring a local model from LM Studio:
|
||||||
|
|
||||||
|
|||||||
@@ -23,13 +23,13 @@ When you share a conversation, opencode:
|
|||||||
|
|
||||||
## Sharing
|
## Sharing
|
||||||
|
|
||||||
You can manually share a conversation or enable automatic sharing for all new conversations.
|
opencode supports three sharing modes that control how conversations are shared:
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Manual
|
### Manual (default)
|
||||||
|
|
||||||
Use the `/share` command in any conversation to create a shareable link:
|
By default, opencode uses manual sharing mode. Sessions are not shared automatically, but you can manually share them using the `/share` command:
|
||||||
|
|
||||||
```
|
```
|
||||||
/share
|
/share
|
||||||
@@ -37,24 +37,48 @@ Use the `/share` command in any conversation to create a shareable link:
|
|||||||
|
|
||||||
This will generate a unique URL that'll be copied to your clipboard.
|
This will generate a unique URL that'll be copied to your clipboard.
|
||||||
|
|
||||||
---
|
To explicitly set manual mode in your [config file](/docs/config):
|
||||||
|
|
||||||
### Autoshare
|
|
||||||
|
|
||||||
You can enable automatic sharing for all new conversations through the `autoshare` option in your [config file](/docs/config).
|
|
||||||
|
|
||||||
```json title="opencode.json"
|
```json title="opencode.json"
|
||||||
{
|
{
|
||||||
"$schema": "https://opencode.ai/config.json",
|
"$schema": "https://opencode.ai/config.json",
|
||||||
"autoshare": true
|
"share": "manual"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
By default, `autoshare` is disabled.
|
---
|
||||||
|
|
||||||
|
### Auto-share
|
||||||
|
|
||||||
|
You can enable automatic sharing for all new conversations by setting the `share` option to `"auto"` in your [config file](/docs/config):
|
||||||
|
|
||||||
|
```json title="opencode.json"
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"share": "auto"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
With auto-share enabled, every new conversation will automatically be shared and a link will be generated.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Unsharing
|
### Disabled
|
||||||
|
|
||||||
|
You can disable sharing entirely by setting the `share` option to `"disabled"` in your [config file](/docs/config):
|
||||||
|
|
||||||
|
```json title="opencode.json"
|
||||||
|
{
|
||||||
|
"$schema": "https://opencode.ai/config.json",
|
||||||
|
"share": "disabled"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
To enforce this across your team for a given project, add it to the `opencode.json` in your project and check into Git.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Un-sharing
|
||||||
|
|
||||||
To stop sharing a conversation and remove it from public access:
|
To stop sharing a conversation and remove it from public access:
|
||||||
|
|
||||||
@@ -85,10 +109,11 @@ includes:
|
|||||||
|
|
||||||
### Recommendations
|
### Recommendations
|
||||||
|
|
||||||
- Only share conversations that don't contain sensitive information
|
- Only share conversations that don't contain sensitive information.
|
||||||
- Review conversation content before sharing
|
- Review conversation content before sharing.
|
||||||
- Unshare conversations when collaboration is complete
|
- Unshare conversations when collaboration is complete.
|
||||||
- Avoid sharing conversations with proprietary code or confidential data
|
- Avoid sharing conversations with proprietary code or confidential data.
|
||||||
|
- For sensitive projects, disable sharing entirely.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -96,8 +121,8 @@ includes:
|
|||||||
|
|
||||||
For enterprise deployments, the share feature can be:
|
For enterprise deployments, the share feature can be:
|
||||||
|
|
||||||
- **Self-hosted** on your own infrastructure
|
|
||||||
- **Restricted** to authenticated users only
|
|
||||||
- **Disabled** entirely for security compliance
|
- **Disabled** entirely for security compliance
|
||||||
|
- **Restricted** to users authenticated through SSO only
|
||||||
|
- **Self-hosted** on your own infrastructure
|
||||||
|
|
||||||
[Learn more](/docs/enterprise) about using opencode in your organization.
|
[Learn more](/docs/enterprise) about using opencode in your organization.
|
||||||
|
|||||||
@@ -116,3 +116,28 @@ export DISPLAY=:99.0
|
|||||||
```
|
```
|
||||||
|
|
||||||
opencode will detect if you're using Wayland and prefer `wl-clipboard`, otherwise it will try to find clipboard tools in order of: `xclip` and `xsel`.
|
opencode will detect if you're using Wayland and prefer `wl-clipboard`, otherwise it will try to find clipboard tools in order of: `xclip` and `xsel`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### How to select and copy text in the TUI
|
||||||
|
|
||||||
|
There are several ways to copy text from opencode's TUI:
|
||||||
|
|
||||||
|
- **Copy latest message**: Use `<leader>y` to copy the most recent message in your current session to the clipboard
|
||||||
|
- **Export session**: Use `/export` (or `<leader>x`) to open the current session as plain text in your `$EDITOR` (requires the `EDITOR` environment variable to be set)
|
||||||
|
|
||||||
|
We're working on adding click & drag text selection in a future update.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### TUI not rendering full width
|
||||||
|
|
||||||
|
By default, opencode's TUI uses an "auto" layout that centers content with padding. If you want the TUI to use the full width of your terminal, you can configure the layout setting:
|
||||||
|
|
||||||
|
```json title="opencode.json"
|
||||||
|
{
|
||||||
|
"layout": "stretch"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Read more about this in the [config docs](/docs/config#layout).
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
diff --git a/dist/index.mjs b/dist/index.mjs
|
|
||||||
index 92a80377692488c4ba8801ce33e7736ad7055e43..add6281bbecaa1c03d3b48eb99aead4a7a7336b2 100644
|
|
||||||
--- a/dist/index.mjs
|
|
||||||
+++ b/dist/index.mjs
|
|
||||||
@@ -1593,7 +1593,7 @@ function prepareCallSettings({
|
|
||||||
return {
|
|
||||||
maxTokens,
|
|
||||||
// TODO v5 remove default 0 for temperature
|
|
||||||
- temperature: temperature != null ? temperature : 0,
|
|
||||||
+ temperature: temperature,
|
|
||||||
topP,
|
|
||||||
topK,
|
|
||||||
presencePenalty,
|
|
||||||
Executable
+16
@@ -0,0 +1,16 @@
|
|||||||
|
#!/usr/bin/env bun
|
||||||
|
|
||||||
|
import { $ } from "bun"
|
||||||
|
|
||||||
|
try {
|
||||||
|
await $`git tag -d github-v1`
|
||||||
|
await $`git push origin :refs/tags/github-v1`
|
||||||
|
} catch (e: any) {
|
||||||
|
if (e instanceof $.ShellError && e.stderr.toString().match(/tag \S+ not found/)) {
|
||||||
|
console.log("tag not found, continuing...")
|
||||||
|
} else {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await $`git tag -a github-v1 -m "Update github-v1 to latest"`
|
||||||
|
await $`git push origin github-v1`
|
||||||
@@ -23,4 +23,7 @@ rm -rf packages/tui/sdk
|
|||||||
mv opencode-go/ packages/tui/sdk/
|
mv opencode-go/ packages/tui/sdk/
|
||||||
rm -rf packages/tui/sdk/.git
|
rm -rf packages/tui/sdk/.git
|
||||||
|
|
||||||
|
echo "Kicking off production build..."
|
||||||
|
stl builds create --branch main --wait false
|
||||||
|
|
||||||
echo "Done!"
|
echo "Done!"
|
||||||
|
|||||||
+186
-234
@@ -1,341 +1,299 @@
|
|||||||
#!/usr/bin/env bun
|
#!/usr/bin/env bun
|
||||||
|
|
||||||
import os from "os";
|
import os from "os"
|
||||||
import path from "path";
|
import path from "path"
|
||||||
import { $ } from "bun";
|
import { $ } from "bun"
|
||||||
import { Octokit } from "@octokit/rest";
|
import { Octokit } from "@octokit/rest"
|
||||||
import { graphql } from "@octokit/graphql";
|
import { graphql } from "@octokit/graphql"
|
||||||
import * as core from "@actions/core";
|
import * as core from "@actions/core"
|
||||||
import * as github from "@actions/github";
|
import * as github from "@actions/github"
|
||||||
import type { IssueCommentEvent } from "@octokit/webhooks-types";
|
import type { IssueCommentEvent } from "@octokit/webhooks-types"
|
||||||
import type {
|
import type { GitHubIssue, GitHubPullRequest, IssueQueryResponse, PullRequestQueryResponse } from "./types"
|
||||||
GitHubIssue,
|
|
||||||
GitHubPullRequest,
|
|
||||||
IssueQueryResponse,
|
|
||||||
PullRequestQueryResponse,
|
|
||||||
} from "./types";
|
|
||||||
|
|
||||||
if (github.context.eventName !== "issue_comment") {
|
if (github.context.eventName !== "issue_comment") {
|
||||||
core.setFailed(`Unsupported event type: ${github.context.eventName}`);
|
core.setFailed(`Unsupported event type: ${github.context.eventName}`)
|
||||||
process.exit(1);
|
process.exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
const { owner, repo } = github.context.repo;
|
const { owner, repo } = github.context.repo
|
||||||
const payload = github.context.payload as IssueCommentEvent;
|
const payload = github.context.payload as IssueCommentEvent
|
||||||
const actor = github.context.actor;
|
const actor = github.context.actor
|
||||||
const issueId = payload.issue.number;
|
const issueId = payload.issue.number
|
||||||
const body = payload.comment.body;
|
const body = payload.comment.body
|
||||||
|
|
||||||
let appToken: string;
|
let appToken: string
|
||||||
let octoRest: Octokit;
|
let octoRest: Octokit
|
||||||
let octoGraph: typeof graphql;
|
let octoGraph: typeof graphql
|
||||||
let commentId: number;
|
let commentId: number
|
||||||
let gitCredentials: string;
|
let gitCredentials: string
|
||||||
let shareUrl: string | undefined;
|
let shareUrl: string | undefined
|
||||||
let state:
|
let state:
|
||||||
| {
|
| {
|
||||||
type: "issue";
|
type: "issue"
|
||||||
issue: GitHubIssue;
|
issue: GitHubIssue
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
type: "local-pr";
|
type: "local-pr"
|
||||||
pr: GitHubPullRequest;
|
pr: GitHubPullRequest
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
type: "fork-pr";
|
type: "fork-pr"
|
||||||
pr: GitHubPullRequest;
|
pr: GitHubPullRequest
|
||||||
};
|
}
|
||||||
|
|
||||||
async function run() {
|
async function run() {
|
||||||
try {
|
try {
|
||||||
const match = body.match(/^hey\s*opencode,?\s*(.*)$/);
|
const match = body.match(/^hey\s*opencode,?\s*(.*)$/)
|
||||||
if (!match?.[1]) throw new Error("Command must start with `hey opencode`");
|
if (!match?.[1]) throw new Error("Command must start with `hey opencode`")
|
||||||
const userPrompt = match[1];
|
const userPrompt = match[1]
|
||||||
|
|
||||||
const oidcToken = await generateGitHubToken();
|
const oidcToken = await generateGitHubToken()
|
||||||
appToken = await exchangeForAppToken(oidcToken);
|
appToken = await exchangeForAppToken(oidcToken)
|
||||||
octoRest = new Octokit({ auth: appToken });
|
octoRest = new Octokit({ auth: appToken })
|
||||||
octoGraph = graphql.defaults({
|
octoGraph = graphql.defaults({
|
||||||
headers: { authorization: `token ${appToken}` },
|
headers: { authorization: `token ${appToken}` },
|
||||||
});
|
})
|
||||||
|
|
||||||
await configureGit(appToken);
|
await configureGit(appToken)
|
||||||
await assertPermissions();
|
await assertPermissions()
|
||||||
|
|
||||||
const comment = await createComment("opencode started...");
|
const comment = await createComment("opencode started...")
|
||||||
commentId = comment.data.id;
|
commentId = comment.data.id
|
||||||
|
|
||||||
// Set state
|
// Set state
|
||||||
const repoData = await fetchRepo();
|
const repoData = await fetchRepo()
|
||||||
if (payload.issue.pull_request) {
|
if (payload.issue.pull_request) {
|
||||||
const prData = await fetchPR();
|
const prData = await fetchPR()
|
||||||
state = {
|
state = {
|
||||||
type:
|
type: prData.headRepository.nameWithOwner === prData.baseRepository.nameWithOwner ? "local-pr" : "fork-pr",
|
||||||
prData.headRepository.nameWithOwner ===
|
|
||||||
prData.baseRepository.nameWithOwner
|
|
||||||
? "local-pr"
|
|
||||||
: "fork-pr",
|
|
||||||
pr: prData,
|
pr: prData,
|
||||||
};
|
}
|
||||||
} else {
|
} else {
|
||||||
state = {
|
state = {
|
||||||
type: "issue",
|
type: "issue",
|
||||||
issue: await fetchIssue(),
|
issue: await fetchIssue(),
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Setup git branch
|
// Setup git branch
|
||||||
if (state.type === "local-pr") await checkoutLocalBranch(state.pr);
|
if (state.type === "local-pr") await checkoutLocalBranch(state.pr)
|
||||||
else if (state.type === "fork-pr") await checkoutForkBranch(state.pr);
|
else if (state.type === "fork-pr") await checkoutForkBranch(state.pr)
|
||||||
|
|
||||||
// Prompt
|
// Prompt
|
||||||
const share = process.env.INPUT_SHARE === "true" || !repoData.data.private;
|
const share = process.env.INPUT_SHARE === "true" || !repoData.data.private
|
||||||
const promptData =
|
const promptData = state.type === "issue" ? buildPromptDataForIssue(state.issue) : buildPromptDataForPR(state.pr)
|
||||||
state.type === "issue"
|
|
||||||
? buildPromptDataForIssue(state.issue)
|
|
||||||
: buildPromptDataForPR(state.pr);
|
|
||||||
const responseRet = await runOpencode(`${userPrompt}\n\n${promptData}`, {
|
const responseRet = await runOpencode(`${userPrompt}\n\n${promptData}`, {
|
||||||
share,
|
share,
|
||||||
});
|
})
|
||||||
|
|
||||||
const response = responseRet.stdout;
|
const response = responseRet.stdout
|
||||||
shareUrl = responseRet.stderr.match(/https:\/\/opencode\.ai\/s\/\w+/)?.[0];
|
shareUrl = responseRet.stderr.match(/https:\/\/opencode\.ai\/s\/\w+/)?.[0]
|
||||||
|
|
||||||
// Comment and push changes
|
// Comment and push changes
|
||||||
if (await branchIsDirty()) {
|
if (await branchIsDirty()) {
|
||||||
const summary =
|
const summary =
|
||||||
(
|
(await runOpencode(`Summarize the following in less than 40 characters:\n\n${response}`, { share: false }))
|
||||||
await runOpencode(
|
?.stdout || `Fix issue: ${payload.issue.title}`
|
||||||
`Summarize the following in less than 40 characters:\n\n${response}`,
|
|
||||||
{ share: false }
|
|
||||||
)
|
|
||||||
)?.stdout || `Fix issue: ${payload.issue.title}`;
|
|
||||||
|
|
||||||
if (state.type === "issue") {
|
if (state.type === "issue") {
|
||||||
const branch = await pushToNewBranch(summary);
|
const branch = await pushToNewBranch(summary)
|
||||||
const pr = await createPR(
|
const pr = await createPR(repoData.data.default_branch, branch, summary, `${response}\n\nCloses #${issueId}`)
|
||||||
repoData.data.default_branch,
|
await updateComment(`opencode created pull request #${pr}`)
|
||||||
branch,
|
|
||||||
summary,
|
|
||||||
`${response}\n\nCloses #${issueId}`
|
|
||||||
);
|
|
||||||
await updateComment(`opencode created pull request #${pr}`);
|
|
||||||
} else if (state.type === "local-pr") {
|
} else if (state.type === "local-pr") {
|
||||||
await pushToCurrentBranch(summary);
|
await pushToCurrentBranch(summary)
|
||||||
await updateComment(response);
|
await updateComment(response)
|
||||||
} else if (state.type === "fork-pr") {
|
} else if (state.type === "fork-pr") {
|
||||||
await pushToForkBranch(summary, state.pr);
|
await pushToForkBranch(summary, state.pr)
|
||||||
await updateComment(response);
|
await updateComment(response)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
await updateComment(response);
|
await updateComment(response)
|
||||||
}
|
}
|
||||||
await restoreGitConfig();
|
await restoreGitConfig()
|
||||||
await revokeAppToken();
|
await revokeAppToken()
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
await restoreGitConfig();
|
await restoreGitConfig()
|
||||||
await revokeAppToken();
|
await revokeAppToken()
|
||||||
console.error(e);
|
console.error(e)
|
||||||
let msg = e;
|
let msg = e
|
||||||
if (e instanceof $.ShellError) {
|
if (e instanceof $.ShellError) {
|
||||||
msg = e.stderr.toString();
|
msg = e.stderr.toString()
|
||||||
} else if (e instanceof Error) {
|
} else if (e instanceof Error) {
|
||||||
msg = e.message;
|
msg = e.message
|
||||||
}
|
}
|
||||||
if (commentId) await updateComment(msg);
|
if (commentId) await updateComment(msg)
|
||||||
core.setFailed(`opencode failed with error: ${msg}`);
|
core.setFailed(`opencode failed with error: ${msg}`)
|
||||||
// Also output the clean error message for the action to capture
|
// Also output the clean error message for the action to capture
|
||||||
//core.setOutput("prepare_error", e.message);
|
//core.setOutput("prepare_error", e.message);
|
||||||
process.exit(1);
|
process.exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (import.meta.main) {
|
if (import.meta.main) {
|
||||||
run();
|
run()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function generateGitHubToken() {
|
async function generateGitHubToken() {
|
||||||
try {
|
try {
|
||||||
return await core.getIDToken("opencode-github-action");
|
return await core.getIDToken("opencode-github-action")
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to get OIDC token:", error);
|
console.error("Failed to get OIDC token:", error)
|
||||||
throw new Error(
|
throw new Error("Could not fetch an OIDC token. Make sure to add `id-token: write` to your workflow permissions.")
|
||||||
"Could not fetch an OIDC token. Make sure to add `id-token: write` to your workflow permissions."
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function exchangeForAppToken(oidcToken: string) {
|
async function exchangeForAppToken(oidcToken: string) {
|
||||||
const response = await fetch(
|
const response = await fetch("https://api.opencode.ai/exchange_github_app_token", {
|
||||||
"https://api.frank.dev.opencode.ai/exchange_github_app_token",
|
method: "POST",
|
||||||
{
|
headers: {
|
||||||
method: "POST",
|
Authorization: `Bearer ${oidcToken}`,
|
||||||
headers: {
|
},
|
||||||
Authorization: `Bearer ${oidcToken}`,
|
})
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const responseJson = (await response.json()) as { error?: string };
|
const responseJson = (await response.json()) as { error?: string }
|
||||||
throw new Error(
|
throw new Error(`App token exchange failed: ${response.status} ${response.statusText} - ${responseJson.error}`)
|
||||||
`App token exchange failed: ${response.status} ${response.statusText} - ${responseJson.error}`
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const responseJson = (await response.json()) as { token: string };
|
const responseJson = (await response.json()) as { token: string }
|
||||||
return responseJson.token;
|
return responseJson.token
|
||||||
}
|
}
|
||||||
|
|
||||||
async function configureGit(appToken: string) {
|
async function configureGit(appToken: string) {
|
||||||
console.log("Configuring git...");
|
console.log("Configuring git...")
|
||||||
const config = "http.https://github.com/.extraheader";
|
const config = "http.https://github.com/.extraheader"
|
||||||
const ret = await $`git config --local --get ${config}`;
|
const ret = await $`git config --local --get ${config}`
|
||||||
gitCredentials = ret.stdout.toString().trim();
|
gitCredentials = ret.stdout.toString().trim()
|
||||||
|
|
||||||
const newCredentials = Buffer.from(
|
const newCredentials = Buffer.from(`x-access-token:${appToken}`, "utf8").toString("base64")
|
||||||
`x-access-token:${appToken}`,
|
|
||||||
"utf8"
|
|
||||||
).toString("base64");
|
|
||||||
|
|
||||||
await $`git config --local --unset-all ${config}`;
|
await $`git config --local --unset-all ${config}`
|
||||||
await $`git config --local ${config} "AUTHORIZATION: basic ${newCredentials}"`;
|
await $`git config --local ${config} "AUTHORIZATION: basic ${newCredentials}"`
|
||||||
await $`git config --global user.name "opencode-agent[bot]"`;
|
await $`git config --global user.name "opencode-agent[bot]"`
|
||||||
await $`git config --global user.email "opencode-agent[bot]@users.noreply.github.com"`;
|
await $`git config --global user.email "opencode-agent[bot]@users.noreply.github.com"`
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkoutLocalBranch(pr: GitHubPullRequest) {
|
async function checkoutLocalBranch(pr: GitHubPullRequest) {
|
||||||
console.log("Checking out local branch...");
|
console.log("Checking out local branch...")
|
||||||
|
|
||||||
const branch = pr.headRefName;
|
const branch = pr.headRefName
|
||||||
const depth = Math.max(pr.commits.totalCount, 20);
|
const depth = Math.max(pr.commits.totalCount, 20)
|
||||||
|
|
||||||
await $`git fetch origin --depth=${depth} ${branch}`;
|
await $`git fetch origin --depth=${depth} ${branch}`
|
||||||
await $`git checkout ${branch}`;
|
await $`git checkout ${branch}`
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkoutForkBranch(pr: GitHubPullRequest) {
|
async function checkoutForkBranch(pr: GitHubPullRequest) {
|
||||||
console.log("Checking out fork branch...");
|
console.log("Checking out fork branch...")
|
||||||
|
|
||||||
const remoteBranch = pr.headRefName;
|
const remoteBranch = pr.headRefName
|
||||||
const localBranch = generateBranchName();
|
const localBranch = generateBranchName()
|
||||||
const depth = Math.max(pr.commits.totalCount, 20);
|
const depth = Math.max(pr.commits.totalCount, 20)
|
||||||
|
|
||||||
await $`git remote add fork https://github.com/${pr.headRepository.nameWithOwner}.git`;
|
await $`git remote add fork https://github.com/${pr.headRepository.nameWithOwner}.git`
|
||||||
await $`git fetch fork --depth=${depth} ${remoteBranch}`;
|
await $`git fetch fork --depth=${depth} ${remoteBranch}`
|
||||||
await $`git checkout -b ${localBranch} fork/${remoteBranch}`;
|
await $`git checkout -b ${localBranch} fork/${remoteBranch}`
|
||||||
}
|
}
|
||||||
|
|
||||||
async function restoreGitConfig() {
|
async function restoreGitConfig() {
|
||||||
if (!gitCredentials) return;
|
if (!gitCredentials) return
|
||||||
const config = "http.https://github.com/.extraheader";
|
const config = "http.https://github.com/.extraheader"
|
||||||
await $`git config --local ${config} "${gitCredentials}"`;
|
await $`git config --local ${config} "${gitCredentials}"`
|
||||||
}
|
}
|
||||||
|
|
||||||
async function assertPermissions() {
|
async function assertPermissions() {
|
||||||
console.log(`Asserting permissions for user ${actor}...`);
|
console.log(`Asserting permissions for user ${actor}...`)
|
||||||
|
|
||||||
let permission;
|
let permission
|
||||||
try {
|
try {
|
||||||
const response = await octoRest.repos.getCollaboratorPermissionLevel({
|
const response = await octoRest.repos.getCollaboratorPermissionLevel({
|
||||||
owner,
|
owner,
|
||||||
repo,
|
repo,
|
||||||
username: actor,
|
username: actor,
|
||||||
});
|
})
|
||||||
|
|
||||||
permission = response.data.permission;
|
permission = response.data.permission
|
||||||
console.log(` permission: ${permission}`);
|
console.log(` permission: ${permission}`)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Failed to check permissions: ${error}`);
|
console.error(`Failed to check permissions: ${error}`)
|
||||||
throw new Error(`Failed to check permissions for user ${actor}: ${error}`);
|
throw new Error(`Failed to check permissions for user ${actor}: ${error}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!["admin", "write"].includes(permission))
|
if (!["admin", "write"].includes(permission)) throw new Error(`User ${actor} does not have write permissions`)
|
||||||
throw new Error(`User ${actor} does not have write permissions`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildComment(content: string) {
|
function buildComment(content: string) {
|
||||||
const runId = process.env.GITHUB_RUN_ID!;
|
const runId = process.env.GITHUB_RUN_ID!
|
||||||
const runUrl = `/${owner}/${repo}/actions/runs/${runId}`;
|
const runUrl = `/${owner}/${repo}/actions/runs/${runId}`
|
||||||
return [
|
return [content, "\n\n", shareUrl ? `[view session](${shareUrl}) | ` : "", `[view log](${runUrl})`].join("")
|
||||||
content,
|
|
||||||
"\n\n",
|
|
||||||
shareUrl ? `[view session](${shareUrl}) | ` : "",
|
|
||||||
`[view log](${runUrl})`,
|
|
||||||
].join("");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createComment(body: string) {
|
async function createComment(body: string) {
|
||||||
console.log("Creating comment...");
|
console.log("Creating comment...")
|
||||||
return await octoRest.rest.issues.createComment({
|
return await octoRest.rest.issues.createComment({
|
||||||
owner,
|
owner,
|
||||||
repo,
|
repo,
|
||||||
issue_number: issueId,
|
issue_number: issueId,
|
||||||
body: buildComment(body),
|
body: buildComment(body),
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async function updateComment(body: string) {
|
async function updateComment(body: string) {
|
||||||
console.log("Updating comment...");
|
console.log("Updating comment...")
|
||||||
return await octoRest.rest.issues.updateComment({
|
return await octoRest.rest.issues.updateComment({
|
||||||
owner,
|
owner,
|
||||||
repo,
|
repo,
|
||||||
comment_id: commentId,
|
comment_id: commentId,
|
||||||
body: buildComment(body),
|
body: buildComment(body),
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateBranchName() {
|
function generateBranchName() {
|
||||||
const type = state.type === "issue" ? "issue" : "pr";
|
const type = state.type === "issue" ? "issue" : "pr"
|
||||||
const timestamp = new Date()
|
const timestamp = new Date()
|
||||||
.toISOString()
|
.toISOString()
|
||||||
.replace(/[:-]/g, "")
|
.replace(/[:-]/g, "")
|
||||||
.replace(/\.\d{3}Z/, "")
|
.replace(/\.\d{3}Z/, "")
|
||||||
.split("T")
|
.split("T")
|
||||||
.join("_");
|
.join("_")
|
||||||
return `opencode/${type}${issueId}-${timestamp}`;
|
return `opencode/${type}${issueId}-${timestamp}`
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pushToCurrentBranch(summary: string) {
|
async function pushToCurrentBranch(summary: string) {
|
||||||
console.log("Pushing to current branch...");
|
console.log("Pushing to current branch...")
|
||||||
await $`git add .`;
|
await $`git add .`
|
||||||
await $`git commit -m "${summary}
|
await $`git commit -m "${summary}
|
||||||
|
|
||||||
Co-authored-by: ${actor} <${actor}@users.noreply.github.com>"`;
|
Co-authored-by: ${actor} <${actor}@users.noreply.github.com>"`
|
||||||
await $`git push`;
|
await $`git push`
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pushToForkBranch(summary: string, pr: GitHubPullRequest) {
|
async function pushToForkBranch(summary: string, pr: GitHubPullRequest) {
|
||||||
console.log("Pushing to fork branch...");
|
console.log("Pushing to fork branch...")
|
||||||
|
|
||||||
const remoteBranch = pr.headRefName;
|
const remoteBranch = pr.headRefName
|
||||||
|
|
||||||
await $`git add .`;
|
await $`git add .`
|
||||||
await $`git commit -m "${summary}
|
await $`git commit -m "${summary}
|
||||||
|
|
||||||
Co-authored-by: ${actor} <${actor}@users.noreply.github.com>"`;
|
Co-authored-by: ${actor} <${actor}@users.noreply.github.com>"`
|
||||||
await $`git push fork HEAD:${remoteBranch}`;
|
await $`git push fork HEAD:${remoteBranch}`
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pushToNewBranch(summary: string) {
|
async function pushToNewBranch(summary: string) {
|
||||||
console.log("Pushing to new branch...");
|
console.log("Pushing to new branch...")
|
||||||
const branch = generateBranchName();
|
const branch = generateBranchName()
|
||||||
await $`git checkout -b ${branch}`;
|
await $`git checkout -b ${branch}`
|
||||||
await $`git add .`;
|
await $`git add .`
|
||||||
await $`git commit -m "${summary}
|
await $`git commit -m "${summary}
|
||||||
|
|
||||||
Co-authored-by: ${actor} <${actor}@users.noreply.github.com>"`;
|
Co-authored-by: ${actor} <${actor}@users.noreply.github.com>"`
|
||||||
await $`git push -u origin ${branch}`;
|
await $`git push -u origin ${branch}`
|
||||||
return branch;
|
return branch
|
||||||
}
|
}
|
||||||
|
|
||||||
async function createPR(
|
async function createPR(base: string, branch: string, title: string, body: string) {
|
||||||
base: string,
|
console.log("Creating pull request...")
|
||||||
branch: string,
|
|
||||||
title: string,
|
|
||||||
body: string
|
|
||||||
) {
|
|
||||||
console.log("Creating pull request...");
|
|
||||||
const pr = await octoRest.rest.pulls.create({
|
const pr = await octoRest.rest.pulls.create({
|
||||||
owner,
|
owner,
|
||||||
repo,
|
repo,
|
||||||
@@ -343,41 +301,39 @@ async function createPR(
|
|||||||
base,
|
base,
|
||||||
title,
|
title,
|
||||||
body: buildComment(body),
|
body: buildComment(body),
|
||||||
});
|
})
|
||||||
return pr.data.number;
|
return pr.data.number
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runOpencode(
|
async function runOpencode(
|
||||||
prompt: string,
|
prompt: string,
|
||||||
opts?: {
|
opts?: {
|
||||||
share?: boolean;
|
share?: boolean
|
||||||
}
|
},
|
||||||
) {
|
) {
|
||||||
console.log("Running opencode...");
|
console.log("Running opencode...")
|
||||||
|
|
||||||
const promptPath = path.join(os.tmpdir(), "PROMPT");
|
const promptPath = path.join(os.tmpdir(), "PROMPT")
|
||||||
await Bun.write(promptPath, prompt);
|
await Bun.write(promptPath, prompt)
|
||||||
const ret = await $`cat ${promptPath} | opencode run -m ${
|
const ret = await $`cat ${promptPath} | opencode run -m ${process.env.INPUT_MODEL} ${opts?.share ? "--share" : ""}`
|
||||||
process.env.INPUT_MODEL
|
|
||||||
} ${opts?.share ? "--share" : ""}`;
|
|
||||||
return {
|
return {
|
||||||
stdout: ret.stdout.toString().trim(),
|
stdout: ret.stdout.toString().trim(),
|
||||||
stderr: ret.stderr.toString().trim(),
|
stderr: ret.stderr.toString().trim(),
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function branchIsDirty() {
|
async function branchIsDirty() {
|
||||||
console.log("Checking if branch is dirty...");
|
console.log("Checking if branch is dirty...")
|
||||||
const ret = await $`git status --porcelain`;
|
const ret = await $`git status --porcelain`
|
||||||
return ret.stdout.toString().trim().length > 0;
|
return ret.stdout.toString().trim().length > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchRepo() {
|
async function fetchRepo() {
|
||||||
return await octoRest.rest.repos.get({ owner, repo });
|
return await octoRest.rest.repos.get({ owner, repo })
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchIssue() {
|
async function fetchIssue() {
|
||||||
console.log("Fetching prompt data for issue...");
|
console.log("Fetching prompt data for issue...")
|
||||||
const issueResult = await octoGraph<IssueQueryResponse>(
|
const issueResult = await octoGraph<IssueQueryResponse>(
|
||||||
`
|
`
|
||||||
query($owner: String!, $repo: String!, $number: Int!) {
|
query($owner: String!, $repo: String!, $number: Int!) {
|
||||||
@@ -408,22 +364,22 @@ query($owner: String!, $repo: String!, $number: Int!) {
|
|||||||
owner,
|
owner,
|
||||||
repo,
|
repo,
|
||||||
number: issueId,
|
number: issueId,
|
||||||
}
|
},
|
||||||
);
|
)
|
||||||
|
|
||||||
const issue = issueResult.repository.issue;
|
const issue = issueResult.repository.issue
|
||||||
if (!issue) throw new Error(`Issue #${issueId} not found`);
|
if (!issue) throw new Error(`Issue #${issueId} not found`)
|
||||||
|
|
||||||
return issue;
|
return issue
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildPromptDataForIssue(issue: GitHubIssue) {
|
function buildPromptDataForIssue(issue: GitHubIssue) {
|
||||||
const comments = (issue.comments?.nodes || [])
|
const comments = (issue.comments?.nodes || [])
|
||||||
.filter((c) => {
|
.filter((c) => {
|
||||||
const id = parseInt(c.databaseId);
|
const id = parseInt(c.databaseId)
|
||||||
return id !== commentId && id !== payload.comment.id;
|
return id !== commentId && id !== payload.comment.id
|
||||||
})
|
})
|
||||||
.map((c) => ` - ${c.author.login} at ${c.createdAt}: ${c.body}`);
|
.map((c) => ` - ${c.author.login} at ${c.createdAt}: ${c.body}`)
|
||||||
|
|
||||||
return [
|
return [
|
||||||
"Here is the context for the issue:",
|
"Here is the context for the issue:",
|
||||||
@@ -433,11 +389,11 @@ function buildPromptDataForIssue(issue: GitHubIssue) {
|
|||||||
`- Created At: ${issue.createdAt}`,
|
`- Created At: ${issue.createdAt}`,
|
||||||
`- State: ${issue.state}`,
|
`- State: ${issue.state}`,
|
||||||
...(comments.length > 0 ? ["- Comments:", ...comments] : []),
|
...(comments.length > 0 ? ["- Comments:", ...comments] : []),
|
||||||
].join("\n");
|
].join("\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchPR() {
|
async function fetchPR() {
|
||||||
console.log("Fetching prompt data for PR...");
|
console.log("Fetching prompt data for PR...")
|
||||||
const prResult = await octoGraph<PullRequestQueryResponse>(
|
const prResult = await octoGraph<PullRequestQueryResponse>(
|
||||||
`
|
`
|
||||||
query($owner: String!, $repo: String!, $number: Int!) {
|
query($owner: String!, $repo: String!, $number: Int!) {
|
||||||
@@ -525,36 +481,32 @@ query($owner: String!, $repo: String!, $number: Int!) {
|
|||||||
owner,
|
owner,
|
||||||
repo,
|
repo,
|
||||||
number: issueId,
|
number: issueId,
|
||||||
}
|
},
|
||||||
);
|
)
|
||||||
|
|
||||||
const pr = prResult.repository.pullRequest;
|
const pr = prResult.repository.pullRequest
|
||||||
if (!pr) throw new Error(`PR #${issueId} not found`);
|
if (!pr) throw new Error(`PR #${issueId} not found`)
|
||||||
|
|
||||||
return pr;
|
return pr
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildPromptDataForPR(pr: GitHubPullRequest) {
|
function buildPromptDataForPR(pr: GitHubPullRequest) {
|
||||||
const comments = (pr.comments?.nodes || [])
|
const comments = (pr.comments?.nodes || [])
|
||||||
.filter((c) => {
|
.filter((c) => {
|
||||||
const id = parseInt(c.databaseId);
|
const id = parseInt(c.databaseId)
|
||||||
return id !== commentId && id !== payload.comment.id;
|
return id !== commentId && id !== payload.comment.id
|
||||||
})
|
})
|
||||||
.map((c) => ` - ${c.author.login} at ${c.createdAt}: ${c.body}`);
|
.map((c) => ` - ${c.author.login} at ${c.createdAt}: ${c.body}`)
|
||||||
|
|
||||||
const files = (pr.files.nodes || []).map(
|
const files = (pr.files.nodes || []).map((f) => ` - ${f.path} (${f.changeType}) +${f.additions}/-${f.deletions}`)
|
||||||
(f) => ` - ${f.path} (${f.changeType}) +${f.additions}/-${f.deletions}`
|
|
||||||
);
|
|
||||||
const reviewData = (pr.reviews.nodes || []).map((r) => {
|
const reviewData = (pr.reviews.nodes || []).map((r) => {
|
||||||
const comments = (r.comments.nodes || []).map(
|
const comments = (r.comments.nodes || []).map((c) => ` - ${c.path}:${c.line ?? "?"}: ${c.body}`)
|
||||||
(c) => ` - ${c.path}:${c.line ?? "?"}: ${c.body}`
|
|
||||||
);
|
|
||||||
return [
|
return [
|
||||||
` - ${r.author.login} at ${r.submittedAt}:`,
|
` - ${r.author.login} at ${r.submittedAt}:`,
|
||||||
` - Review body: ${r.body}`,
|
` - Review body: ${r.body}`,
|
||||||
...(comments.length > 0 ? [" - Comments:", ...comments] : []),
|
...(comments.length > 0 ? [" - Comments:", ...comments] : []),
|
||||||
];
|
]
|
||||||
});
|
})
|
||||||
|
|
||||||
return [
|
return [
|
||||||
"Here is the context for the pull request:",
|
"Here is the context for the pull request:",
|
||||||
@@ -572,11 +524,11 @@ function buildPromptDataForPR(pr: GitHubPullRequest) {
|
|||||||
...(comments.length > 0 ? ["- Comments:", ...comments] : []),
|
...(comments.length > 0 ? ["- Comments:", ...comments] : []),
|
||||||
...(files.length > 0 ? ["- Changed files:", ...files] : []),
|
...(files.length > 0 ? ["- Changed files:", ...files] : []),
|
||||||
...(reviewData.length > 0 ? ["- Reviews:", ...reviewData] : []),
|
...(reviewData.length > 0 ? ["- Reviews:", ...reviewData] : []),
|
||||||
].join("\n");
|
].join("\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
async function revokeAppToken() {
|
async function revokeAppToken() {
|
||||||
if (!appToken) return;
|
if (!appToken) return
|
||||||
|
|
||||||
await fetch("https://api.github.com/installation/token", {
|
await fetch("https://api.github.com/installation/token", {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
@@ -585,5 +537,5 @@ async function revokeAppToken() {
|
|||||||
Accept: "application/vnd.github+json",
|
Accept: "application/vnd.github+json",
|
||||||
"X-GitHub-Api-Version": "2022-11-28",
|
"X-GitHub-Api-Version": "2022-11-28",
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-9
@@ -49,12 +49,15 @@ resources:
|
|||||||
models:
|
models:
|
||||||
app: App
|
app: App
|
||||||
logLevel: LogLevel
|
logLevel: LogLevel
|
||||||
|
provider: Provider
|
||||||
|
model: Model
|
||||||
mode: Mode
|
mode: Mode
|
||||||
methods:
|
methods:
|
||||||
get: get /app
|
get: get /app
|
||||||
init: post /app/init
|
init: post /app/init
|
||||||
log: post /log
|
log: post /log
|
||||||
modes: get /mode
|
modes: get /mode
|
||||||
|
providers: get /config/providers
|
||||||
|
|
||||||
find:
|
find:
|
||||||
models:
|
models:
|
||||||
@@ -75,14 +78,13 @@ resources:
|
|||||||
config:
|
config:
|
||||||
models:
|
models:
|
||||||
config: Config
|
config: Config
|
||||||
keybinds: KeybindsConfig
|
keybindsConfig: KeybindsConfig
|
||||||
mcpLocal: McpLocalConfig
|
mcpLocalConfig: McpLocalConfig
|
||||||
mcpRemote: McpRemoteConfig
|
mcpRemoteConfig: McpRemoteConfig
|
||||||
provider: Provider
|
modeConfig: ModeConfig
|
||||||
model: Model
|
layoutConfig: LayoutConfig
|
||||||
methods:
|
methods:
|
||||||
get: get /config
|
get: get /config
|
||||||
providers: get /config/providers
|
|
||||||
|
|
||||||
session:
|
session:
|
||||||
models:
|
models:
|
||||||
@@ -94,10 +96,9 @@ resources:
|
|||||||
toolPart: ToolPart
|
toolPart: ToolPart
|
||||||
stepStartPart: StepStartPart
|
stepStartPart: StepStartPart
|
||||||
stepFinishPart: StepFinishPart
|
stepFinishPart: StepFinishPart
|
||||||
|
snapshotPart: SnapshotPart
|
||||||
assistantMessage: AssistantMessage
|
assistantMessage: AssistantMessage
|
||||||
assistantMessagePart: AssistantMessagePart
|
|
||||||
userMessage: UserMessage
|
userMessage: UserMessage
|
||||||
userMessagePart: UserMessagePart
|
|
||||||
toolStatePending: ToolStatePending
|
toolStatePending: ToolStatePending
|
||||||
toolStateRunning: ToolStateRunning
|
toolStateRunning: ToolStateRunning
|
||||||
toolStateCompleted: ToolStateCompleted
|
toolStateCompleted: ToolStateCompleted
|
||||||
@@ -126,9 +127,13 @@ readme:
|
|||||||
example_requests:
|
example_requests:
|
||||||
default:
|
default:
|
||||||
type: request
|
type: request
|
||||||
endpoint: get /event
|
endpoint: get /session
|
||||||
params: {}
|
params: {}
|
||||||
headline:
|
headline:
|
||||||
|
type: request
|
||||||
|
endpoint: get /session
|
||||||
|
params: {}
|
||||||
|
streaming:
|
||||||
type: request
|
type: request
|
||||||
endpoint: get /event
|
endpoint: get /event
|
||||||
params: {}
|
params: {}
|
||||||
|
|||||||
Reference in New Issue
Block a user