Compare commits

..
Author SHA1 Message Date
BaaRai 9f892e4e95 fix(intercept): make target pins name-only behind any proxy
The gate treated a call as direct whenever only the recording proxy or a
custom tool's own proxy was in the path, so it stored IP pins the proxy
did not enforce. ProxyAddr now covers the recording and global proxies,
a per-tool check covers a custom http tool's own proxy, and the gate
marks the pin name-only for any of them.

Closes #368.
2026-11-19 15:47:36 +01:00
BaaRai e5fe5b2878 Merge pull request #346 from mervedalgin/i18n-turkish
web: add UI translation layer and Turkish locale
2026-11-19 15:43:22 +01:00
BaaRai d577d7e3b2 fix(web): guard t() against prototype keys and check the dictionary in CI
t() looked a key up with dict[key] ?? key, so t("constructor") returned
Object and t("toString", {}) threw. Backend values are used as keys, so
this was reachable. Use an own-property check for the dictionary and the
vars, and commit the key-check script as npm run test:i18n in the web
job so tr.json cannot drift.
2026-11-19 15:40:49 +01:00
BaaRai 5ada6ecd86 Merge pull request #369 from BaaRai/docs/provider-policy
docs(contributing): keep provider support generic
2026-11-19 15:31:08 +01:00
Merve DALĞINandClaude Opus 5.5 e59d396f20 web: render the 404 text on the client
not-found is prerendered in the build-time locale, so a reader whose
browser picks another locale hit a hydration mismatch. Render the
translated text after mount instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:03:52 +03:00
Merve DALĞINandClaude Opus 5.5 a2445e3551 web: add UI translation layer and Turkish locale
Every user-visible string in the web UI now goes through t() from
web/src/i18n. The English source text is the key, so a missing entry
falls back to English and nothing breaks; Turkish lives in one flat
file, web/src/i18n/locales/tr.json (about 2,600 entries).

The locale is chosen once per page load: a saved choice, else the
browser language, else English. Switching (new Language toggle under
Preferences) stores the choice and reloads, so t() also works in module
constants, helpers and toasts without hooks.

Also:
- hard-coded zh-CN / implicit date locales now follow the UI language
- sentences assembled from fragments became single templates
- "Toujours autoriser" in approval records is now English
- upload.test.mjs stubs the new @/i18n import

Values sent to the API or compared in code, agent prompts, and backend
messages are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:03:52 +03:00
114 changed files with 7390 additions and 3518 deletions
+1
View File
@@ -149,6 +149,7 @@ jobs:
- run: npm run test:polling
- run: npm run test:replay
- run: npm run test:upload
- run: npm run test:i18n
- run: npm run build:static
python:
+1
View File
@@ -49,6 +49,7 @@ All notable changes to this project are documented in this file. The format is b
### Fixed
- **Target gate behind proxies**: a target approval is name-only whenever a proxy is in the path, including the recording proxy, the global egress proxy and a custom tool's own proxy, so the gate never claims an IP binding the proxy does not enforce.
- **Remote MCP response bound**: Streamable HTTP JSON-RPC bodies and SSE data payloads are refused above 8 MiB, so a remote MCP server cannot force an unbounded decode.
- **LLM response capture bound**: each recorded provider attempt keeps at most 1 MiB, and a call keeps at most 8 attempts, so a large or retrying stream cannot grow the recorder without bound. The live stream is unchanged.
- **Intercept audit ring**: `preToolUse` records allow only after intercept and the target gate decide, so a blocked call no longer leaves a leftover allow row in `Guard.Audit()`.
+12
View File
@@ -211,6 +211,9 @@ type Interceptor struct {
// upstreamProxy reports whether target traffic leaves through an upstream
// egress proxy (nil = no). Injected by the server layer.
upstreamProxy func() bool
// toolProxy reports whether one tool's own configuration routes its traffic
// through a proxy (nil = no). Injected by the server layer.
toolProxy func(string) bool
// derivedExempt lists the endpoints of the platform's own services (nil =
// none). Injected by the server layer. See SetDerivedExemptions.
derivedExempt func() []string
@@ -234,6 +237,15 @@ func (i *Interceptor) SetUpstreamProxyCheck(f func() bool) {
i.mu.Unlock()
}
// SetToolProxyCheck installs the function that reports whether a tool sends its
// own traffic through a proxy. The proxy then chooses the address it connects
// to, so a target approval for that call is name-only. Passing nil disables it.
func (i *Interceptor) SetToolProxyCheck(f func(string) bool) {
i.mu.Lock()
i.toolProxy = f
i.mu.Unlock()
}
// SetReviewer installs the LLM fallback judge callback. Passing nil disables it.
func (i *Interceptor) SetReviewer(r Reviewer) {
i.mu.Lock()
+6 -4
View File
@@ -208,11 +208,13 @@ func (c *targetCheck) run(targets []Target) ([]TargetRequest, TargetResult) {
i.mu.RLock()
proxied := i.upstreamProxy
toolProxy := i.toolProxy
i.mu.RUnlock()
// Behind the upstream proxy the proxy chooses the address it connects to, so
// every pin is name-only for this call, whatever the pin row says: the proxy
// can be turned on after a pin was approved.
nameOnly := proxied != nil && proxied()
// Behind a proxy the proxy chooses the address it connects to, so every pin
// is name-only for this call, whatever the pin row says: the proxy can be
// turned on after a pin was approved. The recording proxy, the global egress
// proxy and a custom tool's own proxy all count.
nameOnly := (proxied != nil && proxied()) || (toolProxy != nil && toolProxy(c.tool))
var unpinned []TargetRequest
var uses []func()
+25
View File
@@ -975,6 +975,31 @@ func TestUpstreamProxyMakesPinsNameOnlyAtCallTime(t *testing.T) {
g.passes("name-only pin, no proxy", g.fetch(appURL))
}
// A custom tool that carries its own proxy cannot enforce an approved IP, so
// its pins are name-only at call time, the same as behind the upstream proxy.
func TestToolProxyMakesPinsNameOnlyAtCallTime(t *testing.T) {
g := newGate(t)
proxied := false
g.ic.SetToolProxyCheck(func(string) bool { return proxied })
const tool = "my_http_tool"
const input = `{"url":"https://app.example.com/login"}`
g.res.set("app.example.com", "203.0.113.7")
g.pin("app.example.com", 443, "203.0.113.7")
// The address changes. A direct call asks.
g.res.set("app.example.com", "198.51.100.99")
g.expire()
g.requests("changed address, direct tool", g.check(tool, input))
// The same pin covers the name for the proxied tool, and the first-use row
// records that the connection was not bound.
proxied = true
g.passes("changed address, proxied tool", g.check(tool, input))
if got := g.store.outcomes(); len(got) != 1 || got[0] != "allowed/pin_match" || !g.store.logged[0].Audit.Targets[0].NameOnlyEffective {
t.Fatalf("rows %v, target %+v; want a name-only first use", got, g.store.logged[0].Audit.Targets[0])
}
}
// The first call that a pin version covers is logged once per process.
func TestPinFirstUseLoggedOncePerVersion(t *testing.T) {
g := newGate(t)
+35 -2
View File
@@ -430,8 +430,11 @@ func NewManager(dir, proxyAddr string) (*Manager, error) {
log.Printf("[llmusage] create table: %v", err)
}
m := &Manager{dir: dir, pg: pg, assets: pg.Assets(), tasks: map[string]*Task{}, interceptor: intercept.New(pg)}
// Behind the global egress proxy a target approval is name-only.
m.interceptor.SetUpstreamProxyCheck(func() bool { return m.GlobalProxy() != "" })
// Behind any proxy in the path (the recording proxy, the global egress proxy,
// or a custom tool's own proxy) the proxy chooses the address, so a target
// approval is name-only.
m.interceptor.SetUpstreamProxyCheck(func() bool { return m.ProxyAddr() != "" })
m.interceptor.SetToolProxyCheck(m.toolUsesProxy)
// The platform's own endpoints need no target approval.
m.interceptor.SetDerivedExemptions(m.targetGateEndpoints)
if proxyAddr != "" {
@@ -832,6 +835,36 @@ func (m *Manager) ProxyAddr() string {
return m.globalProxy
}
// toolUsesProxy reports whether a custom tool's own configuration sends its
// traffic through a proxy. That call cannot enforce an approved IP, so the
// target gate treats its pins as name-only. A recording-proxy tool is also
// covered by ProxyAddr() when capture is on; the per-tool check covers a
// tool-specific proxy while capture is off.
func (m *Manager) toolUsesProxy(key string) bool {
if m.pg == nil {
return false
}
t, err := m.pg.GetTool(key)
if err != nil {
// A failed read cannot prove the call is direct; treat it as proxied.
return true
}
if t == nil || t.Kind != "http" {
return false
}
var spec struct {
Proxy string `json:"proxy"`
UseRecordingProxy bool `json:"use_recording_proxy"`
}
if json.Unmarshal(t.Exec, &spec) != nil {
return false
}
if strings.TrimSpace(spec.Proxy) != "" {
return true
}
return spec.UseRecordingProxy && m.ProxyAddr() != ""
}
// ProxyCACert returns the CA cert path agents must trust to verify HTTPS through
// the egress proxy. Non-empty ONLY when traffic capture is on (the MITM re-signs
// certs): the global proxy used directly (capture off) is a plain forwarder that
+86
View File
@@ -0,0 +1,86 @@
package server
import (
"encoding/json"
"fmt"
"testing"
"time"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/traffic"
)
// ProxyAddr is the one source of truth for "is there a proxy in the path":
// the recording proxy while capture is on, the global proxy otherwise.
func TestProxyAddrCoversRecordingAndGlobal(t *testing.T) {
m := &Manager{}
if got := m.ProxyAddr(); got != "" {
t.Fatalf("empty manager ProxyAddr = %q", got)
}
m.globalProxy = "http://127.0.0.1:9"
if got := m.ProxyAddr(); got != m.globalProxy {
t.Fatalf("global ProxyAddr = %q", got)
}
tr, err := traffic.Open(t.TempDir(), "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer tr.Close()
m.traffic = tr
m.trafficOn = true
if got := m.ProxyAddr(); got == "" {
t.Fatal("recording proxy not returned by ProxyAddr")
}
}
// A custom http tool with its own proxy cannot enforce an approved IP; a
// recording-proxy tool counts only when a proxy address is actually in the path.
func TestToolUsesProxy(t *testing.T) {
g := newGateServer(t)
pg := g.m.pg
suffix := fmt.Sprintf("_%d", time.Now().UnixNano())
add := func(key, kind string, exec map[string]any) string {
t.Helper()
key += suffix
raw, err := json.Marshal(exec)
if err != nil {
t.Fatal(err)
}
if err := pg.CreateCustomTool(&db.Tool{Key: key, Kind: kind, Enabled: true, Exec: raw}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = pg.DeleteCustomTool(key) })
return key
}
proxied := add("t_proxy_http", "http", map[string]any{
"url": "http://example.com/", "proxy": "http://127.0.0.1:9"})
direct := add("t_direct_http", "http", map[string]any{"url": "http://example.com/"})
recording := add("t_rec_http", "http", map[string]any{
"url": "http://example.com/", "use_recording_proxy": true})
command := add("t_proxy_cmd", "command", map[string]any{
"command": "curl http://example.com/", "proxy": "http://127.0.0.1:9"})
if !g.m.toolUsesProxy(proxied) {
t.Fatal("per-tool proxy not detected")
}
if g.m.toolUsesProxy(direct) {
t.Fatal("direct http tool reported as proxied")
}
if g.m.toolUsesProxy(recording) {
t.Fatal("recording tool reported as proxied with capture off and no global proxy")
}
if g.m.toolUsesProxy(command) {
t.Fatal("command tool reported as proxied")
}
if g.m.toolUsesProxy("t_missing" + suffix) {
t.Fatal("missing tool reported as proxied")
}
// With a proxy address in the path, the recording flag counts.
g.m.globalProxy = "http://127.0.0.1:9"
if !g.m.toolUsesProxy(recording) {
t.Fatal("recording tool not proxied with a global proxy")
}
}
+2 -1
View File
@@ -15,7 +15,8 @@
"generate:presets": "ts-node -P tsconfig.scripts.json src/scripts/generate-theme-presets.ts",
"test:polling": "node --test scripts/polling.test.mjs",
"test:replay": "node --test scripts/replay.test.mjs",
"test:upload": "node --test scripts/upload.test.mjs"
"test:upload": "node --test scripts/upload.test.mjs",
"test:i18n": "node scripts/check-i18n.mjs"
},
"lint-staged": {
"*.{js,ts,jsx,tsx}": [
+64
View File
@@ -0,0 +1,64 @@
import { readFileSync, readdirSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
// Every literal t("...") / t('...') key must exist in the locale dictionary
// with the same {placeholders}. Dynamic keys (variables, template literals
// with ${}) are skipped: there is nothing to compare them against.
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const dict = JSON.parse(readFileSync(join(root, "src/i18n/locales/tr.json"), "utf8"));
const files = [];
function walk(dir) {
for (const name of readdirSync(dir)) {
const p = join(dir, name);
const st = statSync(p);
if (st.isDirectory()) walk(p);
else if (/\.(ts|tsx)$/.test(name)) files.push(p);
}
}
walk(join(root, "src"));
const calls = new Map(); // key -> first file that uses it
const literalCall = /(?:^|[^\w$.])t\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')/gm;
for (const file of files) {
const src = readFileSync(file, "utf8");
for (const m of src.matchAll(literalCall)) {
const key =
m[1] !== undefined ? JSON.parse(`"${m[1]}"`) : m[2].replace(/\\(['\\])/g, "$1");
if (!calls.has(key)) calls.set(key, file.slice(root.length + 1));
}
}
function placeholders(s) {
return [...s.matchAll(/\{(\w+)\}/g)]
.map((m) => m[1])
.sort()
.join(",");
}
const missing = [];
const mismatch = [];
for (const [key, file] of calls) {
if (!Object.prototype.hasOwnProperty.call(dict, key)) {
missing.push(`${file}: ${JSON.stringify(key)}`);
continue;
}
if (placeholders(dict[key]) !== placeholders(key)) {
mismatch.push(`${JSON.stringify(key)}: source {${placeholders(key)}} dict {${placeholders(dict[key])}}`);
}
}
if (missing.length || mismatch.length) {
if (missing.length) {
console.error(`Missing tr.json entries (${missing.length}):\n${missing.join("\n")}`);
}
if (mismatch.length) {
console.error(`Placeholder mismatches (${mismatch.length}):\n${mismatch.join("\n")}`);
}
process.exit(1);
}
console.log(
`i18n: ${calls.size} literal keys checked against ${Object.keys(dict).length} tr.json entries`,
);
+3
View File
@@ -21,6 +21,9 @@ function setup(mock = false) {
require(name) {
if (name === "@/lib/mock/enabled") return { MOCK: mock };
if (name === "@/lib/mock/handler") return { mockHandle: () => assert.fail("unexpected mock request") };
// English passthrough: assertions below match the source (English) messages.
if (name === "@/i18n")
return { t: (key, vars) => key.replace(/\{(\w+)\}/g, (m, k) => (vars && k in vars ? String(vars[k]) : m)) };
throw new Error("Unexpected import: " + name);
},
FormData: class {
+81 -44
View File
@@ -11,6 +11,7 @@ import { Checkbox } from "@/components/ui/checkbox";
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import { auth } from "@/lib/auth";
@@ -55,14 +56,14 @@ export default function LoginPage() {
.then(({ initialized }) => {
if (!initialized) router.replace("/setup");
})
.catch(() => setError("Unable to connect to the backend service"))
.catch(() => setError(t("Unable to connect to the backend service")))
.finally(() => setChecking(false));
}, [router]);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!agreed) {
setError("Please read and agree to the Terms of Use first");
setError(t("Please read and agree to the Terms of Use first"));
return;
}
setLoading(true);
@@ -72,7 +73,7 @@ export default function LoginPage() {
auth.setToken(token);
window.location.replace("/function/tasks");
} catch {
setError("Incorrect username or password");
setError(t("Incorrect username or password"));
} finally {
setLoading(false);
}
@@ -80,12 +81,16 @@ export default function LoginPage() {
if (checking) {
return (
<div role="status" className="flex min-h-dvh items-center justify-center text-muted-foreground">
Checking login state…
// Prerendered in the build-time locale; the reader's locale may differ for this brief state.
<div role="status" className="flex min-h-dvh items-center justify-center text-muted-foreground" suppressHydrationWarning>
{t("Checking login state…")}
</div>
);
}
// Keep the agreement sentence whole: the link text is placed through a placeholder so the word order can follow the locale.
const [agreeBefore, agreeAfter = ""] = t("I have read and agree to {terms}").split("{terms}");
return (
<div className="flex h-dvh">
{/* Left panel */}
@@ -103,22 +108,24 @@ export default function LoginPage() {
<div className="flex w-full items-center justify-center bg-background p-8 lg:w-2/3">
<div className="w-full max-w-md space-y-10 py-24 lg:py-32">
<div className="space-y-4 text-center">
<h2 className="text-2xl font-medium tracking-tight">Sign in</h2>
<p className="mx-auto max-w-xl text-muted-foreground">Welcome back — enter your password to continue using ARTEX</p>
<h2 className="text-2xl font-medium tracking-tight">{t("Sign in")}</h2>
<p className="mx-auto max-w-xl text-muted-foreground">
{t("Welcome back — enter your password to continue using ARTEX")}
</p>
</div>
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
<div className="space-y-1.5">
<Label htmlFor="username">Username</Label>
<Label htmlFor="username">{t("Username")}</Label>
<Input id="username" value="ARTEX" readOnly className="bg-muted text-muted-foreground" />
</div>
<div className="space-y-1.5">
<Label htmlFor="password">Password</Label>
<Label htmlFor="password">{t("Password")}</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter your password"
placeholder={t("Enter your password")}
autoFocus
autoComplete="current-password"
/>
@@ -131,19 +138,20 @@ export default function LoginPage() {
className="mt-0.5"
/>
<Label htmlFor="agree-terms" className="text-sm font-normal leading-relaxed text-muted-foreground">
I have read and agree to
{agreeBefore}
<button
type="button"
onClick={() => setTermsOpen(true)}
className="mx-0.5 font-medium text-primary underline-offset-4 hover:underline"
>
Terms of Use
{t("Terms of Use")}
</button>
{agreeAfter}
</Label>
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
<Button type="submit" className="w-full" disabled={loading || !password || !agreed}>
{loading ? "Signing in..." : "Sign in"}
{loading ? t("Signing in...") : t("Sign in")}
</Button>
</form>
</div>
@@ -156,9 +164,9 @@ export default function LoginPage() {
<ShieldCheck className="size-5" />
</div>
<div className="space-y-0.5">
<DialogTitle className="text-base">ARTEX Terms of Use and Disclaimer</DialogTitle>
<DialogTitle className="text-base">{t("ARTEX Terms of Use and Disclaimer")}</DialogTitle>
<p className="text-xs text-muted-foreground">
Version v1.1 · Effective 2026-10-11 · Please read all the following terms in full before signing in
{t("Version v1.1 · Effective 2026-10-11 · Please read all the following terms in full before signing in")}
</p>
</div>
</DialogHeader>
@@ -169,11 +177,14 @@ export default function LoginPage() {
className="max-h-[60vh] space-y-5 overflow-y-auto px-6 py-5 text-sm leading-relaxed text-muted-foreground"
>
<p className="rounded-lg border bg-muted/40 p-3 text-foreground/80">
This Terms of Use and Disclaimer (the "Statement") is the agreement between you and the ARTEX
project authors and contributors regarding your use of this software. Please read it carefully and fully understand each provision before use, especially the disclaimer, liability-limitation, and prohibition clauses highlighted in bold or color blocks.
{t(
'This Terms of Use and Disclaimer (the "Statement") is the agreement between you and the ARTEX project authors and contributors regarding your use of this software. Please read it carefully and fully understand each provision before use, especially the disclaimer, liability-limitation, and prohibition clauses highlighted in bold or color blocks.',
)}
<span className="font-medium text-foreground">
{" "}
Once you download, install, access, or use this software in any way, you are deemed to have read, understood, and agreed to be bound by all of this Statement.
{t(
"Once you download, install, access, or use this software in any way, you are deemed to have read, understood, and agreed to be bound by all of this Statement.",
)}
</span>
</p>
@@ -182,12 +193,12 @@ export default function LoginPage() {
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
1
</span>
Article 1 · Definitions and Open-Source License
{t("Article 1 · Definitions and Open-Source License")}
</h4>
<p className="pl-7">
This software (ARTEX) is an open-source program released under the GNU Affero General Public License
v3.0 (AGPL-3.0). You may freely use, copy, modify, and distribute it under that license; however, any derivative work (including online services provided to third parties over a network) must likewise be open-sourced under
the AGPL-3.0 license with the complete corresponding source code made public to its users. The full AGPL-3.0 terms are governed by the accompanying LICENSE file.
{t(
"This software (ARTEX) is an open-source program released under the GNU Affero General Public License v3.0 (AGPL-3.0). You may freely use, copy, modify, and distribute it under that license; however, any derivative work (including online services provided to third parties over a network) must likewise be open-sourced under the AGPL-3.0 license with the complete corresponding source code made public to its users. The full AGPL-3.0 terms are governed by the accompanying LICENSE file.",
)}
</p>
</section>
@@ -196,10 +207,12 @@ export default function LoginPage() {
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
2
</span>
Article 2 · Permitted Scope of Use
{t("Article 2 · Permitted Scope of Use")}
</h4>
<p className="pl-7">
This software is a security-testing platform. You may use it for: personal study, code research, and technical verification in environments you set up yourself; security testing of systems you own; security testing of third-party systems when you hold the owner's explicit authorization; and testing within the written scope of a bug bounty or vulnerability disclosure program, in compliance with that program's rules of engagement. You are responsible for obtaining and keeping proof of authorization, for staying inside the authorized scope, and for the safety and proportionality of every action the software takes on your behalf.
{t(
"This software is a security-testing platform. You may use it for: personal study, code research, and technical verification in environments you set up yourself; security testing of systems you own; security testing of third-party systems when you hold the owner's explicit authorization; and testing within the written scope of a bug bounty or vulnerability disclosure program, in compliance with that program's rules of engagement. You are responsible for obtaining and keeping proof of authorization, for staying inside the authorized scope, and for the safety and proportionality of every action the software takes on your behalf.",
)}
</p>
</section>
@@ -209,15 +222,29 @@ export default function LoginPage() {
3
</span>
<AlertTriangle className="size-4" />
Article 3 · Prohibited Conduct
{t("Article 3 · Prohibited Conduct")}
</h4>
<ul className="ml-7 list-decimal space-y-1.5 rounded-lg border border-destructive/20 bg-destructive/5 p-3 pl-8 text-foreground/80 marker:text-destructive/70">
<li>
Strictly forbidden: scanning, probing, exploiting, or attacking any system whose owner has not explicitly authorized you to test it, or exceeding the authorized scope or a program's rules of engagement once granted;
{t(
"Strictly forbidden: scanning, probing, exploiting, or attacking any system whose owner has not explicitly authorized you to test it, or exceeding the authorized scope or a program's rules of engagement once granted;",
)}
</li>
<li>
{t(
"Strictly forbidden: using this software for illegal intrusion, data theft, extortion, denial of service (DoS/DDoS), or any destructive or criminal activity;",
)}
</li>
<li>
{t(
"Strictly forbidden: removing, tampering with, or circumventing any copyright, license, or security notice in this software or its output;",
)}
</li>
<li>
{t(
"Strictly forbidden: engaging in any conduct that violates the laws, regulations, or regulatory rules of your country or region.",
)}
</li>
<li>Strictly forbidden: using this software for illegal intrusion, data theft, extortion, denial of service (DoS/DDoS), or any destructive or criminal activity;</li>
<li>Strictly forbidden: removing, tampering with, or circumventing any copyright, license, or security notice in this software or its output;</li>
<li>Strictly forbidden: engaging in any conduct that violates the laws, regulations, or regulatory rules of your country or region.</li>
</ul>
</section>
@@ -226,11 +253,12 @@ export default function LoginPage() {
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
4
</span>
Article 4 · Intellectual Property
{t("Article 4 · Intellectual Property")}
</h4>
<p className="pl-7">
The copyright and related intellectual property of this software belong to the project authors and contributors, who grant
you the corresponding rights within the scope of the AGPL-3.0 license. Beyond the rights expressly granted by that license, this Statement grants you no other rights, expressly or by implication.
{t(
"The copyright and related intellectual property of this software belong to the project authors and contributors, who grant you the corresponding rights within the scope of the AGPL-3.0 license. Beyond the rights expressly granted by that license, this Statement grants you no other rights, expressly or by implication.",
)}
</p>
</section>
@@ -239,10 +267,12 @@ export default function LoginPage() {
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
5
</span>
Article 5 · Data and Privacy
{t("Article 5 · Data and Privacy")}
</h4>
<p className="pl-7">
This software is a self-deployable open-source program; the authors run no centralized service and neither collect nor upload your usage data. All data you generate, process, or touch while using it stays under your control, and you are responsible for its legality and security; any consequence of improper data handling is yours to bear.
{t(
"This software is a self-deployable open-source program; the authors run no centralized service and neither collect nor upload your usage data. All data you generate, process, or touch while using it stays under your control, and you are responsible for its legality and security; any consequence of improper data handling is yours to bear.",
)}
</p>
</section>
@@ -251,13 +281,17 @@ export default function LoginPage() {
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
6
</span>
Article 6 · Compliance and Legal Liability
{t("Article 6 · Compliance and Legal Liability")}
</h4>
<p className="pl-7">
You must comply on your own with all laws and regulations of your country or region on cybersecurity, data security and personal-information protection, computer crime, and the like (for example, laws on unauthorized access to computer systems, on personal-data protection, and on the responsibilities of security researchers and penetration testers in your jurisdiction).
{t(
"You must comply on your own with all laws and regulations of your country or region on cybersecurity, data security and personal-information protection, computer crime, and the like (for example, laws on unauthorized access to computer systems, on personal-data protection, and on the responsibilities of security researchers and penetration testers in your jurisdiction).",
)}
<span className="font-medium text-foreground">
{" "}
All legal liability and consequences arising from your violation of the above laws and regulations or of this Statement are borne by you alone and have nothing to do with this software's authors and contributors.
{t(
"All legal liability and consequences arising from your violation of the above laws and regulations or of this Statement are borne by you alone and have nothing to do with this software's authors and contributors.",
)}
</span>
</p>
</section>
@@ -267,11 +301,12 @@ export default function LoginPage() {
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
7
</span>
Article 7 · Disclaimer and Limitation of Liability
{t("Article 7 · Disclaimer and Limitation of Liability")}
</h4>
<p className="pl-7">
This software is provided on an "AS IS" and "AS
AVAILABLE" basis, without any express or implied warranty, including but not limited to warranties of merchantability, fitness for a particular purpose, accuracy, and non-infringement. To the maximum extent permitted by applicable law, this software's authors and contributors are not liable for any direct, indirect, incidental, special, or consequential loss arising from using or being unable to use this software (regardless of whether it is used properly), including but not limited to data loss, system damage, business interruption, loss of profit, or legal disputes.
{t(
'This software is provided on an "AS IS" and "AS AVAILABLE" basis, without any express or implied warranty, including but not limited to warranties of merchantability, fitness for a particular purpose, accuracy, and non-infringement. To the maximum extent permitted by applicable law, this software\'s authors and contributors are not liable for any direct, indirect, incidental, special, or consequential loss arising from using or being unable to use this software (regardless of whether it is used properly), including but not limited to data loss, system damage, business interruption, loss of profit, or legal disputes.',
)}
</p>
</section>
@@ -280,17 +315,19 @@ export default function LoginPage() {
<span className="flex size-5 items-center justify-center rounded-md bg-muted text-xs font-semibold text-muted-foreground">
8
</span>
Article 8 · Changes to the Terms and Final Interpretation
{t("Article 8 · Changes to the Terms and Final Interpretation")}
</h4>
<p className="pl-7">
The authors may update this Statement from time to time as laws, regulations, or project development require; the updated version ships with the project and takes effect on its publication date, and your continued use of this software means you accept the revised terms. To the extent permitted by law, the authors hold the final right of interpretation of this Statement. If any provision of this Statement is held invalid, the remaining provisions stay in effect.
{t(
"The authors may update this Statement from time to time as laws, regulations, or project development require; the updated version ships with the project and takes effect on its publication date, and your continued use of this software means you accept the revised terms. To the extent permitted by law, the authors hold the final right of interpretation of this Statement. If any provision of this Statement is held invalid, the remaining provisions stay in effect.",
)}
</p>
</section>
</div>
<DialogFooter className="mx-0 mb-0 flex-col items-stretch gap-2 rounded-b-xl px-6 sm:flex-row sm:items-center sm:justify-between">
<p className="text-xs text-muted-foreground">
{readToEnd ? "You have read all the terms" : "Scroll the terms to the bottom to confirm"}
{readToEnd ? t("You have read all the terms") : t("Scroll the terms to the bottom to confirm")}
</p>
<DialogClose asChild>
<Button
@@ -301,7 +338,7 @@ export default function LoginPage() {
setError("");
}}
>
I have read and agree to all the terms
{t("I have read and agree to all the terms")}
</Button>
</DialogClose>
</DialogFooter>
+20 -15
View File
@@ -7,6 +7,7 @@ import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import { auth } from "@/lib/auth";
@@ -29,7 +30,7 @@ export default function SetupPage() {
if (initialized) router.replace("/login");
})
.catch((err) => {
setError(err instanceof Error ? err.message : "Unable to connect to the backend service");
setError(err instanceof Error ? err.message : t("Unable to connect to the backend service"));
setUnavailable(true);
})
.finally(() => setChecking(false));
@@ -38,11 +39,11 @@ export default function SetupPage() {
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (password !== confirm) {
setError("The two passwords do not match");
setError(t("The two passwords do not match"));
return;
}
if (password.length < 12) {
setError("Password must be at least 12 characters");
setError(t("Password must be at least 12 characters"));
return;
}
setLoading(true);
@@ -52,7 +53,7 @@ export default function SetupPage() {
auth.setToken(token);
router.replace("/function/tasks");
} catch (err) {
setError(err instanceof Error ? err.message : "Initialization failed");
setError(err instanceof Error ? err.message : t("Initialization failed"));
} finally {
setLoading(false);
}
@@ -77,52 +78,56 @@ export default function SetupPage() {
<div className="flex w-full items-center justify-center bg-background p-8 lg:w-2/3">
<div className="w-full max-w-md space-y-10 py-24 lg:py-32">
<div className="space-y-4 text-center">
<h2 className="text-2xl font-medium tracking-tight">{unavailable ? "Cannot confirm initialization state" : "Set initial password"}</h2>
<h2 className="text-2xl font-medium tracking-tight">{unavailable ? t("Cannot confirm initialization state") : t("Set initial password")}</h2>
<p className="mx-auto max-w-xl text-muted-foreground">
{unavailable
? "The backend or database is temporarily unavailable. To avoid overwriting a password already set on this instance, setup is temporarily closed — restore the service and try again."
: "First time using ARTEX? Enter the setup token from the server log, then set a login password for the account (at least 12 characters)"}
? t(
"The backend or database is temporarily unavailable. To avoid overwriting a password already set on this instance, setup is temporarily closed — restore the service and try again.",
)
: t(
"First time using ARTEX? Enter the setup token from the server log, then set a login password for the account (at least 12 characters)",
)}
</p>
</div>
{unavailable ? (
<div className="flex flex-col gap-4">
{error && <p className="text-center text-sm text-destructive">{error}</p>}
<Button type="button" className="w-full" onClick={() => window.location.reload()}>
Retry
{t("Retry")}
</Button>
</div>
) : (
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
<div className="space-y-1.5">
<Label htmlFor="setup-token">Setup token</Label>
<Label htmlFor="setup-token">{t("Setup token")}</Label>
<Input
id="setup-token"
value={setupToken}
onChange={(e) => setSetupToken(e.target.value)}
placeholder="Printed in the server log at startup"
placeholder={t("Printed in the server log at startup")}
autoFocus
autoComplete="off"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="password">New password</Label>
<Label htmlFor="password">{t("New password")}</Label>
<Input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="At least 12 characters"
placeholder={t("At least 12 characters")}
autoComplete="new-password"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="confirm">Confirm password</Label>
<Label htmlFor="confirm">{t("Confirm password")}</Label>
<Input
id="confirm"
type="password"
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
placeholder="Enter the password again"
placeholder={t("Enter the password again")}
autoComplete="new-password"
/>
</div>
@@ -132,7 +137,7 @@ export default function SetupPage() {
className="w-full"
disabled={loading || !setupToken.trim() || !password || !confirm}
>
{loading ? "Saving..." : "Set password and sign in"}
{loading ? t("Saving...") : t("Set password and sign in")}
</Button>
</form>
)}
+3 -1
View File
@@ -1,6 +1,8 @@
import { redirect } from "next/navigation";
import { t } from "@/i18n";
export default function Home() {
redirect("/function/tasks");
return <>Coming Soon</>;
return <>{t("Coming Soon")}</>;
}
@@ -9,6 +9,7 @@ import { X } from "lucide-react";
import { Separator } from "@/components/ui/separator";
import { SidebarTrigger } from "@/components/ui/sidebar";
import { useCurrentUser } from "@/hooks/use-current-user";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import { getLocalStorageValue, setLocalStorageValue } from "@/lib/local-storage.client";
import { cn } from "@/lib/utils";
@@ -57,11 +58,11 @@ export function MainContent({ children }: { children: ReactNode }) {
const updateBanner = latest ? (
<div className="flex shrink-0 items-center justify-center gap-2 border-b bg-muted/50 px-4 py-1 text-xs">
<a href={RELEASES_URL} target="_blank" rel="noreferrer" className="underline-offset-2 hover:underline">
ARTEX {latest} is available. See the release notes.
{t("ARTEX {version} is available. See the release notes.", { version: latest })}
</a>
<button
type="button"
aria-label="Dismiss update notice"
aria-label={t("Dismiss update notice")}
className="text-muted-foreground hover:text-foreground"
onClick={() => {
setLocalStorageValue(UPDATE_DISMISSED_KEY, latest);
@@ -102,7 +103,7 @@ export function MainContent({ children }: { children: ReactNode }) {
</div>
<div className="flex items-center gap-2">
{version && (
<span className="font-medium text-muted-foreground text-xs tabular-nums">Version · {version}</span>
<span className="font-medium text-muted-foreground text-xs tabular-nums">{t("Version · {version}", { version })}</span>
)}
<LayoutControls />
<ThemeSwitcher />
@@ -12,6 +12,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { t } from "@/i18n";
import { auth } from "@/lib/auth";
import { cn, getInitials } from "@/lib/utils";
@@ -64,7 +65,7 @@ export function AccountSwitcher({
</Avatar>
<div className="grid min-w-0 flex-1 text-left text-sm leading-tight">
<span className="truncate font-semibold">{user.name}</span>
<span className="truncate text-xs capitalize">{user.role}</span>
<span className="truncate text-xs capitalize">{t(user.role)}</span>
</div>
<span
className={cn(
@@ -80,11 +81,11 @@ export function AccountSwitcher({
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setPwOpen(true)}>
<KeyRound />
Change password
{t("Change password")}
</DropdownMenuItem>
<DropdownMenuItem onClick={handleLogout} className="text-destructive focus:text-destructive">
<LogOut />
Sign out
{t("Sign out")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -15,6 +15,7 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { t } from "@/i18n";
import { api } from "@/lib/api";
export function ChangePasswordDialog({
@@ -41,37 +42,44 @@ export function ChangePasswordDialog({
function submit(e: React.FormEvent) {
e.preventDefault();
if (!oldPassword || !newPassword) {
toast.error("Fill in the current password and the new password");
toast.error(t("Fill in the current password and the new password"));
return;
}
if (newPassword !== confirmPassword) {
toast.error("The two new passwords do not match");
toast.error(t("The two new passwords do not match"));
return;
}
setSaving(true);
api
.changePassword(oldPassword, newPassword)
.then(() => {
toast.success("Password changed");
toast.success(t("Password changed"));
onOpenChange(false);
})
.catch((err) => toast.error(`Change failed: ${(err as Error).message}`))
.catch((err) => toast.error(t("Change failed: {error}", { error: (err as Error).message })))
.finally(() => setSaving(false));
}
// The username stays bold; it is placed through a placeholder so the sentence is translated whole.
const [descBefore, descAfter = ""] = t(
"The username is fixed as {username}. Enter the current password to verify; login tokens issued before the change stay valid until they expire.",
).split("{username}");
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<form onSubmit={submit}>
<DialogHeader>
<DialogTitle>Change password</DialogTitle>
<DialogTitle>{t("Change password")}</DialogTitle>
<DialogDescription>
The username is fixed as <b>ARTEX</b>. Enter the current password to verify; login tokens issued before the change stay valid until they expire.
{descBefore}
<b>ARTEX</b>
{descAfter}
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3 py-4">
<div className="flex flex-col gap-1.5">
<Label htmlFor="cp-old">Current password</Label>
<Label htmlFor="cp-old">{t("Current password")}</Label>
<Input
id="cp-old"
type="password"
@@ -82,7 +90,7 @@ export function ChangePasswordDialog({
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="cp-new">New password</Label>
<Label htmlFor="cp-new">{t("New password")}</Label>
<Input
id="cp-new"
type="password"
@@ -93,7 +101,7 @@ export function ChangePasswordDialog({
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="cp-confirm">Confirm new password</Label>
<Label htmlFor="cp-confirm">{t("Confirm new password")}</Label>
<Input
id="cp-confirm"
type="password"
@@ -106,10 +114,10 @@ export function ChangePasswordDialog({
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
Cancel
{t("Cancel")}
</Button>
<Button type="submit" disabled={saving}>
{saving ? "Changing…" : "Confirm change"}
{saving ? t("Changing…") : t("Confirm change")}
</Button>
</DialogFooter>
</form>
@@ -21,6 +21,7 @@ import { persistPreference } from "@/lib/preferences/preferences-storage";
import { THEME_PRESET_OPTIONS, type ThemeMode, type ThemePreset } from "@/lib/preferences/theme";
import { applyThemePreset } from "@/lib/preferences/theme-utils";
import { usePreferencesStore } from "@/stores/preferences/preferences-provider";
import { type Locale, LOCALES, locale, setLocale, t } from "@/i18n";
export function LayoutControls() {
const themeMode = usePreferencesStore((s) => s.themeMode);
@@ -106,15 +107,33 @@ export function LayoutControls() {
<PopoverContent align="end">
<div className="flex flex-col gap-5">
<div className="space-y-1.5">
<h4 className="font-medium text-sm leading-none">Preferences</h4>
<p className="text-muted-foreground text-xs">Customize your dashboard layout preferences.</p>
<h4 className="font-medium text-sm leading-none">{t("Preferences")}</h4>
<p className="text-muted-foreground text-xs">{t("Customize your dashboard layout preferences.")}</p>
</div>
<div className="space-y-3 **:data-[slot=toggle-group]:w-full **:data-[slot=toggle-group-item]:flex-1 **:data-[slot=toggle-group-item]:text-xs">
<div className="space-y-1">
<Label className="font-medium text-xs">Theme Preset</Label>
<Label className="font-medium text-xs">{t("Language")}</Label>
<ToggleGroup
size="sm"
spacing={0}
variant="outline"
type="single"
value={locale}
onValueChange={(v: string) => v && setLocale(v as Locale)}
>
{LOCALES.map((l) => (
<ToggleGroupItem key={l.code} value={l.code} aria-label={l.label}>
{l.label}
</ToggleGroupItem>
))}
</ToggleGroup>
</div>
<div className="space-y-1">
<Label className="font-medium text-xs">{t("Theme Preset")}</Label>
<Select value={themePreset} onValueChange={onThemePresetChange}>
<SelectTrigger size="sm" className="w-full text-xs">
<SelectValue placeholder="Preset" />
<SelectValue placeholder={t("Preset")} />
</SelectTrigger>
<SelectContent>
<SelectGroup>
@@ -136,10 +155,10 @@ export function LayoutControls() {
</div>
<div className="space-y-1">
<Label className="font-medium text-xs">Fonts</Label>
<Label className="font-medium text-xs">{t("Fonts")}</Label>
<Select value={font} onValueChange={onFontChange}>
<SelectTrigger size="sm" className="w-full text-xs">
<SelectValue placeholder="Select font" />
<SelectValue placeholder={t("Select font")} />
</SelectTrigger>
<SelectContent>
<SelectGroup>
@@ -154,7 +173,7 @@ export function LayoutControls() {
</div>
<div className="space-y-1">
<Label className="font-medium text-xs">Theme Mode</Label>
<Label className="font-medium text-xs">{t("Theme Mode")}</Label>
<ToggleGroup
size="sm"
spacing={0}
@@ -163,20 +182,20 @@ export function LayoutControls() {
value={themeMode}
onValueChange={onThemeModeChange}
>
<ToggleGroupItem value="light" aria-label="Toggle light">
Light
<ToggleGroupItem value="light" aria-label={t("Light")}>
{t("Light")}
</ToggleGroupItem>
<ToggleGroupItem value="dark" aria-label="Toggle dark">
Dark
<ToggleGroupItem value="dark" aria-label={t("Dark")}>
{t("Dark")}
</ToggleGroupItem>
<ToggleGroupItem value="system" aria-label="Toggle system">
System
<ToggleGroupItem value="system" aria-label={t("System")}>
{t("System")}
</ToggleGroupItem>
</ToggleGroup>
</div>
<div className="space-y-1">
<Label className="font-medium text-xs">Page Layout</Label>
<Label className="font-medium text-xs">{t("Page Layout")}</Label>
<ToggleGroup
size="sm"
spacing={0}
@@ -185,17 +204,17 @@ export function LayoutControls() {
value={contentLayout}
onValueChange={onContentLayoutChange}
>
<ToggleGroupItem value="centered" aria-label="Toggle centered">
Centered
<ToggleGroupItem value="centered" aria-label={t("Centered")}>
{t("Centered")}
</ToggleGroupItem>
<ToggleGroupItem value="full-width" aria-label="Toggle full-width">
Full Width
<ToggleGroupItem value="full-width" aria-label={t("Full Width")}>
{t("Full Width")}
</ToggleGroupItem>
</ToggleGroup>
</div>
<div className="space-y-1">
<Label className="font-medium text-xs">Navbar Behavior</Label>
<Label className="font-medium text-xs">{t("Navbar Behavior")}</Label>
<ToggleGroup
size="sm"
spacing={0}
@@ -204,17 +223,17 @@ export function LayoutControls() {
value={navbarStyle}
onValueChange={onNavbarStyleChange}
>
<ToggleGroupItem value="sticky" aria-label="Toggle sticky">
Sticky
<ToggleGroupItem value="sticky" aria-label={t("Sticky")}>
{t("Sticky")}
</ToggleGroupItem>
<ToggleGroupItem value="scroll" aria-label="Toggle scroll">
Scroll
<ToggleGroupItem value="scroll" aria-label={t("Scroll")}>
{t("Scroll")}
</ToggleGroupItem>
</ToggleGroup>
</div>
<div className="space-y-1">
<Label className="font-medium text-xs">Sidebar Style</Label>
<Label className="font-medium text-xs">{t("Sidebar Style")}</Label>
<ToggleGroup
size="sm"
spacing={0}
@@ -223,20 +242,20 @@ export function LayoutControls() {
value={variant}
onValueChange={onSidebarStyleChange}
>
<ToggleGroupItem value="inset" aria-label="Toggle inset">
Inset
<ToggleGroupItem value="inset" aria-label={t("Inset")}>
{t("Inset")}
</ToggleGroupItem>
<ToggleGroupItem value="sidebar" aria-label="Toggle sidebar">
Sidebar
<ToggleGroupItem value="sidebar" aria-label={t("Sidebar")}>
{t("Sidebar")}
</ToggleGroupItem>
<ToggleGroupItem value="floating" aria-label="Toggle floating">
Floating
<ToggleGroupItem value="floating" aria-label={t("Floating")}>
{t("Floating")}
</ToggleGroupItem>
</ToggleGroup>
</div>
<div className="space-y-1">
<Label className="font-medium text-xs">Sidebar Collapse Mode</Label>
<Label className="font-medium text-xs">{t("Sidebar Collapse Mode")}</Label>
<ToggleGroup
size="sm"
spacing={0}
@@ -245,17 +264,17 @@ export function LayoutControls() {
value={collapsible}
onValueChange={onSidebarCollapseModeChange}
>
<ToggleGroupItem value="icon" aria-label="Toggle icon">
Icon
<ToggleGroupItem value="icon" aria-label={t("Icon")}>
{t("Icon")}
</ToggleGroupItem>
<ToggleGroupItem value="offcanvas" aria-label="Toggle offcanvas">
OffCanvas
<ToggleGroupItem value="offcanvas" aria-label={t("OffCanvas")}>
{t("OffCanvas")}
</ToggleGroupItem>
</ToggleGroup>
</div>
<Button type="button" size="sm" variant="outline" className="w-full text-xs" onClick={handleRestore}>
Restore Defaults
{t("Restore Defaults")}
</Button>
</div>
</div>
@@ -18,6 +18,7 @@ import {
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar";
import { t } from "@/i18n";
export function NavDocuments({
items,
@@ -32,7 +33,7 @@ export function NavDocuments({
return (
<SidebarGroup className="group-data-[collapsible=icon]:hidden">
<SidebarGroupLabel>Documents</SidebarGroupLabel>
<SidebarGroupLabel>{t("Documents")}</SidebarGroupLabel>
<SidebarMenu>
{items.map((item) => (
<SidebarMenuItem key={item.name}>
@@ -46,7 +47,7 @@ export function NavDocuments({
<DropdownMenuTrigger asChild>
<SidebarMenuAction showOnHover className="rounded-sm data-[state=open]:bg-accent">
<Ellipsis />
<span className="sr-only">More</span>
<span className="sr-only">{t("More")}</span>
</SidebarMenuAction>
</DropdownMenuTrigger>
<DropdownMenuContent
@@ -56,16 +57,16 @@ export function NavDocuments({
>
<DropdownMenuItem>
<Folder />
<span>Open</span>
<span>{t("Open")}</span>
</DropdownMenuItem>
<DropdownMenuItem>
<Forward />
<span>Share</span>
<span>{t("Share")}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive">
<Trash2 />
<span>Delete</span>
<span>{t("Delete")}</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -74,7 +75,7 @@ export function NavDocuments({
<SidebarMenuItem>
<SidebarMenuButton className="text-sidebar-foreground/70">
<Ellipsis className="text-sidebar-foreground/70" />
<span>More</span>
<span>{t("More")}</span>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
@@ -29,6 +29,7 @@ import {
SidebarMenuSubItem,
useSidebar,
} from "@/components/ui/sidebar";
import { t } from "@/i18n";
import { cn } from "@/lib/utils";
import type {
NavBadge,
@@ -321,7 +322,7 @@ function NavItemBadge({ badge }: { badge?: NavBadge }) {
badge === "soon" && "border-muted-foreground text-muted-foreground",
)}
>
{badge}
{t(badge)}
</SidebarMenuBadge>
);
}
@@ -14,6 +14,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "@/components/ui/sidebar";
import { t } from "@/i18n";
import { auth } from "@/lib/auth";
import { getInitials } from "@/lib/utils";
@@ -79,12 +80,12 @@ export function NavUser({
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setPwOpen(true)}>
<KeyRound />
Change password
{t("Change password")}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleLogout} className="text-destructive focus:text-destructive">
<LogOut />
Sign out
{t("Sign out")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -17,6 +17,7 @@ import {
CommandList,
CommandSeparator,
} from "@/components/ui/command";
import { t } from "@/i18n";
import type { NavMainItem } from "@/navigation/sidebar/sidebar-items";
import { sidebarItems } from "@/navigation/sidebar/sidebar-items";
@@ -33,7 +34,7 @@ type SearchItem = {
const sidebarGroupLabels = new Set(sidebarItems.flatMap((group) => (group.label ? [group.label] : [])));
function getSubItemGroup(groupLabel: string | undefined, itemTitle: string) {
return sidebarGroupLabels.has(itemTitle) ? (groupLabel ?? "Other") : itemTitle;
return sidebarGroupLabels.has(itemTitle) ? (groupLabel ?? t("Other")) : itemTitle;
}
const searchItems: SearchItem[] = sidebarItems.flatMap((group) =>
@@ -52,7 +53,7 @@ const searchItems: SearchItem[] = sidebarItems.flatMap((group) =>
return [
{
id: item.id,
group: group.label ?? "Other",
group: group.label ?? t("Other"),
label: item.title,
url: item.url,
icon: item.icon,
@@ -138,16 +139,16 @@ export function SearchDialog() {
className="px-0! font-normal text-muted-foreground hover:no-underline"
>
<Search data-icon="inline-start" />
Search
{t("Search")}
<kbd className="inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-medium text-[10px]">
<span className="text-xs">⌘</span>J
</kbd>
</Button>
<CommandDialog open={open} onOpenChange={handleOpenChange}>
<Command>
<CommandInput placeholder="Search dashboards, users, and more…" value={query} onValueChange={setQuery} />
<CommandInput placeholder={t("Search dashboards, users, and more…")} value={query} onValueChange={setQuery} />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandEmpty>{t("No results found.")}</CommandEmpty>
{query ? renderGroups(searchItems) : renderGroups(recommendations)}
</CommandList>
</Command>
@@ -4,24 +4,27 @@ import { siX } from "simple-icons";
import { SimpleIcon } from "@/components/simple-icon";
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { t } from "@/i18n";
export function SidebarSupportCard() {
// The X link sits inside the sentence through a placeholder so the word order can follow the locale.
const [before, after = ""] = t("Open an issue or do reach out to me on {x}.").split("{x}");
return (
<Card size="sm" className="overflow-hidden shadow-none group-data-[collapsible=icon]:hidden">
<CardHeader className="min-w-0 px-4">
<CardTitle className="truncate text-sm">Looking for something more?</CardTitle>
<CardTitle className="truncate text-sm">{t("Looking for something more?")}</CardTitle>
<CardDescription className="line-clamp-2">
Open an issue or do reach out to me on&nbsp;
{before.trimEnd()}&nbsp;
<Link
href="https://x.com/arhamkhnz"
target="_blank"
rel="noreferrer"
aria-label="Reach out on X"
aria-label={t("Reach out on X")}
className="inline-flex items-center text-foreground"
>
<SimpleIcon icon={siX} aria-hidden className="size-3 fill-current" />
</Link>
.
{after}
</CardDescription>
</CardHeader>
</Card>
@@ -3,11 +3,18 @@
import { Monitor, Moon, Sun } from "lucide-react";
import { Button } from "@/components/ui/button";
import { t } from "@/i18n";
import { persistPreference } from "@/lib/preferences/preferences-storage";
import { usePreferencesStore } from "@/stores/preferences/preferences-provider";
const THEME_CYCLE = ["light", "dark", "system"] as const;
const THEME_LABELS: Record<(typeof THEME_CYCLE)[number], string> = {
light: t("Light"),
dark: t("Dark"),
system: t("System"),
};
export function ThemeSwitcher() {
const themeMode = usePreferencesStore((s) => s.themeMode);
const setThemeMode = usePreferencesStore((s) => s.setThemeMode);
@@ -21,7 +28,7 @@ export function ThemeSwitcher() {
};
return (
<Button size="icon" onClick={cycleTheme} aria-label={`Current theme: ${themeMode}. Click to cycle themes`}>
<Button size="icon" onClick={cycleTheme} aria-label={t("Current theme: {theme}. Click to cycle themes", { theme: THEME_LABELS[themeMode] ?? themeMode })}>
{/* SYSTEM */}
<Monitor className="hidden [html[data-theme-mode=system]_&]:block" />
+103 -72
View File
@@ -60,6 +60,7 @@ import { getLocalStorageValue, setLocalStorageValue } from "@/lib/local-storage.
import { isBtwCommand } from "@/lib/side-questions";
import type { Activity, Agent, ChatAttachment, Conversation, LLMProfile } from "@/lib/types";
import { cn } from "@/lib/utils";
import { intlLocale, t } from "@/i18n";
// fmtBytes renders a human file size for attachment chips (mirrors transcript.tsx).
function fmtBytes(n: number): string {
@@ -137,7 +138,7 @@ function LiveBadge() {
return (
<span className="inline-flex items-center gap-1 rounded bg-blue-500/15 px-1.5 py-0.5 text-[10px] font-medium text-blue-600 dark:text-blue-400">
<span className="size-1 animate-pulse rounded-full bg-blue-500" />
Live
{t("Live")}
</span>
);
}
@@ -203,7 +204,7 @@ function Composer({
type="button"
className="ml-0.5 text-muted-foreground hover:text-foreground"
onClick={() => onRemoveAttachment(a.path)}
title="Remove"
title={t("Remove")}
>
<XIcon className="size-3" />
</button>
@@ -234,7 +235,7 @@ function Composer({
variant="ghost"
onClick={() => fileInputRef.current?.click()}
disabled={disabled || uploading}
title="Upload files"
title={t("Upload files")}
>
{uploading ? <Loader2Icon className="size-4 animate-spin" /> : <PaperclipIcon className="size-4" />}
</Button>
@@ -250,14 +251,14 @@ function Composer({
onKeyDown={onKeyDown}
/>
{running && allowBtw && isBtwCommand(value) && (
<Button size="icon" onClick={onSend} aria-label="Send side question" title="Send side question">
<Button size="icon" onClick={onSend} aria-label={t("Send side question")} title={t("Send side question")}>
<ArrowUpIcon />
</Button>
)}
{running ? (
// while a run is in flight the send button becomes a stop button —
// aborts just this session (the trigger queue keeps going).
<Button size="icon" variant="destructive" onClick={onStop} disabled={stopDisabled} title="Stop this run">
<Button size="icon" variant="destructive" onClick={onStop} disabled={stopDisabled} title={t("Stop this run")}>
<Square className="size-3.5 fill-current" />
</Button>
) : (
@@ -265,8 +266,8 @@ function Composer({
size="icon"
onClick={onSend}
disabled={disabled || (!value.trim() && atts.length === 0)}
title="Send message"
aria-label="Send message"
title={t("Send message")}
aria-label={t("Send message")}
>
<ArrowUpIcon />
</Button>
@@ -294,7 +295,11 @@ function LLMProfileRow({
const [open, setOpen] = React.useState(false);
const activeDefault = profiles.find((p) => p.is_default);
const current = selected != null ? profiles.find((p) => Number(p.id) === selected) : null;
const label = current ? current.name : `Default${activeDefault ? ` (${activeDefault.name})` : ""}`;
const label = current
? current.name
: activeDefault
? t("Default ({name})", { name: activeDefault.name })
: t("Default");
return (
<div className="flex min-w-0 shrink-0 items-center gap-1 px-1 pt-0.5 pb-1">
@@ -309,12 +314,12 @@ function LLMProfileRow({
disabled={disabled}
className="flex shrink-0 items-center gap-0.5 text-primary text-xs hover:underline disabled:pointer-events-none disabled:opacity-40"
>
Change
{t("Change")}
<ChevronDownIcon className="size-3" />
</button>
</PopoverTrigger>
<PopoverContent align="start" className="w-64 p-1">
<p className="text-muted-foreground px-2 py-1 text-[11px] font-medium">Select an LLM profile</p>
<p className="text-muted-foreground px-2 py-1 text-[11px] font-medium">{t("Select an LLM profile")}</p>
{/* default option */}
<button
type="button"
@@ -327,7 +332,9 @@ function LLMProfileRow({
selected == null && "bg-accent",
)}
>
<span className="text-sm">Default{activeDefault ? ` (${activeDefault.name})` : ""}</span>
<span className="text-sm">
{activeDefault ? t("Default ({name})", { name: activeDefault.name }) : t("Default")}
</span>
{activeDefault && (
<span className="text-muted-foreground text-[11px]">
{activeDefault.format} · {activeDefault.model}
@@ -395,7 +402,7 @@ function DraftChat({
await api.sendConversationMessage(c.id, msg);
onStarted(c);
} catch (e) {
toast.error("Send failed: " + (e as Error).message);
toast.error(t("Send failed: {error}", { error: (e as Error).message }));
setSending(false);
}
}
@@ -413,7 +420,7 @@ function DraftChat({
const r = await api.chatUpload("session", `conv-${c.id}`, files);
onStarted(c, { input, attachments: r.attachments });
} catch (e) {
toast.error("Upload failed: " + (e as Error).message);
toast.error(t("Upload failed: {error}", { error: (e as Error).message }));
setUploading(false);
}
}
@@ -421,7 +428,7 @@ function DraftChat({
const agentPicker = (
<Select value={agentKey} onValueChange={setAgentKey}>
<SelectTrigger className="w-full sm:w-40">
<SelectValue placeholder="Select an agent…" />
<SelectValue placeholder={t("Select an agent…")} />
</SelectTrigger>
<SelectContent>
<SelectGroup>
@@ -432,7 +439,7 @@ function DraftChat({
{a.name}
{!a.builtin && (
<Badge variant="outline" className="px-1 py-0 text-[9px]">
Custom
{t("Custom")}
</Badge>
)}
</span>
@@ -450,7 +457,9 @@ function DraftChat({
<div className="bg-primary/10 flex size-12 items-center justify-center rounded-full">
<Bot className="text-primary size-6" />
</div>
<div className="text-sm font-medium">Start a conversation with "{agent?.name ?? "Agent"}"</div>
<div className="text-sm font-medium">
{t('Start a conversation with "{name}"', { name: agent?.name ?? t("Agent") })}
</div>
{agent?.description && <p className="text-muted-foreground max-w-md text-xs">{agent.description}</p>}
</div>
@@ -459,7 +468,7 @@ function DraftChat({
onChange={setInput}
onSend={send}
disabled={sending || uploading || !agentKey}
placeholder="Type a message, @ to reference records, Enter to send"
placeholder={t("Type a message, @ to reference records, Enter to send")}
leftSlot={agentPicker}
onPickFiles={pickFiles}
uploading={uploading}
@@ -518,7 +527,7 @@ function ChatView({
await api.updateConversationProfile(conv.id, id);
onConvUpdated();
} catch (e) {
toast.error("Failed to switch LLM: " + (e as Error).message);
toast.error(t("Failed to switch LLM: {error}", { error: (e as Error).message }));
}
}
@@ -716,7 +725,7 @@ function ChatView({
const r = await api.chatUpload("session", `conv-${conv.id}`, files);
setAttachments((prev) => [...prev, ...r.attachments]);
} catch (e) {
toast.error("Upload failed: " + (e as Error).message);
toast.error(t("Upload failed: {error}", { error: (e as Error).message }));
} finally {
setUploading(false);
}
@@ -736,7 +745,7 @@ function ChatView({
// fetch avoids racing a separate post-send request against the poller.
setRunning(true);
} catch (e) {
toast.error("Send failed: " + (e as Error).message);
toast.error(t("Send failed: {error}", { error: (e as Error).message }));
setInput(msg); // restore so the user doesn't lose their text
setAttachments(atts); // and their attachments
} finally {
@@ -753,7 +762,7 @@ function ChatView({
try {
await api.stopConversation(conv.id);
} catch (e) {
toast.error("Stop failed: " + (e as Error).message);
toast.error(t("Stop failed: {error}", { error: (e as Error).message }));
} finally {
setStopping(false);
}
@@ -768,7 +777,7 @@ function ChatView({
<span className="text-muted-foreground hidden shrink-0 font-mono text-xs sm:inline">{conv.agent_key}</span>
{agent && !agent.builtin && (
<Badge variant="outline" className="shrink-0 px-1.5 py-0 text-[10px]">
Custom
{t("Custom")}
</Badge>
)}
{agent?.description && (
@@ -778,13 +787,17 @@ function ChatView({
<SideQuestionButton side={side} />
<div className="text-muted-foreground ml-auto flex min-w-0 max-w-full items-center justify-end gap-x-3 gap-y-1 text-xs max-sm:w-full max-sm:flex-wrap">
{tokenTotal.turns > 0 && (
<span title="Agent loop turns (model calls)" className="tabular-nums">
{tokenTotal.turns} turns
<span title={t("Agent loop turns (model calls)")} className="tabular-nums">
{t("{count} turns", { count: tokenTotal.turns })}
</span>
)}
{tokenTotal.any && (
<span title="input / cache(read) / output tokens" className="min-w-0 truncate tabular-nums">
input {fmtTokens(tokenTotal.i)} · cache {fmtTokens(tokenTotal.cr)} · output {fmtTokens(tokenTotal.o)}
<span title={t("input / cache(read) / output tokens")} className="min-w-0 truncate tabular-nums">
{t("input {input} · cache {cache} · output {output}", {
input: fmtTokens(tokenTotal.i),
cache: fmtTokens(tokenTotal.cr),
output: fmtTokens(tokenTotal.o),
})}
</span>
)}
</div>
@@ -797,12 +810,12 @@ function ChatView({
<div className="min-w-0 max-w-full px-4 py-3" ref={contentRef}>
{messages.length === 0 && !running ? (
<div className="text-muted-foreground py-10 text-center text-sm">
Start a conversation with "{agent?.name ?? conv.agent_key}"
{t('Start a conversation with "{name}"', { name: agent?.name ?? conv.agent_key })}
</div>
) : (
<>
{hasMore && (
<div className="text-muted-foreground/70 pb-2 text-center text-[11px]">Scroll up to load earlier messages…</div>
<div className="text-muted-foreground/70 pb-2 text-center text-[11px]">{t("Scroll up to load earlier messages…")}</div>
)}
<Transcript activity={messages} live={running} chat fetchDetail={fetchDetail} focusedSeq={focusHistory.ready ? approvalFocus.state?.source?.seq : undefined} />
</>
@@ -816,7 +829,11 @@ function ChatView({
onSend={send}
disabled={running || sending}
allowBtw
placeholder={running ? "Agent is replying; type /btw to ask a side question…" : "Type a message, @ to reference records, Enter to send"}
placeholder={
running
? t("Agent is replying; type /btw to ask a side question…")
: t("Type a message, @ to reference records, Enter to send")
}
running={running}
onStop={stop}
stopDisabled={stopping}
@@ -897,7 +914,7 @@ const ConversationItem = React.memo(function ConversationItem({
<Checkbox
checked={selectedForDelete}
onCheckedChange={(checked) => onSelectedForDeleteChange(conv.id, checked === true)}
aria-label={`Select conversation "${conv.title || "New conversation"}"`}
aria-label={t('Select conversation "{title}"', { title: conv.title || t("New conversation") })}
className="ml-1 shrink-0"
/>
)}
@@ -924,16 +941,16 @@ const ConversationItem = React.memo(function ConversationItem({
type="button"
onClick={() => onSelect(conv.id)}
onDoubleClick={() => onStartRename(conv)}
title="Double-click to rename"
title={t("Double-click to rename")}
className="min-w-0 flex-1 rounded-md px-2 py-1.5 text-left"
>
<div className="flex min-w-0 items-center gap-1.5">
{pinned && <PinIcon className="text-primary size-3 shrink-0" aria-label="Pinned" />}
<div className="truncate text-sm">{conv.title || "New conversation"}</div>
{pinned && <PinIcon className="text-primary size-3 shrink-0" aria-label={t("Pinned")} />}
<div className="truncate text-sm">{conv.title || t("New conversation")}</div>
{conv.running ? (
<Badge variant="secondary" className="shrink-0 gap-1" title="Agent is running">
<Badge variant="secondary" className="shrink-0 gap-1" title={t("Agent is running")}>
<Spinner className="size-3" aria-hidden="true" />
Running
{t("Running")}
</Badge>
) : null}
</div>
@@ -946,7 +963,7 @@ const ConversationItem = React.memo(function ConversationItem({
</>
)}
<span className="shrink-0">
{new Date(conv.created_at).toLocaleDateString("zh-CN", {
{new Date(conv.created_at).toLocaleDateString(intlLocale, {
month: "numeric",
day: "numeric",
hour: "2-digit",
@@ -963,7 +980,7 @@ const ConversationItem = React.memo(function ConversationItem({
variant="ghost"
size="icon-sm"
className="text-muted-foreground shrink-0"
aria-label={`Manage conversation "${conv.title || "New conversation"}"`}
aria-label={t('Manage conversation "{title}"', { title: conv.title || t("New conversation") })}
>
<MoreHorizontalIcon />
</Button>
@@ -972,18 +989,18 @@ const ConversationItem = React.memo(function ConversationItem({
<DropdownMenuGroup>
<DropdownMenuItem onSelect={() => onStartRename(conv)}>
<PencilIcon />
Rename
{t("Rename")}
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => onTogglePinned(conv)}>
{pinned ? <PinOffIcon /> : <PinIcon />}
{pinned ? "Unpin" : "Pin"}
{pinned ? t("Unpin") : t("Pin")}
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem variant="destructive" onSelect={() => setDeleteOpen(true)}>
<Trash2Icon />
Delete
{t("Delete")}
</DropdownMenuItem>
</DropdownMenuGroup>
</DropdownMenuContent>
@@ -991,12 +1008,14 @@ const ConversationItem = React.memo(function ConversationItem({
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete conversation "{conv.title || "New conversation"}"?</AlertDialogTitle>
<AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
<AlertDialogTitle>
{t('Delete conversation "{title}"?', { title: conv.title || t("New conversation") })}
</AlertDialogTitle>
<AlertDialogDescription>{t("This action cannot be undone.")}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => onDelete(conv.id)}>Delete</AlertDialogAction>
<AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={() => onDelete(conv.id)}>{t("Delete")}</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
@@ -1022,7 +1041,7 @@ function AgentGroupHeader({
type="button"
onClick={() => onToggle(group.key)}
aria-expanded={!collapsed}
title={collapsed ? `Expand "${group.name}"` : `Collapse "${group.name}"`}
title={collapsed ? t('Expand "{name}"', { name: group.name }) : t('Collapse "{name}"', { name: group.name })}
className={cn(
"sticky top-0 z-10 flex min-w-0 items-center gap-1.5 rounded-md bg-card px-1.5 py-1 text-left font-medium text-[11px] transition-colors hover:bg-accent/50",
collapsed && hasActive ? "text-foreground" : "text-muted-foreground",
@@ -1032,10 +1051,10 @@ function AgentGroupHeader({
<Bot className="size-3 shrink-0" />
<span className="min-w-0 flex-1 truncate">{group.name}</span>
{collapsed && hasActive && (
<span className="size-1.5 shrink-0 rounded-full bg-primary" title="The current conversation is in this group" />
<span className="size-1.5 shrink-0 rounded-full bg-primary" title={t("The current conversation is in this group")} />
)}
{group.runningCount > 0 && (
<Spinner className="size-3 shrink-0" aria-label={`${group.runningCount} conversations running`} />
<Spinner className="size-3 shrink-0" aria-label={t("{count} conversations running", { count: group.runningCount })} />
)}
<span className="shrink-0 tabular-nums opacity-60">{group.conversations.length}</span>
</button>
@@ -1211,10 +1230,10 @@ export default function ChatPage() {
if (agentFilter !== null) keys.add(agentFilter);
return [...keys]
.map((key) => ({ key, name: agentByKey.get(key)?.name || key, count: counts.get(key) ?? 0 }))
.sort((a, b) => a.name.localeCompare(b.name, "zh-CN"));
.sort((a, b) => a.name.localeCompare(b.name, intlLocale));
}, [convs, chatAgents, agentByKey, agentFilter]);
const conversationCountLabel =
agentFilter === null ? `${convs.length} total` : `${filteredConversations.length} / ${convs.length}`;
agentFilter === null ? t("{count} total", { count: convs.length }) : `${filteredConversations.length} / ${convs.length}`;
function changeAgentFilter(key: string | null) {
setAgentFilter(key);
@@ -1265,7 +1284,7 @@ export default function ChatPage() {
});
void reloadConvs();
} catch (e) {
toast.error("Delete failed: " + (e as Error).message);
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
}
},
[reloadConvs],
@@ -1282,7 +1301,7 @@ export default function ChatPage() {
const result = await api.deleteConversations(ids.slice(offset, offset + 100));
for (const item of result.items) {
if (item.ok) deleted.add(item.id);
else failed.push({ id: item.id, error: item.error ?? "conversation not found" });
else failed.push({ id: item.id, error: item.error ?? t("conversation not found") });
}
}
if (deleted.has(selectedId ?? -1)) selectConversation(null);
@@ -1291,13 +1310,18 @@ export default function ChatPage() {
for (const id of deleted) next.delete(id);
return next;
});
if (deleted.size > 0) toast.success(`Deleted ${deleted.size} conversations`);
if (deleted.size > 0) toast.success(t("Deleted {count} conversations", { count: deleted.size }));
if (failed.length > 0) {
const details = failed
.slice(0, 3)
.map((item) => `#${item.id} (${item.error})`)
.join("; ");
toast.error(`Failed to delete ${failed.length} conversations: ${details}${failed.length > 3 ? " etc." : ""}`);
toast.error(
t("Failed to delete {count} conversations: {details}", {
count: failed.length,
details: failed.length > 3 ? t("{items} etc.", { items: details }) : details,
}),
);
}
setBulkDeleteOpen(false);
// Fully successful → return to the clean list; keep selection mode on if
@@ -1305,7 +1329,7 @@ export default function ChatPage() {
if (failed.length === 0) setSelectionMode(false);
void reloadConvs();
} catch (error) {
toast.error(`Bulk delete failed: ${(error as Error).message}`);
toast.error(t("Bulk delete failed: {error}", { error: (error as Error).message }));
void reloadConvs();
} finally {
setBulkDeleting(false);
@@ -1319,7 +1343,8 @@ export default function ChatPage() {
await api.pinConversation(conversation.id, !pinned);
void reloadConvs();
} catch (e) {
toast.error(`Failed to ${pinned ? "unpin" : "pin"}: ${(e as Error).message}`);
const error = (e as Error).message;
toast.error(pinned ? t("Failed to unpin: {error}", { error }) : t("Failed to pin: {error}", { error }));
}
},
[reloadConvs],
@@ -1338,7 +1363,7 @@ export default function ChatPage() {
await api.renameConversation(id, title);
void reloadConvs();
} catch (e) {
toast.error("Rename failed: " + (e as Error).message);
toast.error(t("Rename failed: {error}", { error: (e as Error).message }));
}
},
[reloadConvs],
@@ -1355,20 +1380,20 @@ export default function ChatPage() {
<div className="bg-card flex flex-col overflow-hidden rounded-lg border">
<div className="flex flex-col gap-2 border-b p-2">
<Button size="sm" className="w-full" onClick={() => selectConversation(null)}>
<PlusIcon /> New conversation
<PlusIcon /> {t("New conversation")}
</Button>
<Select
value={agentFilter === null ? "all" : `agent:${agentFilter}`}
onValueChange={(value) => changeAgentFilter(value === "all" ? null : value.slice(6))}
disabled={bulkDeleting}
>
<SelectTrigger size="sm" className="w-full min-w-0" aria-label="Filter conversations by agent">
<SelectTrigger size="sm" className="w-full min-w-0" aria-label={t("Filter conversations by agent")}>
<Bot />
<SelectValue placeholder="All agents" />
<SelectValue placeholder={t("All agents")} />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="all">All agents</SelectItem>
<SelectItem value="all">{t("All agents")}</SelectItem>
{agentFilterOptions.map((agent) => (
<SelectItem key={agent.key} value={`agent:${agent.key}`}>
{agent.name} ({agent.count})
@@ -1383,11 +1408,13 @@ export default function ChatPage() {
<Checkbox
checked={conversationHeaderChecked}
onCheckedChange={(checked) => toggleAllConversations(checked === true)}
aria-label="Select all conversations matching the current filter"
aria-label={t("Select all conversations matching the current filter")}
disabled={filteredConversations.length === 0 || bulkDeleting}
/>
<span className="text-muted-foreground min-w-0 flex-1 text-xs tabular-nums">
{selectedConversationCount > 0 ? `${selectedConversationCount} selected` : conversationCountLabel}
{selectedConversationCount > 0
? t("{count} selected", { count: selectedConversationCount })
: conversationCountLabel}
</span>
{selectedConversationCount > 0 && (
<Button
@@ -1397,11 +1424,11 @@ export default function ChatPage() {
onClick={() => setBulkDeleteOpen(true)}
>
<Trash2Icon data-icon="inline-start" />
Delete
{t("Delete")}
</Button>
)}
<Button size="sm" variant="ghost" onClick={exitSelectionMode}>
Done
{t("Done")}
</Button>
</div>
) : (
@@ -1417,7 +1444,7 @@ export default function ChatPage() {
disabled={filteredConversations.length === 0}
>
<ListChecksIcon data-icon="inline-start" />
Select
{t("Select")}
</Button>
</div>
))}
@@ -1430,7 +1457,7 @@ export default function ChatPage() {
<div className="flex min-w-0 flex-col gap-0.5 p-2">
{filteredConversations.length === 0 && (
<p className="text-muted-foreground px-2 py-6 text-center text-xs">
{agentFilter === null ? "No conversations yet" : "No conversations for this agent"}
{agentFilter === null ? t("No conversations yet") : t("No conversations for this agent")}
</p>
)}
{pinnedConversations.map((c) => (
@@ -1496,7 +1523,7 @@ export default function ChatPage() {
className="mt-1 w-full"
onClick={() => setVisibleConversationCount((count) => count + CONVERSATION_LIST_PAGE)}
>
Load more
{t("Load more")}
</Button>
)}
</div>
@@ -1517,7 +1544,7 @@ export default function ChatPage() {
/>
) : sourceRequested ? (
<div role="status" className="p-6 text-sm text-muted-foreground">
{convsLoaded ? "The conversation has been deleted" : "Loading the conversation…"}
{convsLoaded ? t("The conversation has been deleted") : t("Loading the conversation…")}
</div>
) : (
<DraftChat
@@ -1545,11 +1572,15 @@ export default function ChatPage() {
<AlertDialog open={bulkDeleteOpen} onOpenChange={setBulkDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {selectedConversationCount} selected conversations?</AlertDialogTitle>
<AlertDialogDescription>Conversation messages and execution records will be deleted with them. This action cannot be undone.</AlertDialogDescription>
<AlertDialogTitle>
{t("Delete {count} selected conversations?", { count: selectedConversationCount })}
</AlertDialogTitle>
<AlertDialogDescription>
{t("Conversation messages and execution records will be deleted with them. This action cannot be undone.")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={bulkDeleting}>Cancel</AlertDialogCancel>
<AlertDialogCancel disabled={bulkDeleting}>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
disabled={bulkDeleting || selectedConversationCount === 0}
@@ -1559,7 +1590,7 @@ export default function ChatPage() {
}}
>
{bulkDeleting && <Loader2Icon data-icon="inline-start" className="animate-spin" />}
{bulkDeleting ? "Deleting" : "Confirm delete"}
{bulkDeleting ? t("Deleting") : t("Confirm delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
+105 -85
View File
@@ -40,14 +40,15 @@ import type {
UsageStats,
} from "@/lib/types";
import { cn } from "@/lib/utils";
import { t } from "@/i18n";
import { setVisibleInterval } from "@/lib/polling";
// ── chart constants ───────────────────────────────────────────────────────────
const dailyTrendConfig = {
input: { label: "Input", color: "hsl(217 91% 60%)" },
output: { label: "Output", color: "hsl(263 70% 60%)" },
cacheRead: { label: "Cache read", color: "hsl(160 60% 45%)" },
input: { label: t("Input"), color: "hsl(217 91% 60%)" },
output: { label: t("Output"), color: "hsl(263 70% 60%)" },
cacheRead: { label: t("Cache read"), color: "hsl(160 60% 45%)" },
} satisfies ChartConfig;
// ── helpers ──────────────────────────────────────────────────────────────────
@@ -56,12 +57,12 @@ function fmtRel(ts?: string | number): string {
if (!ts) return "—";
const ms = Date.now() - (typeof ts === "number" ? ts * 1000 : Date.parse(ts as string));
const s = Math.floor(ms / 1000);
if (s < 60) return `${s}s ago`;
if (s < 60) return t("{n}s ago", { n: s });
const m = Math.floor(s / 60);
if (m < 60) return `${m}m ago`;
if (m < 60) return t("{n}m ago", { n: m });
const h = Math.floor(m / 60);
if (h < 24) return `${h}h ago`;
return `${Math.floor(h / 24)}d ago`;
if (h < 24) return t("{n}h ago", { n: h });
return t("{n}d ago", { n: Math.floor(h / 24) });
}
function fmtTokens(n: number): string {
@@ -71,12 +72,12 @@ function fmtTokens(n: number): string {
}
const ASSET_TYPE_LABELS: Record<string, string> = {
root_domain: "Root domain",
root_domain: t("Root domain"),
ip: "IP",
subdomain: "Subdomain",
app: "App",
service: "Service",
endpoint: "Endpoint",
subdomain: t("Subdomain"),
app: t("App"),
service: t("Service"),
endpoint: t("Endpoint"),
};
const ASSET_COLORS: Record<string, string> = {
@@ -473,9 +474,9 @@ export default function DashboardPage() {
// activity kind label
function kindLabel(a: Activity): string {
if (a.kind === "tool_use") return a.tool ?? "tool_use";
if (a.kind === "tool_result") return "tool_result";
return a.kind;
if (a.kind === "tool_use") return a.tool ?? t("tool_use");
if (a.kind === "tool_result") return t("tool_result");
return t(a.kind);
}
function workerColor(w: string): string {
@@ -497,8 +498,8 @@ export default function DashboardPage() {
{/* ── Header ── */}
<div>
<div>
<h1 className="text-lg font-semibold tracking-tight">Overview</h1>
<p className="text-xs text-muted-foreground">System-wide status · live refresh</p>
<h1 className="text-lg font-semibold tracking-tight">{t("Overview")}</h1>
<p className="text-xs text-muted-foreground">{t("System-wide status · live refresh")}</p>
</div>
</div>
@@ -508,7 +509,7 @@ export default function DashboardPage() {
<Card className="gap-1">
<CardHeader className="pb-0">
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
<TargetIcon className="size-3" /> Active tasks
<TargetIcon className="size-3" /> {t("Active tasks")}
</div>
<div className="flex items-baseline gap-1.5">
<span className="text-2xl font-semibold tabular-nums">{tasksByStatus.running ?? 0}</span>
@@ -516,10 +517,16 @@ export default function DashboardPage() {
</div>
</CardHeader>
<CardContent className="flex flex-wrap gap-x-2.5 gap-y-0.5 text-[10px]">
{(tasksByStatus.running ?? 0) > 0 && <span className="text-blue-400">Exploring {tasksByStatus.running}</span>}
{(tasksByStatus.paused ?? 0) > 0 && <span className="text-amber-400">Paused {tasksByStatus.paused}</span>}
{(tasksByStatus.done ?? 0) > 0 && <span className="text-emerald-400">Completed {tasksByStatus.done}</span>}
{tasks.length === 0 && <span className="text-muted-foreground">No tasks</span>}
{(tasksByStatus.running ?? 0) > 0 && (
<span className="text-blue-400">{t("Exploring {count}", { count: tasksByStatus.running })}</span>
)}
{(tasksByStatus.paused ?? 0) > 0 && (
<span className="text-amber-400">{t("Paused {count}", { count: tasksByStatus.paused })}</span>
)}
{(tasksByStatus.done ?? 0) > 0 && (
<span className="text-emerald-400">{t("Completed {count}", { count: tasksByStatus.done })}</span>
)}
{tasks.length === 0 && <span className="text-muted-foreground">{t("No tasks")}</span>}
</CardContent>
</Card>
@@ -527,15 +534,15 @@ export default function DashboardPage() {
<Card className="gap-1">
<CardHeader className="pb-0">
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
<BugIcon className="size-3" /> Confirmed findings
<BugIcon className="size-3" /> {t("Confirmed findings")}
</div>
<div className="text-2xl font-semibold tabular-nums">{findings.length}</div>
</CardHeader>
<CardContent className="flex flex-wrap gap-2.5 text-[10px]">
<span className="text-rose-500">Critical {findingsBySev.critical}</span>
<span className="text-red-400">High {findingsBySev.high}</span>
<span className="text-amber-400">Medium {findingsBySev.medium}</span>
<span className="text-slate-400">Low {findingsBySev.low}</span>
<span className="text-rose-500">{t("Critical {count}", { count: findingsBySev.critical })}</span>
<span className="text-red-400">{t("High {count}", { count: findingsBySev.high })}</span>
<span className="text-amber-400">{t("Medium {count}", { count: findingsBySev.medium })}</span>
<span className="text-slate-400">{t("Low {count}", { count: findingsBySev.low })}</span>
</CardContent>
</Card>
@@ -543,18 +550,18 @@ export default function DashboardPage() {
<Card className="gap-1">
<CardHeader className="pb-0">
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
<NetworkIcon className="size-3" /> Asset nodes
<NetworkIcon className="size-3" /> {t("Asset nodes")}
</div>
<div className="text-2xl font-semibold tabular-nums">{totalAssets}</div>
</CardHeader>
<CardContent className="text-[10px] text-muted-foreground">Shared across tasks</CardContent>
<CardContent className="text-[10px] text-muted-foreground">{t("Shared across tasks")}</CardContent>
</Card>
{/* Traffic exchanges */}
<Card className="gap-1">
<CardHeader className="pb-0">
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
<ActivityIcon className="size-3" /> Traffic exchanges
<ActivityIcon className="size-3" /> {t("Traffic exchanges")}
</div>
<div className="text-2xl font-semibold tabular-nums">{traffic.length}</div>
</CardHeader>
@@ -562,10 +569,10 @@ export default function DashboardPage() {
{settings?.traffic_capture ? (
<>
<LiveDot />
<span>Recording</span>
<span>{t("Recording")}</span>
</>
) : (
<span>Capture is off</span>
<span>{t("Capture is off")}</span>
)}
</CardContent>
</Card>
@@ -574,15 +581,18 @@ export default function DashboardPage() {
<Card className="gap-1">
<CardHeader className="pb-0">
<div className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
<ZapIcon className="size-3" /> Token usage
<ZapIcon className="size-3" /> {t("Token usage")}
</div>
<div className="text-2xl font-semibold tabular-nums">
{fmtTokens(displayedTokens.input + displayedTokens.output) || "—"}
</div>
</CardHeader>
<CardContent className="text-[10px] text-muted-foreground">
In {fmtTokens(displayedTokens.input)} (incl. cache {fmtTokens(displayedTokens.cacheRead)}) · Out{" "}
{fmtTokens(displayedTokens.output)}
{t("In {input} (incl. cache {cache}) · Out {output}", {
input: fmtTokens(displayedTokens.input),
cache: fmtTokens(displayedTokens.cacheRead),
output: fmtTokens(displayedTokens.output),
})}
</CardContent>
</Card>
</div>
@@ -593,13 +603,13 @@ export default function DashboardPage() {
<div className="mb-4 flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-1.5 text-xs font-semibold">
<ZapIcon className="size-3.5 text-muted-foreground" />
LLM token usage
{t("LLM token usage")}
{/* Data source toggle: old = activity stats (includes historical tasks), new = the llm_usage metering ledger (more accurate, only covers data since it was enabled) */}
<div className="ml-1 flex gap-0.5 rounded-md border bg-muted/30 p-0.5">
{(
[
{ v: "old", label: "Old" },
{ v: "new", label: "New" },
{ v: "old", label: t("Old") },
{ v: "new", label: t("New") },
] as const
).map(({ v, label }) => (
<button
@@ -608,8 +618,12 @@ export default function DashboardPage() {
onClick={() => setTokenVersion(v)}
title={
v === "new"
? "New: from the llm_usage metering ledger, exact per call and including aborted runs; only covers data since it was enabled"
: "Old: from activity stats (includes historical tasks); aborted runs are not counted and it cannot break down by model"
? t(
"New: from the llm_usage metering ledger, exact per call and including aborted runs; only covers data since it was enabled",
)
: t(
"Old: from activity stats (includes historical tasks); aborted runs are not counted and it cannot break down by model",
)
}
className={cn(
"rounded px-2 py-0.5 text-[9px] font-medium transition-colors",
@@ -638,7 +652,7 @@ export default function DashboardPage() {
: "bg-muted/30 text-muted-foreground hover:text-foreground",
)}
>
All
{t("All")}
</button>
{llmProfiles.map((p) => {
const key = Number(p.id);
@@ -667,7 +681,7 @@ export default function DashboardPage() {
: "bg-emerald-500/20 text-emerald-400",
)}
>
Default
{t("Default")}
</span>
)}
</button>
@@ -682,11 +696,13 @@ export default function DashboardPage() {
<div className="flex flex-col gap-4">
{/* Total */}
<div>
<div className="text-[10px] text-muted-foreground">Total (input+output)</div>
<div className="text-[10px] text-muted-foreground">{t("Total (input+output)")}</div>
<div className="mt-0.5 text-3xl font-bold tabular-nums tracking-tight">
{fmtTokens(displayedTokens.input + displayedTokens.output) || "—"}
</div>
<div className="mt-0.5 text-[10px] text-muted-foreground">{displayedTokens.taskCount} tasks</div>
<div className="mt-0.5 text-[10px] text-muted-foreground">
{t("{count} tasks", { count: displayedTokens.taskCount })}
</div>
</div>
{/* Per-type bars */}
@@ -696,19 +712,19 @@ export default function DashboardPage() {
const total = displayedTokens.input + displayedTokens.output;
return [
{
label: "Input (uncached)",
label: t("Input (uncached)"),
value: displayedTokens.input - displayedTokens.cacheRead,
barColor: dailyTrendConfig.input.color!,
text: "text-blue-400",
},
{
label: "Cache hits",
label: t("Cache hits"),
value: displayedTokens.cacheRead,
barColor: dailyTrendConfig.cacheRead.color!,
text: "text-emerald-400",
},
{
label: "Output",
label: t("Output"),
value: displayedTokens.output,
barColor: dailyTrendConfig.output.color!,
text: "text-violet-400",
@@ -740,7 +756,7 @@ export default function DashboardPage() {
const hitPct = denominator > 0 ? Math.round((displayedTokens.cacheRead / denominator) * 100) : 0;
return (
<div className="flex items-center justify-between rounded-lg border bg-muted/20 px-3 py-2 text-[10px]">
<span className="text-muted-foreground">Cache hit rate</span>
<span className="text-muted-foreground">{t("Cache hit rate")}</span>
<span
className={cn("font-semibold tabular-nums", hitPct > 50 ? "text-emerald-400" : "text-amber-400")}
>
@@ -768,11 +784,11 @@ export default function DashboardPage() {
<div className="flex gap-0.5 rounded-md border bg-muted/30 p-0.5">
{(
[
{ days: 7, label: "7d" },
{ days: 30, label: "30d" },
{ days: 90, label: "3mo" },
{ days: 180, label: "6mo" },
{ days: 365, label: "1y" },
{ days: 7, label: t("7d") },
{ days: 30, label: t("30d") },
{ days: 90, label: t("3mo") },
{ days: 180, label: t("6mo") },
{ days: 365, label: t("1y") },
] as const
).map(({ days, label }) => (
<button
@@ -797,7 +813,7 @@ export default function DashboardPage() {
className="flex flex-1 items-center justify-center rounded-lg border bg-muted/10 text-xs text-muted-foreground"
style={{ minHeight: 180 }}
>
No data
{t("No data")}
</div>
) : (
<ChartContainer config={dailyTrendConfig} className="h-[200px] w-full">
@@ -852,17 +868,17 @@ export default function DashboardPage() {
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-1.5 text-xs font-semibold">
<ActivityIcon className="size-3.5 text-muted-foreground" />
Activity feed
{t("Activity feed")}
</div>
<div className="flex items-center gap-2">
<span className="text-[10px] text-muted-foreground">
{activity.filter((a) => a.kind !== "usage").length} events
{t("{count} events", { count: activity.filter((a) => a.kind !== "usage").length })}
</span>
<Link
href="/function/tasks"
className="flex items-center gap-0.5 text-[10px] text-muted-foreground hover:text-foreground"
>
View tasks <ArrowUpRightIcon className="size-3" />
{t("View tasks")} <ArrowUpRightIcon className="size-3" />
</Link>
</div>
</div>
@@ -873,7 +889,7 @@ export default function DashboardPage() {
if (count === 0) return null;
return (
<span key={kind} className="rounded border bg-muted/20 px-1.5 py-0.5 text-[9px] text-muted-foreground">
{kind} <strong className="text-foreground/70">{count}</strong>
{t(kind)} <strong className="text-foreground/70">{count}</strong>
</span>
);
})}
@@ -881,7 +897,7 @@ export default function DashboardPage() {
<div className="divide-y">
{recentActivity.length === 0 ? (
<div className="py-4 text-center text-xs text-muted-foreground">No activity records</div>
<div className="py-4 text-center text-xs text-muted-foreground">{t("No activity records")}</div>
) : (
recentActivity.map((a) => (
<div key={a.seq} className="flex gap-2.5 py-2">
@@ -899,7 +915,7 @@ export default function DashboardPage() {
</div>
<div className="shrink-0 text-right">
<Badge variant="outline" className="px-1.5 py-0 text-[9px] text-muted-foreground">
{a.kind}
{t(a.kind)}
</Badge>
<div className="mt-0.5 text-[9px] tabular-nums text-muted-foreground">{fmtRel(a.ts)}</div>
</div>
@@ -914,19 +930,19 @@ export default function DashboardPage() {
<div className="mb-3 flex items-center justify-between">
<div className="flex items-center gap-1.5 text-xs font-semibold">
<BugIcon className="size-3.5 text-muted-foreground" />
Findings
{t("Findings")}
</div>
<Link
href="/function/findings"
className="flex items-center gap-0.5 text-[10px] text-muted-foreground hover:text-foreground"
>
All <ArrowUpRightIcon className="size-3" />
{t("All")} <ArrowUpRightIcon className="size-3" />
</Link>
</div>
<div className="divide-y">
{recentFindings.length === 0 ? (
<div className="py-4 text-center text-xs text-muted-foreground">No findings</div>
<div className="py-4 text-center text-xs text-muted-foreground">{t("No findings")}</div>
) : (
recentFindings.map((f) => (
<div key={f.id} className="flex items-start gap-2 py-2">
@@ -959,15 +975,15 @@ export default function DashboardPage() {
<div className="flex items-center justify-between border-b px-4 py-3">
<div className="flex items-center gap-1.5 text-xs font-semibold">
<ClockIcon className="size-3.5 text-muted-foreground" />
Tasks
{t("Tasks")}
</div>
<div className="flex items-center gap-2">
<span className="text-[10px] text-muted-foreground">{tasks.length} tasks</span>
<span className="text-[10px] text-muted-foreground">{t("{count} tasks", { count: tasks.length })}</span>
<Link
href="/function/tasks"
className="flex items-center gap-0.5 text-[10px] text-muted-foreground hover:text-foreground"
>
All <ArrowUpRightIcon className="size-3" />
{t("All")} <ArrowUpRightIcon className="size-3" />
</Link>
</div>
</div>
@@ -979,7 +995,7 @@ export default function DashboardPage() {
key={h}
className="px-4 py-2 text-left text-[9px] font-semibold uppercase tracking-widest text-muted-foreground first:pl-4"
>
{h}
{t(h)}
</th>
))}
</tr>
@@ -988,7 +1004,7 @@ export default function DashboardPage() {
{sortedTasks.length === 0 ? (
<tr>
<td colSpan={6} className="px-4 py-6 text-center text-xs text-muted-foreground">
No tasks
{t("No tasks")}
</td>
</tr>
) : (
@@ -1046,12 +1062,12 @@ export default function DashboardPage() {
<div className="grid grid-cols-1 gap-3 lg:grid-cols-3">
{/* Asset distribution */}
<Card className="p-4">
<SectionTitle icon={NetworkIcon} sub="By type">
Asset distribution
<SectionTitle icon={NetworkIcon} sub={t("By type")}>
{t("Asset distribution")}
</SectionTitle>
{assetByType.length === 0 ? (
<div className="py-6 text-center text-xs text-muted-foreground">No asset data</div>
<div className="py-6 text-center text-xs text-muted-foreground">{t("No asset data")}</div>
) : (
<div className="flex flex-col gap-2">
{assetByType.map(([type, count]) => (
@@ -1071,18 +1087,20 @@ export default function DashboardPage() {
</div>
)}
<div className="mt-3 border-t pt-3 text-[10px] text-muted-foreground">{totalAssets} nodes in total</div>
<div className="mt-3 border-t pt-3 text-[10px] text-muted-foreground">
{t("{count} nodes in total", { count: totalAssets })}
</div>
</Card>
{/* Traffic status codes */}
<Card className="p-4">
<SectionTitle icon={ActivityIcon} sub={`${traffic.length} requests`}>
Traffic status codes
<SectionTitle icon={ActivityIcon} sub={t("{count} requests", { count: traffic.length })}>
{t("Traffic status codes")}
</SectionTitle>
{/* bar chart */}
{trafficByCodes.length === 0 ? (
<div className="py-6 text-center text-xs text-muted-foreground">No traffic data</div>
<div className="py-6 text-center text-xs text-muted-foreground">{t("No traffic data")}</div>
) : (
<>
<div className="mb-3 flex items-end gap-2" style={{ height: 52 }}>
@@ -1099,7 +1117,7 @@ export default function DashboardPage() {
</div>
<div className="border-t pt-2.5">
<div className="mb-1.5 text-[10px] text-muted-foreground">Recent requests</div>
<div className="mb-1.5 text-[10px] text-muted-foreground">{t("Recent requests")}</div>
<div className="flex flex-col gap-1.5">
{recentTraffic.map((e) => (
<div key={e.id} className="flex items-center gap-1.5 text-[10px]">
@@ -1128,11 +1146,11 @@ export default function DashboardPage() {
{/* System status & pending approvals */}
<Card className="p-4">
<SectionTitle icon={ShieldCheckIcon}>System status</SectionTitle>
<SectionTitle icon={ShieldCheckIcon}>{t("System status")}</SectionTitle>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between rounded-lg border bg-muted/20 px-3 py-2">
<div className="text-[10px] text-muted-foreground">LLM config</div>
<div className="text-[10px] text-muted-foreground">{t("LLM config")}</div>
<Badge
variant="outline"
className={cn(
@@ -1142,12 +1160,12 @@ export default function DashboardPage() {
: "border-red-500/30 bg-red-500/10 text-red-400",
)}
>
{stats?.llm_configured ? "Configured" : "Not configured"}
{stats?.llm_configured ? t("Configured") : t("Not configured")}
</Badge>
</div>
<div className="flex items-center justify-between rounded-lg border bg-muted/20 px-3 py-2">
<div className="text-[10px] text-muted-foreground">Traffic capture</div>
<div className="text-[10px] text-muted-foreground">{t("Traffic capture")}</div>
<Badge
variant="outline"
className={cn(
@@ -1157,13 +1175,13 @@ export default function DashboardPage() {
: "text-muted-foreground",
)}
>
{settings?.traffic_capture ? "On" : "Off"}
{settings?.traffic_capture ? t("On") : t("Off")}
</Badge>
</div>
{activeProfile && (
<div className="flex items-center justify-between rounded-lg border bg-muted/20 px-3 py-2">
<div className="text-[10px] text-muted-foreground">Active model</div>
<div className="text-[10px] text-muted-foreground">{t("Active model")}</div>
<span className="font-mono text-[10px]">{activeProfile.model}</span>
</div>
)}
@@ -1172,7 +1190,9 @@ export default function DashboardPage() {
{/* pending approvals */}
{pendingCount > 0 && (
<div className="mt-3">
<div className="mb-1.5 text-[10px] font-medium text-amber-400">Pending approvals ({pendingCount})</div>
<div className="mb-1.5 text-[10px] font-medium text-amber-400">
{t("Pending approvals ({count})", { count: pendingCount })}
</div>
<div className="flex flex-col gap-1.5">
{pending.slice(0, 3).map((p) => (
<Link
@@ -1192,7 +1212,7 @@ export default function DashboardPage() {
href="/system/intercept/approvals"
className="text-center text-[10px] text-muted-foreground hover:text-foreground"
>
{pendingCount - 3} more…
{t("{count} more…", { count: pendingCount - 3 })}
</Link>
)}
</div>
@@ -1202,7 +1222,7 @@ export default function DashboardPage() {
{pendingCount === 0 && (
<div className="mt-3 rounded-lg border bg-muted/10 px-3 py-3 text-center text-[10px] text-muted-foreground">
<ShieldCheckIcon className="mx-auto mb-1 size-4 text-emerald-500/50" />
No pending interception approvals
{t("No pending interception approvals")}
</div>
)}
</Card>
+102 -81
View File
@@ -63,6 +63,7 @@ import { parseCompanyScopeText } from "@/lib/company-scope";
import { httpHref } from "@/lib/http-href";
import type { Asset, Company, CompanyScopeRule } from "@/lib/types";
import { cn } from "@/lib/utils";
import { t } from "@/i18n";
const METHOD_COLOR: Record<string, string> = {
GET: "bg-emerald-100 text-emerald-700",
@@ -99,13 +100,13 @@ function statusTone(code: number) {
const PAGE_SIZES = [25, 50, 100, 200];
const TABS: { key: string; label: string; icon: LucideIcon }[] = [
{ key: "company", label: "Companies", icon: BuildingIcon },
{ key: "root_domain", label: "Root domains", icon: GlobeIcon },
{ key: "company", label: t("Companies"), icon: BuildingIcon },
{ key: "root_domain", label: t("Root domains"), icon: GlobeIcon },
{ key: "ip", label: "IP", icon: NetworkIcon },
{ key: "subdomain", label: "Subdomains", icon: GlobeIcon },
{ key: "app", label: "Apps", icon: SmartphoneIcon },
{ key: "service", label: "Services", icon: LayoutTemplateIcon },
{ key: "endpoint", label: "Endpoints", icon: LinkIcon },
{ key: "subdomain", label: t("Subdomains"), icon: GlobeIcon },
{ key: "app", label: t("Apps"), icon: SmartphoneIcon },
{ key: "service", label: t("Services"), icon: LayoutTemplateIcon },
{ key: "endpoint", label: t("Endpoints"), icon: LinkIcon },
];
export default function AssetsPage() {
@@ -193,11 +194,11 @@ export default function AssetsPage() {
setDeleting(true);
try {
const res = await api.deleteAssets(deleteIds);
toast.success(`Deleted ${res.deleted} assets`);
toast.success(t("Deleted {count} assets", { count: res.deleted }));
setSelected(new Set());
refresh();
} catch (e) {
toast.error("Delete failed: " + String((e as Error)?.message ?? e));
toast.error(t("Delete failed: {error}", { error: String((e as Error)?.message ?? e) }));
} finally {
setDeleting(false);
setDeleteOpen(false);
@@ -211,12 +212,12 @@ export default function AssetsPage() {
const res = await api.deleteCompany(companyDeleteTarget.id, companyDeleteAssets);
const msg =
companyDeleteAssets && res.assets_deleted > 0
? `Company deleted, along with ${res.assets_deleted} assets`
: "Company deleted";
? t("Company deleted, along with {count} assets", { count: res.assets_deleted })
: t("Company deleted");
toast.success(msg);
refresh();
} catch (e) {
toast.error("Delete failed: " + String((e as Error)?.message ?? e));
toast.error(t("Delete failed: {error}", { error: String((e as Error)?.message ?? e) }));
} finally {
setCompanyDeleting(false);
setCompanyDeleteTarget(null);
@@ -317,19 +318,19 @@ export default function AssetsPage() {
<div className="flex h-[calc(100vh-6rem)] min-h-0 flex-col gap-4">
<div className="flex items-center justify-between gap-4">
<div>
<h1 className="text-xl font-semibold tracking-tight">Assets</h1>
<h1 className="text-xl font-semibold tracking-tight">{t("Assets")}</h1>
</div>
<div className="flex items-center gap-3">
<span className="text-sm text-muted-foreground">
<span className="tabular-nums">{totalAssets}</span> assets in total
<span className="text-sm text-muted-foreground tabular-nums">
{t("{count} assets in total", { count: totalAssets })}
</span>
{selected.size > 0 && (
<Button variant="destructive" size="sm" onClick={() => openDelete(Array.from(selected) as number[])}>
<Trash2Icon className="size-3.5" /> Delete selected ({selected.size})
<Trash2Icon className="size-3.5" /> {t("Delete selected ({count})", { count: selected.size })}
</Button>
)}
<Button variant="outline" size="sm" onClick={refresh} disabled={loading}>
<RefreshCwIcon className={cn("size-4", loading && "animate-spin")} /> Refresh
<RefreshCwIcon className={cn("size-4", loading && "animate-spin")} /> {t("Refresh")}
</Button>
<CompanyDialog onSaved={refresh} />
</div>
@@ -355,10 +356,10 @@ export default function AssetsPage() {
<Table>
<TableHeader className="sticky top-0 z-10 bg-card">
<TableRow>
<TableHead>Company</TableHead>
<TableHead className="w-24 text-right">Assets</TableHead>
<TableHead>Asset scope</TableHead>
<TableHead className="w-36 text-right">Actions</TableHead>
<TableHead>{t("Company")}</TableHead>
<TableHead className="w-24 text-right">{t("Assets")}</TableHead>
<TableHead>{t("Asset scope")}</TableHead>
<TableHead className="w-36 text-right">{t("Actions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -381,7 +382,7 @@ export default function AssetsPage() {
))}
</div>
) : (
<span className="text-xs text-muted-foreground">No scope set</span>
<span className="text-xs text-muted-foreground">{t("No scope set")}</span>
)}
</TableCell>
<TableCell className="text-right">
@@ -396,7 +397,7 @@ export default function AssetsPage() {
setCompanyDeleteTarget(c);
setCompanyDeleteAssets(false);
}}
aria-label={`Delete company ${c.name}`}
aria-label={t("Delete company {name}", { name: c.name })}
>
<Trash2Icon className="size-3.5" />
</Button>
@@ -407,7 +408,9 @@ export default function AssetsPage() {
{companies.length === 0 && (
<TableRow>
<TableCell colSpan={4} className="py-10 text-center text-sm text-muted-foreground">
No companies yet. Click "Add company" in the top-right corner and fill in the asset scope; the system will automatically claim matching assets.
{t(
'No companies yet. Click "Add company" in the top-right corner and fill in the asset scope; the system will automatically claim matching assets.',
)}
</TableCell>
</TableRow>
)}
@@ -440,7 +443,7 @@ export default function AssetsPage() {
<TableCell className="font-mono text-xs font-medium">{a.domain}</TableCell>
<TableCell className="text-xs">{a.icp || "—"}</TableCell>
<TableCell className="text-xs">
{companyName(a.company_id) || <span className="text-muted-foreground">Unassigned</span>}
{companyName(a.company_id) || <span className="text-muted-foreground">{t("Unassigned")}</span>}
</TableCell>
<TableCell className="w-8 pl-0">
<Button
@@ -448,7 +451,7 @@ export default function AssetsPage() {
size="icon"
className="size-7 text-muted-foreground hover:text-destructive"
onClick={() => openDelete([a.id])}
aria-label={`Delete asset ${a.domain || a.id}`}
aria-label={t("Delete asset {name}", { name: a.domain || a.id })}
>
<Trash2Icon className="size-3.5" />
</Button>
@@ -495,7 +498,7 @@ export default function AssetsPage() {
size="icon"
className="size-7 text-muted-foreground hover:text-destructive"
onClick={() => openDelete([a.id])}
aria-label={`Delete asset ${a.ip || a.id}`}
aria-label={t("Delete asset {name}", { name: a.ip || a.id })}
>
<Trash2Icon className="size-3.5" />
</Button>
@@ -537,7 +540,7 @@ export default function AssetsPage() {
size="icon"
className="size-7 text-muted-foreground hover:text-destructive"
onClick={() => openDelete([a.id])}
aria-label={`Delete asset ${a.domain || a.id}`}
aria-label={t("Delete asset {name}", { name: a.domain || a.id })}
>
<Trash2Icon className="size-3.5" />
</Button>
@@ -577,7 +580,7 @@ export default function AssetsPage() {
size="icon"
className="size-7 text-muted-foreground hover:text-destructive"
onClick={() => openDelete([a.id])}
aria-label={`Delete asset ${a.app_name || a.id}`}
aria-label={t("Delete asset {name}", { name: a.app_name || a.id })}
>
<Trash2Icon className="size-3.5" />
</Button>
@@ -657,7 +660,7 @@ export default function AssetsPage() {
) : (
(a.auth ?? []).map((authItem, i) => {
const item = authItem as Record<string, string>;
const label = item.type || item.username || "Auth";
const label = item.type || item.username || t("Auth");
return (
<span key={i} className="inline-flex items-center gap-1 text-[11px]">
<KeyRoundIcon className="size-3 text-muted-foreground" />
@@ -673,7 +676,7 @@ export default function AssetsPage() {
size="icon"
className="size-7 text-muted-foreground hover:text-destructive"
onClick={() => openDelete([a.id])}
aria-label={`Delete asset ${a.url || a.id}`}
aria-label={t("Delete asset {name}", { name: a.url || a.id })}
>
<Trash2Icon className="size-3.5" />
</Button>
@@ -725,7 +728,7 @@ export default function AssetsPage() {
size="icon"
className="size-7 text-muted-foreground hover:text-destructive"
onClick={() => openDelete([a.id])}
aria-label={`Delete asset ${a.url || a.id}`}
aria-label={t("Delete asset {name}", { name: a.url || a.id })}
>
<Trash2Icon className="size-3.5" />
</Button>
@@ -739,14 +742,15 @@ export default function AssetsPage() {
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Confirm delete</AlertDialogTitle>
<AlertDialogTitle>{t("Confirm delete")}</AlertDialogTitle>
<AlertDialogDescription>
This will permanently delete <span className="font-semibold tabular-nums">{deleteIds.length}</span>{" "}
asset records. This action cannot be undone.
{t("This will permanently delete {count} asset records. This action cannot be undone.", {
count: deleteIds.length,
})}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
<AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault();
@@ -755,7 +759,7 @@ export default function AssetsPage() {
disabled={deleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleting ? "Deleting…" : "Confirm delete"}
{deleting ? t("Deleting…") : t("Confirm delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -772,10 +776,14 @@ export default function AssetsPage() {
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete company · {companyDeleteTarget?.name}</AlertDialogTitle>
<AlertDialogTitle>{t("Delete company · {name}", { name: companyDeleteTarget?.name ?? "" })}</AlertDialogTitle>
<AlertDialogDescription asChild>
<div className="space-y-3">
<p>This will permanently delete the company and its asset scope configuration. This action cannot be undone.</p>
<p>
{t(
"This will permanently delete the company and its asset scope configuration. This action cannot be undone.",
)}
</p>
<label
htmlFor="delete-assets-opt"
className="flex cursor-pointer items-center gap-2.5 rounded-md border p-3 hover:bg-muted/50"
@@ -786,15 +794,17 @@ export default function AssetsPage() {
onCheckedChange={(v) => setCompanyDeleteAssets(!!v)}
/>
<span className="text-sm leading-snug">
Also delete all assets under this company
<span className="block text-xs text-muted-foreground">Leave unchecked to keep the assets and only remove the ownership</span>
{t("Also delete all assets under this company")}
<span className="block text-xs text-muted-foreground">
{t("Leave unchecked to keep the assets and only remove the ownership")}
</span>
</span>
</label>
</div>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={companyDeleting}>Cancel</AlertDialogCancel>
<AlertDialogCancel disabled={companyDeleting}>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault();
@@ -803,7 +813,7 @@ export default function AssetsPage() {
disabled={companyDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{companyDeleting ? "Deleting…" : "Confirm delete"}
{companyDeleting ? t("Deleting…") : t("Confirm delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -861,7 +871,7 @@ function AssetCard({
/>
</TableHead>
) : (
<TableHead key={c + i}>{c}</TableHead>
<TableHead key={c + i}>{c && t(c)}</TableHead>
),
)}
</TableRow>
@@ -872,7 +882,7 @@ function AssetCard({
) : (
<TableRow>
<TableCell colSpan={cols.length} className="py-12 text-center text-sm text-muted-foreground">
{loaded ? "No data." : "Loading…"}
{loaded ? t("No data.") : t("Loading…")}
</TableCell>
</TableRow>
)}
@@ -889,7 +899,7 @@ function AssetCard({
<SelectGroup>
{PAGE_SIZES.map((n) => (
<SelectItem key={n} value={String(n)}>
{n} / page
{t("{count} / page", { count: n })}
</SelectItem>
))}
</SelectGroup>
@@ -989,11 +999,11 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) {
const submit = async () => {
if (!name.trim()) {
toast.error("Please enter a company name");
toast.error(t("Please enter a company name"));
return;
}
if (parsedScope.errors.length > 0) {
toast.error("Please fix the invalid asset scope");
toast.error(t("Please fix the invalid asset scope"));
return;
}
setBusy(true);
@@ -1001,14 +1011,15 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) {
const res = await api.createCompany(name.trim(), parsedScope.rules);
const added = res.scope_added ?? 0;
const invalid = res.scope_invalid ?? 0;
if (invalid > 0) toast.warning(`Company created, ${added} scopes added; ${invalid} invalid lines`);
else toast.success(`Company created, ${added} scopes added`);
if (invalid > 0)
toast.warning(t("Company created, {added} scopes added; {invalid} invalid lines", { added, invalid }));
else toast.success(t("Company created, {added} scopes added", { added }));
setOpen(false);
onSaved();
} catch (e) {
const msg = String((e as Error)?.message ?? e);
if (/:\s*409$/.test(msg)) toast.error("Company already exists; try a different name");
else toast.error(`Save failed: ${msg}`);
if (/:\s*409$/.test(msg)) toast.error(t("Company already exists; try a different name"));
else toast.error(t("Save failed: {error}", { error: msg }));
} finally {
setBusy(false);
}
@@ -1018,21 +1029,25 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) {
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button size="sm">
<BuildingIcon data-icon="inline-start" /> Add company
<BuildingIcon data-icon="inline-start" /> {t("Add company")}
</Button>
</SheetTrigger>
<SheetContent className="w-full! max-w-none! gap-0 p-0 sm:w-[520px]! sm:max-w-[520px]!">
<SheetHeader className="border-b p-6">
<SheetTitle>Add company</SheetTitle>
<SheetDescription>Configure the company and its asset scope. Keywords only serve as agent hints and do not automatically assign assets.</SheetDescription>
<SheetTitle>{t("Add company")}</SheetTitle>
<SheetDescription>
{t(
"Configure the company and its asset scope. Keywords only serve as agent hints and do not automatically assign assets.",
)}
</SheetDescription>
</SheetHeader>
<div className="flex-1 overflow-y-auto p-6">
<FieldGroup>
<Field>
<FieldLabel htmlFor="cn-name">Company name</FieldLabel>
<FieldLabel htmlFor="cn-name">{t("Company name")}</FieldLabel>
<Input
id="cn-name"
placeholder="e.g. Acme Corp (name must be unique)"
placeholder={t("e.g. Acme Corp (name must be unique)")}
value={name}
onChange={(e) => setName(e.target.value)}
/>
@@ -1042,10 +1057,10 @@ function CompanyDialog({ onSaved }: { onSaved: () => void }) {
</div>
<SheetFooter className="flex-row justify-end gap-2 border-t p-4">
<Button variant="outline" onClick={() => setOpen(false)} disabled={busy}>
Cancel
{t("Cancel")}
</Button>
<Button onClick={submit} disabled={busy || !name.trim() || parsedScope.errors.length > 0}>
{busy ? "Saving…" : "Save"}
{busy ? t("Saving…") : t("Save")}
</Button>
</SheetFooter>
</SheetContent>
@@ -1073,20 +1088,20 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () =
const submit = async () => {
if (parsedScope.errors.length > 0) {
toast.error("Please fix the invalid asset scope");
toast.error(t("Please fix the invalid asset scope"));
return;
}
setBusy(true);
try {
const res = await api.updateCompanyScope(company.id, parsedScope.rules, reason);
const errCount = res.invalid ?? 0;
if (errCount > 0) toast.warning(`Saved; ${errCount} invalid lines`);
else toast.success(`Scope updated, ${res.added} entries in total`);
if (errCount > 0) toast.warning(t("Saved; {count} invalid lines", { count: errCount }));
else toast.success(t("Scope updated, {count} entries in total", { count: res.added }));
showScopeWarnings(res.warnings);
setOpen(false);
onSaved();
} catch (e) {
toast.error(`Save failed: ${String((e as Error)?.message ?? e)}`);
toast.error(t("Save failed: {error}", { error: String((e as Error)?.message ?? e) }));
} finally {
setBusy(false);
}
@@ -1096,14 +1111,16 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () =
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm" className="h-7">
Edit
{t("Edit")}
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit asset scope · {company.name}</DialogTitle>
<DialogTitle>{t("Edit asset scope · {name}", { name: company.name })}</DialogTitle>
<DialogDescription>
Saving replaces all existing scopes. ICP matches assets exactly; company keywords only serve as agent hints.
{t(
"Saving replaces all existing scopes. ICP matches assets exactly; company keywords only serve as agent hints.",
)}
</DialogDescription>
</DialogHeader>
<FieldGroup className="py-2">
@@ -1114,10 +1131,10 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () =
parsed={parsedScope}
/>
<Field>
<FieldLabel htmlFor="es-reason">Attribution basis (optional)</FieldLabel>
<FieldLabel htmlFor="es-reason">{t("Attribution basis (optional)")}</FieldLabel>
<Input
id="es-reason"
placeholder="e.g. certificate / whois / ASN evidence"
placeholder={t("e.g. certificate / whois / ASN evidence")}
value={reason}
onChange={(e) => setReason(e.target.value)}
/>
@@ -1125,10 +1142,10 @@ function EditScopeDialog({ company, onSaved }: { company: Company; onSaved: () =
</FieldGroup>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)} disabled={busy}>
Cancel
{t("Cancel")}
</Button>
<Button onClick={submit} disabled={busy || parsedScope.errors.length > 0}>
{busy ? "Saving…" : "Overwrite save"}
{busy ? t("Saving…") : t("Overwrite save")}
</Button>
</DialogFooter>
</DialogContent>
@@ -1152,24 +1169,24 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: ()
const submit = async () => {
if (parsedScope.rules.length === 0) {
toast.error("Please enter the scopes to append");
toast.error(t("Please enter the scopes to append"));
return;
}
if (parsedScope.errors.length > 0) {
toast.error("Please fix the invalid asset scope");
toast.error(t("Please fix the invalid asset scope"));
return;
}
setBusy(true);
try {
const res = await api.addCompanyScope(company.id, parsedScope.rules, reason);
const errCount = res.invalid ?? 0;
if (errCount > 0) toast.warning(`Saved; ${errCount} invalid lines`);
else toast.success(`Appended ${res.added} scopes`);
if (errCount > 0) toast.warning(t("Saved; {count} invalid lines", { count: errCount }));
else toast.success(t("Appended {count} scopes", { count: res.added }));
showScopeWarnings(res.warnings);
setOpen(false);
onSaved();
} catch (e) {
toast.error(`Save failed: ${String((e as Error)?.message ?? e)}`);
toast.error(t("Save failed: {error}", { error: String((e as Error)?.message ?? e) }));
} finally {
setBusy(false);
}
@@ -1179,13 +1196,17 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: ()
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm" className="h-7">
Append
{t("Append")}
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Append asset scope · {company.name}</DialogTitle>
<DialogDescription>New scopes are appended to the existing ones. ICP matches assets exactly; company keywords only serve as agent hints.</DialogDescription>
<DialogTitle>{t("Append asset scope · {name}", { name: company.name })}</DialogTitle>
<DialogDescription>
{t(
"New scopes are appended to the existing ones. ICP matches assets exactly; company keywords only serve as agent hints.",
)}
</DialogDescription>
</DialogHeader>
<FieldGroup className="py-2">
<ScopeTextEditor
@@ -1195,10 +1216,10 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: ()
parsed={parsedScope}
/>
<Field>
<FieldLabel htmlFor="as-reason">Attribution basis (optional)</FieldLabel>
<FieldLabel htmlFor="as-reason">{t("Attribution basis (optional)")}</FieldLabel>
<Input
id="as-reason"
placeholder="e.g. certificate / whois / ASN evidence"
placeholder={t("e.g. certificate / whois / ASN evidence")}
value={reason}
onChange={(e) => setReason(e.target.value)}
/>
@@ -1206,10 +1227,10 @@ function AppendScopeDialog({ company, onSaved }: { company: Company; onSaved: ()
</FieldGroup>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)} disabled={busy}>
Cancel
{t("Cancel")}
</Button>
<Button onClick={submit} disabled={busy || parsedScope.rules.length === 0 || parsedScope.errors.length > 0}>
{busy ? "Saving…" : "Append"}
{busy ? t("Saving…") : t("Append")}
</Button>
</DialogFooter>
</DialogContent>
+33 -31
View File
@@ -15,9 +15,10 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@
import { api } from "@/lib/api";
import type { CommandRecord, ToolStat } from "@/lib/types";
import { cn } from "@/lib/utils";
import { intlLocale, t } from "@/i18n";
function fmtTime(ts: string) {
return new Date(ts).toLocaleString("zh-CN", {
return new Date(ts).toLocaleString(intlLocale, {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
@@ -130,7 +131,7 @@ export default function CommandsPage() {
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-2">
<TerminalIcon className="h-5 w-5 text-muted-foreground" />
<h1 className="text-xl font-semibold tracking-tight">Tool executions</h1>
<h1 className="text-xl font-semibold tracking-tight">{t("Tool executions")}</h1>
<Badge variant="secondary">{total}</Badge>
</div>
</div>
@@ -140,14 +141,14 @@ export default function CommandsPage() {
<div className="relative max-w-sm flex-1">
<SearchIcon className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search tools / arguments..."
placeholder={t("Search tools / arguments...")}
value={query}
onChange={(e) => setQuery(e.target.value)}
className="h-8 pl-8"
/>
</div>
<Input
placeholder="Task ID"
placeholder={t("Task ID")}
className="h-8 w-28"
value={taskFilter}
onChange={(e) => setTaskFilter(e.target.value.replace(/\D/g, ""))}
@@ -159,7 +160,7 @@ export default function CommandsPage() {
<SelectContent>
{PAGE_SIZES.map((n) => (
<SelectItem key={n} value={String(n)}>
{n} / page
{t("{count} / page", { count: n })}
</SelectItem>
))}
</SelectContent>
@@ -167,7 +168,7 @@ export default function CommandsPage() {
<Button variant="outline" size="sm" className="h-8" onClick={() => setStatsOpen(true)}>
<BarChart3Icon className="size-4" />
Stats
{t("Stats")}
</Button>
<div className="ml-auto flex items-center gap-2 text-xs text-muted-foreground">
@@ -205,12 +206,12 @@ export default function CommandsPage() {
<Table>
<TableHeader className="sticky top-0 z-10 bg-card">
<TableRow>
<TableHead className="w-[130px]">Time</TableHead>
<TableHead className="w-[60px]">Task</TableHead>
<TableHead className="w-[90px]">Worker</TableHead>
<TableHead className="w-[110px]">Tool</TableHead>
<TableHead>Input</TableHead>
<TableHead className="w-[60px]">Status</TableHead>
<TableHead className="w-[130px]">{t("Time")}</TableHead>
<TableHead className="w-[60px]">{t("Task")}</TableHead>
<TableHead className="w-[90px]">{t("Worker")}</TableHead>
<TableHead className="w-[110px]">{t("Tool")}</TableHead>
<TableHead>{t("Input")}</TableHead>
<TableHead className="w-[60px]">{t("Status")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -223,7 +224,7 @@ export default function CommandsPage() {
) : commands.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="py-12 text-center text-sm text-muted-foreground">
No tool execution records yet
{t("No tool execution records yet")}
</TableCell>
</TableRow>
) : (
@@ -255,11 +256,11 @@ export default function CommandsPage() {
<TableCell>
{cmd.is_error ? (
<Badge variant="destructive" className="text-xs">
Failed
{t("Failed")}
</Badge>
) : (
<Badge variant="secondary" className="text-xs text-emerald-600">
Success
{t("Success")}
</Badge>
)}
</TableCell>
@@ -276,21 +277,20 @@ export default function CommandsPage() {
<Dialog open={statsOpen} onOpenChange={setStatsOpen}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>Tool call stats</DialogTitle>
<DialogTitle>{t("Tool call stats")}</DialogTitle>
<DialogDescription>
{taskFilter || queryQ ? "All records under the current filters" : "All tool execution records"}
{taskFilter || queryQ ? t("All records under the current filters") : t("All tool execution records")}
{stats.length > 0 && (
<>
<span className="tabular-nums">
{" · "}
<span className="tabular-nums">{stats.length}</span> tools ·{" "}
<span className="tabular-nums">{statsTotal}</span> calls
{t("{tools} tools · {calls} calls", { tools: stats.length, calls: statsTotal })}
{statsErrors > 0 && (
<>
{" · Failed "}
<span className="tabular-nums text-red-600 dark:text-red-400">{statsErrors}</span>
{" · "}
<span className="text-red-600 dark:text-red-400">{t("Failed {count}", { count: statsErrors })}</span>
</>
)}
</>
</span>
)}
</DialogDescription>
</DialogHeader>
@@ -300,7 +300,7 @@ export default function CommandsPage() {
<Loader2Icon className="mx-auto h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : stats.length === 0 ? (
<div className="py-10 text-center text-sm text-muted-foreground">No stats data</div>
<div className="py-10 text-center text-sm text-muted-foreground">{t("No stats data")}</div>
) : (
<div className="-mr-2 max-h-[55vh] space-y-1 overflow-auto pr-2">
{stats.map((s) => (
@@ -309,7 +309,9 @@ export default function CommandsPage() {
<div className="flex items-center gap-2">
<span className="truncate font-mono text-xs font-medium">{s.tool}</span>
{s.errors > 0 && (
<span className="text-[11px] tabular-nums text-red-600 dark:text-red-400">Failed {s.errors}</span>
<span className="text-[11px] tabular-nums text-red-600 dark:text-red-400">
{t("Failed {count}", { count: s.errors })}
</span>
)}
</div>
<div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted">
@@ -337,7 +339,7 @@ export default function CommandsPage() {
{selected && (
<>
<SheetHeader className="border-b px-5 py-4">
<SheetTitle className="pr-8">Tool execution details</SheetTitle>
<SheetTitle className="pr-8">{t("Tool execution details")}</SheetTitle>
<SheetDescription>{fmtTime(selected.created_at)}</SheetDescription>
<div className="flex flex-wrap items-center gap-2 pt-2">
<Badge variant="outline" className="text-xs font-mono">
@@ -351,18 +353,18 @@ export default function CommandsPage() {
</Badge>
{selected.is_error ? (
<Badge variant="destructive" className="text-xs">
Failed
{t("Failed")}
</Badge>
) : (
<Badge variant="secondary" className="text-xs text-emerald-600">
Success
{t("Success")}
</Badge>
)}
</div>
</SheetHeader>
<div className="grid min-h-0 flex-1 grid-rows-2 divide-y">
<div className="flex min-h-0 min-w-0 flex-col">
<div className="border-b px-5 py-2 text-xs font-medium text-muted-foreground">Input</div>
<div className="border-b px-5 py-2 text-xs font-medium text-muted-foreground">{t("Input")}</div>
<div className="min-h-0 flex-1 overflow-auto">
<pre className="p-5 font-mono text-xs break-all whitespace-pre-wrap">
{toolInput(selected.command)}
@@ -370,7 +372,7 @@ export default function CommandsPage() {
</div>
</div>
<div className="flex min-h-0 min-w-0 flex-col">
<div className="border-b px-5 py-2 text-xs font-medium text-muted-foreground">Output</div>
<div className="border-b px-5 py-2 text-xs font-medium text-muted-foreground">{t("Output")}</div>
<div className="min-h-0 flex-1 overflow-auto">
<pre
className={cn(
@@ -378,7 +380,7 @@ export default function CommandsPage() {
selected.is_error && "text-red-600 dark:text-red-400",
)}
>
{selected.output || "(empty)"}
{selected.output || t("(empty)")}
</pre>
</div>
</div>
@@ -20,6 +20,7 @@ import { Button } from "@/components/ui/button";
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
import type { FindingAssetKind, FindingAssetNode } from "@/lib/types";
import { cn } from "@/lib/utils";
import { t } from "@/i18n";
// Icons reuse the assets page's type mapping, so the same asset kind looks the same in both places.
const KIND_ICON: Record<FindingAssetKind, LucideIcon> = {
@@ -34,14 +35,14 @@ const KIND_ICON: Record<FindingAssetKind, LucideIcon> = {
};
const KIND_LABEL: Record<FindingAssetKind, string> = {
company: "Company",
root_domain: "Root domain",
subdomain: "Subdomain",
company: t("Company"),
root_domain: t("Root domain"),
subdomain: t("Subdomain"),
ip: "IP",
app: "App",
service: "Service",
endpoint: "Endpoint",
none: "Unlinked",
app: t("App"),
service: t("Service"),
endpoint: t("Endpoint"),
none: t("Unlinked"),
};
// TreeNode is the tree assembled from the node array. The backend already sorts by "most findings under the same parent first",
@@ -233,9 +234,9 @@ export function AssetTree({
[isExpanded],
);
let emptyHint = "No findings are linked to assets under the current filters.";
if (loading) emptyHint = "Loading…";
else if (searching) emptyHint = "No matching assets.";
let emptyHint = t("No findings are linked to assets under the current filters.");
if (loading) emptyHint = t("Loading…");
else if (searching) emptyHint = t("No matching assets.");
const rows: React.ReactNode[] = [];
const pushRows = (list: TreeNode[]) => {
@@ -264,8 +265,8 @@ export function AssetTree({
type="search"
value={keyword}
onChange={(event) => setKeyword(event.target.value)}
placeholder="Filter assets"
aria-label="Filter assets"
placeholder={t("Filter assets")}
aria-label={t("Filter assets")}
/>
<InputGroupAddon>
<SearchIcon aria-hidden="true" />
@@ -278,8 +279,8 @@ export function AssetTree({
className="size-8 shrink-0 text-muted-foreground"
onClick={onRefresh}
disabled={loading}
aria-label="Refresh asset tree"
title="Refresh asset tree"
aria-label={t("Refresh asset tree")}
title={t("Refresh asset tree")}
>
<RefreshCwIcon className={cn("size-4", loading && "animate-spin")} />
</Button>
@@ -294,7 +295,7 @@ export function AssetTree({
selected === null ? "bg-accent font-medium" : "hover:bg-accent/50",
)}
>
<span>All assets</span>
<span>{t("All assets")}</span>
<span className="text-xs tabular-nums text-muted-foreground">{findingTotal}</span>
</button>
@@ -307,8 +308,10 @@ export function AssetTree({
{truncated && (
<p className="px-1 text-xs text-muted-foreground">
Too many assets; the {(droppedKinds ?? []).map((k) => KIND_LABEL[k as FindingAssetKind] ?? k).join(" / ")}
levels are hidden (their counts still roll up into the parents). Narrow with the filters or the filter box to see the full hierarchy.
{t(
"Too many assets; the {kinds} levels are hidden (their counts still roll up into the parents). Narrow with the filters or the filter box to see the full hierarchy.",
{ kinds: (droppedKinds ?? []).map((k) => KIND_LABEL[k as FindingAssetKind] ?? k).join(" / ") },
)}
</p>
)}
</div>
@@ -343,7 +346,7 @@ function AssetTreeRow({
type="button"
onClick={onToggle}
className="flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground"
aria-label={open ? "Collapse" : "Expand"}
aria-label={open ? t("Collapse") : t("Expand")}
aria-expanded={open}
>
<ChevronRightIcon className={cn("size-3.5 transition-transform", open && "rotate-90")} />
@@ -362,16 +365,16 @@ function AssetTreeRow({
</button>
<span className="flex shrink-0 items-center gap-1 text-xs tabular-nums">
{node.critical > 0 && (
<span className="text-rose-600" title={`Critical ${node.critical}`}>
<span className="text-rose-600" title={t("Critical {count}", { count: node.critical })}>
{node.critical}
</span>
)}
{node.high > 0 && (
<span className="text-red-500" title={`High ${node.high}`}>
<span className="text-red-500" title={t("High {count}", { count: node.high })}>
{node.high}
</span>
)}
<span className="text-muted-foreground" title={`${node.total} findings total`}>
<span className="text-muted-foreground" title={t("{count} findings total", { count: node.total })}>
{node.total}
</span>
</span>
@@ -46,6 +46,7 @@ import type {
VerificationStatus,
} from "@/lib/types";
import { cn } from "@/lib/utils";
import { intlLocale, t } from "@/i18n";
export const SEVERITIES: Severity[] = ["critical", "high", "medium", "low"];
@@ -78,11 +79,11 @@ export const FINDING_REPORT_STATES: FindingReportState[] = [
];
export const REPORT_STATE_META: Record<FindingReportState, { label: string; tone: Tone }> = {
none: { label: "Not submitted", tone: "slate" },
submitted: { label: "Submitted", tone: "amber" },
accepted: { label: "Accepted", tone: "green" },
rejected: { label: "Rejected", tone: "red" },
duplicate: { label: "Duplicate report", tone: "neutral" },
none: { label: t("Not submitted"), tone: "slate" },
submitted: { label: t("Submitted"), tone: "amber" },
accepted: { label: t("Accepted"), tone: "green" },
rejected: { label: t("Rejected"), tone: "red" },
duplicate: { label: t("Duplicate report"), tone: "neutral" },
};
export function ReportStateBadge({ state }: { state?: FindingReportState }) {
@@ -102,11 +103,11 @@ export function ReportStateBadge({ state }: { state?: FindingReportState }) {
// Verification outcome → label/tone, on the same tone tokens StatusBadge uses.
export const VERIFICATION_META: Record<VerificationStatus, { label: string; tone: Tone }> = {
verified: { label: "Verified", tone: "green" },
unverified: { label: "Unverified", tone: "slate" },
blocked: { label: "Blocked", tone: "amber" },
not_assessed: { label: "Not assessed", tone: "red" },
false_positive: { label: "False positive", tone: "neutral" },
verified: { label: t("Verified"), tone: "green" },
unverified: { label: t("Unverified"), tone: "slate" },
blocked: { label: t("Blocked"), tone: "amber" },
not_assessed: { label: t("Not assessed"), tone: "red" },
false_positive: { label: t("False positive"), tone: "neutral" },
};
// VerificationBadge shows the automated verification outcome ("Verified L3" when a
@@ -155,7 +156,7 @@ export function isSameFinding(left: Finding, right: Finding): boolean {
}
export function fmtTime(ts: string) {
return new Date(ts).toLocaleString("zh-CN", {
return new Date(ts).toLocaleString(intlLocale, {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
@@ -208,7 +209,7 @@ export function FindingsTable({
activeRetests,
onDeepen,
onDelete,
selectAllLabel = "Select all on this page",
selectAllLabel = t("Select all on this page"),
}: FindingsTableProps) {
const selectableIds = items.map((finding) => finding.finding_id).filter((id): id is string => Boolean(id));
const selectedCount = selectableIds.filter((id) => selectedIds.has(id)).length;
@@ -232,14 +233,14 @@ export function FindingsTable({
/>
</TableHead>
<TableHead className="w-8" />
<TableHead className="w-20">Severity</TableHead>
<TableHead>Vulnerability</TableHead>
<TableHead className="w-44">Asset</TableHead>
<TableHead className="w-28">Status</TableHead>
<TableHead className="w-36">Report</TableHead>
<TableHead className="w-32">Task</TableHead>
<TableHead className="w-24">Time</TableHead>
<TableHead className="w-48">Actions</TableHead>
<TableHead className="w-20">{t("Severity")}</TableHead>
<TableHead>{t("Vulnerability")}</TableHead>
<TableHead className="w-44">{t("Asset")}</TableHead>
<TableHead className="w-28">{t("Status")}</TableHead>
<TableHead className="w-36">{t("Report")}</TableHead>
<TableHead className="w-32">{t("Task")}</TableHead>
<TableHead className="w-24">{t("Time")}</TableHead>
<TableHead className="w-48">{t("Actions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -266,7 +267,7 @@ export function FindingsTable({
<Checkbox
checked={selectedIds.has(f.finding_id)}
onCheckedChange={(c) => onToggleSelected(f.finding_id as string, c === true)}
aria-label="Select this vulnerability"
aria-label={t("Select this vulnerability")}
/>
)}
</TableCell>
@@ -285,16 +286,16 @@ export function FindingsTable({
href={`/function/findings/detail?id=${f.finding_id}`}
onClick={(e) => e.stopPropagation()}
className="truncate font-medium hover:text-primary hover:underline"
title="View finding details"
title={t("View finding details")}
>
{f.name || f.vulnclass || "Uncategorized"}
{f.name || f.vulnclass || t("Uncategorized")}
</Link>
) : (
<span className="truncate font-medium">{f.name || f.vulnclass || "Uncategorized"}</span>
<span className="truncate font-medium">{f.name || f.vulnclass || t("Uncategorized")}</span>
)}
<span className="truncate text-xs text-muted-foreground">{f.summary}</span>
<div className="flex flex-wrap items-center gap-1">
<Badge variant="outline">Traffic evidence: {f.traffic_count ?? 0}</Badge>
<Badge variant="outline">{t("Traffic evidence: {count}", { count: f.traffic_count ?? 0 })}</Badge>
<VerificationBadge finding={f} />
</div>
</div>
@@ -378,22 +379,27 @@ export function FindingsTable({
<div className="flex items-center gap-1">
{retest ? (
<Button asChild size="sm" variant="ghost">
<Link href={`/chat?c=${retest.conversation_id}`} title="View the retest in progress">
<Link href={`/chat?c=${retest.conversation_id}`} title={t("View the retest in progress")}>
<Spinner data-icon="inline-start" />
Retesting
{t("Retesting")}
</Link>
</Button>
) : null}
{!retest && f.finding_id && !f.inherited ? (
<Button size="sm" variant="ghost" onClick={() => onRetest(f)} title="Retest this vulnerability in a separate conversation">
<Button
size="sm"
variant="ghost"
onClick={() => onRetest(f)}
title={t("Retest this vulnerability in a separate conversation")}
>
<RotateCcwIcon data-icon="inline-start" />
Retest
{t("Retest")}
</Button>
) : null}
{f.finding_id && f.task_id && (
<Button size="sm" variant="ghost" onClick={() => onDeepen(f)}>
<FlaskConicalIcon data-icon="inline-start" />
Deepen
{t("Deepen")}
</Button>
)}
{f.finding_id && (
@@ -403,25 +409,24 @@ export function FindingsTable({
size="icon"
variant="ghost"
className="size-7 text-muted-foreground hover:text-destructive"
aria-label="Delete vulnerability"
aria-label={t("Delete vulnerability")}
>
<Trash2Icon className="size-4" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete this vulnerability?</AlertDialogTitle>
<AlertDialogDescription className="break-words">
"
<span className="break-all">
{f.name || f.vulnclass || f.summary || `#${f.finding_id}`}
</span>
" will be permanently deleted and removed from the findings list, the task findings tab, and the exploration graph. This action cannot be undone.
<AlertDialogTitle>{t("Delete this vulnerability?")}</AlertDialogTitle>
<AlertDialogDescription className="[overflow-wrap:anywhere]">
{t(
'"{name}" will be permanently deleted and removed from the findings list, the task findings tab, and the exploration graph. This action cannot be undone.',
{ name: f.name || f.vulnclass || f.summary || `#${f.finding_id}` },
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => onDelete(f)}>Delete</AlertDialogAction>
<AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={() => onDelete(f)}>{t("Delete")}</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
@@ -439,23 +444,23 @@ export function FindingsTable({
{f.finding_id && edit && (
<div className="flex flex-wrap items-end gap-3 rounded-md border bg-background px-3 py-2.5">
<div className="flex min-w-[12rem] flex-1 flex-col gap-1">
<Label className="text-xs text-muted-foreground">Vulnerability</Label>
<Label className="text-xs text-muted-foreground">{t("Vulnerability")}</Label>
<Input
value={edit.name}
onChange={(e) => onEditChange((s) => (s ? { ...s, name: e.target.value } : s))}
placeholder="Readable title; falls back to category when empty"
placeholder={t("Readable title; falls back to category when empty")}
/>
</div>
<div className="flex min-w-[10rem] flex-col gap-1">
<Label className="text-xs text-muted-foreground">Category</Label>
<Label className="text-xs text-muted-foreground">{t("Category")}</Label>
<Input
value={edit.vulnclass}
onChange={(e) => onEditChange((s) => (s ? { ...s, vulnclass: e.target.value } : s))}
placeholder="e.g. SQL Injection"
placeholder={t("e.g. SQL Injection")}
/>
</div>
<div className="flex flex-col gap-1">
<Label className="text-xs text-muted-foreground">Severity</Label>
<Label className="text-xs text-muted-foreground">{t("Severity")}</Label>
<Select
value={edit.severity}
onValueChange={(v) => onEditChange((s) => (s ? { ...s, severity: v as Severity } : s))}
@@ -473,23 +478,23 @@ export function FindingsTable({
</Select>
</div>
<Button size="sm" disabled={saving} onClick={() => onSave(f)}>
{saving ? "Saving…" : "Save"}
{saving ? t("Saving…") : t("Save")}
</Button>
</div>
)}
<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<ShieldAlertIcon className="size-3.5" />
Evidence
{t("Evidence")}
{f.vulnclass && (
<span>
· Type:
· {t("Type:")}
<code className="rounded bg-muted px-1.5 py-0.5 font-mono">{f.vulnclass}</code>
</span>
)}
{f.param_id && <code className="rounded bg-muted px-1.5 py-0.5 font-mono">{f.param_id}</code>}
{f.assets && f.assets.length > 0 && (
<span className="flex flex-wrap items-center gap-1">
· Assets:
· {t("Assets:")}
{f.assets.map((a) => (
<code key={a.id} className="rounded bg-muted px-1.5 py-0.5 font-mono" title={a.type}>
{a.label}
@@ -508,12 +513,12 @@ export function FindingsTable({
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
<span className="flex items-center gap-2">
<FileTextIcon className="size-3.5" />
Detailed report
{t("Detailed report")}
</span>
{reports[rowKey]?.status === "done" && reports[rowKey]?.text.trim() && (
<CopyButton
text={reports[rowKey]?.text}
successMessage="Detailed report copied"
successMessage={t("Detailed report copied")}
variant="ghost"
className="h-6 px-2 text-xs"
/>
@@ -522,11 +527,11 @@ export function FindingsTable({
{(() => {
const rep = reports[rowKey];
if (!rep || rep.status === "loading")
return <p className="text-xs text-muted-foreground">Loading…</p>;
return <p className="text-xs text-muted-foreground">{t("Loading…")}</p>;
if (rep.status === "error")
return <p className="text-xs text-muted-foreground">Failed to load the report.</p>;
return <p className="text-xs text-muted-foreground">{t("Failed to load the report.")}</p>;
if (!rep.text.trim())
return <p className="text-xs text-muted-foreground">No detailed report yet.</p>;
return <p className="text-xs text-muted-foreground">{t("No detailed report yet.")}</p>;
return (
// break-words inherits into paragraphs/lists; pre additionally gets
// whitespace-pre-wrap so code blocks wrap too — otherwise long code lines/URLs
@@ -548,7 +553,7 @@ export function FindingsTable({
{items.length === 0 && (
<TableRow>
<TableCell colSpan={COLUMN_COUNT} className="py-12 text-center text-sm text-muted-foreground">
No matching findings.
{t("No matching findings.")}
</TableCell>
</TableRow>
)}
@@ -5,6 +5,7 @@ import * as React from "react";
import { ExplorationGraph } from "@/components/exploration-graph";
import { api } from "@/lib/api";
import type { Edge, TaskNode } from "@/lib/types";
import { t } from "@/i18n";
// FindingLineageView renders the exploration sub-graph from the task's initial
// node down to this finding's node — the same exploration graph canvas as the task graph,
@@ -35,7 +36,7 @@ export function FindingLineageView({ findingId }: { findingId: string }) {
if (loaded && nodes.length === 0) {
return (
<p className="text-muted-foreground p-6 text-sm">
No lineage to display (this vulnerability is not linked to an exploration node, or its task has been deleted).
{t("No lineage to display (this vulnerability is not linked to an exploration node, or its task has been deleted).")}
</p>
);
}
@@ -45,7 +46,7 @@ export function FindingLineageView({ findingId }: { findingId: string }) {
nodes={nodes}
edges={edges}
className="h-[68vh]"
emptyHint={loaded ? "No lineage" : "Loading…"}
emptyHint={loaded ? t("No lineage") : t("Loading…")}
/>
);
}
@@ -24,6 +24,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { api } from "@/lib/api";
import { statusMeta } from "@/lib/status";
import type { Finding, FindingReportState, FindingStatus, Severity } from "@/lib/types";
import { intlLocale, t } from "@/i18n";
import {
FINDING_REPORT_STATES,
@@ -47,7 +48,7 @@ const FINDING_STATUSES: FindingStatus[] = [
];
function fmtTime(ts: string) {
return new Date(ts).toLocaleString("zh-CN");
return new Date(ts).toLocaleString(intlLocale);
}
// FieldRow is one label/value line in the right-hand status panel.
@@ -91,10 +92,10 @@ function FindingDetailInner() {
try {
const updated = await api.setFindingSeverity(id, next);
setFinding(updated);
toast.success(`Severity changed to "${statusMeta("severity", next).label}"`);
toast.success(t('Severity changed to "{label}"', { label: statusMeta("severity", next).label }));
} catch (e) {
setFinding((cur) => (cur ? { ...cur, severity: prev } : cur));
toast.error("Update failed: " + (e as Error).message);
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
}
},
[finding, id],
@@ -108,10 +109,10 @@ function FindingDetailInner() {
try {
const updated = await api.setFindingStatus(id, next);
setFinding(updated);
toast.success(`Status changed to "${statusMeta("finding", next).label}"`);
toast.success(t('Status changed to "{label}"', { label: statusMeta("finding", next).label }));
} catch (e) {
setFinding((cur) => (cur ? { ...cur, status: prev } : cur));
toast.error("Update failed: " + (e as Error).message);
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
}
},
[finding, id],
@@ -125,10 +126,10 @@ function FindingDetailInner() {
try {
const updated = await api.setFindingReportState(id, next);
setFinding(updated);
toast.success(`Report stage changed to "${REPORT_STATE_META[next].label}"`);
toast.success(t('Report stage changed to "{label}"', { label: REPORT_STATE_META[next].label }));
} catch (e) {
setFinding((cur) => (cur ? { ...cur, report_state: prev } : cur));
toast.error("Update failed: " + (e as Error).message);
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
}
},
[finding, id],
@@ -137,11 +138,11 @@ function FindingDetailInner() {
if (!finding) {
return (
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-10 text-center">
<p className="text-muted-foreground">{loaded ? `Finding ${id} not found` : "Loading…"}</p>
<p className="text-muted-foreground">{loaded ? t("Finding {id} not found", { id }) : t("Loading…")}</p>
{loaded && (
<Button asChild variant="outline">
<Link href="/function/findings">
<ArrowLeftIcon /> Back to findings
<ArrowLeftIcon /> {t("Back to findings")}
</Link>
</Button>
)}
@@ -149,7 +150,7 @@ function FindingDetailInner() {
);
}
const title = finding.name || finding.vulnclass || "Uncategorized";
const title = finding.name || finding.vulnclass || t("Uncategorized");
return (
<Tabs value={tab} onValueChange={setTab} className="flex flex-1 flex-col gap-0">
@@ -173,12 +174,12 @@ function FindingDetailInner() {
<ReportStateBadge state={finding.report_state} />
<VerificationBadge finding={finding} />
{finding.inherited && finding.source_task_id && (
<Badge variant="outline">Source task #{finding.source_task_id} · read-only</Badge>
<Badge variant="outline">{t("Source task #{id} · read-only", { id: finding.source_task_id })}</Badge>
)}
</div>
<TabsList>
<TabsTrigger value="overview">Overview</TabsTrigger>
<TabsTrigger value="lineage">Exploration graph</TabsTrigger>
<TabsTrigger value="overview">{t("Overview")}</TabsTrigger>
<TabsTrigger value="lineage">{t("Exploration graph")}</TabsTrigger>
</TabsList>
</header>
@@ -191,16 +192,16 @@ function FindingDetailInner() {
<div className="flex flex-col gap-4 lg:col-span-2">
<Card>
<CardHeader>
<CardTitle className="text-sm">Digest</CardTitle>
<CardTitle className="text-sm">{t("Digest")}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm leading-relaxed whitespace-pre-wrap">{finding.summary || "(no digest)"}</p>
<p className="text-sm leading-relaxed whitespace-pre-wrap">{finding.summary || t("(no digest)")}</p>
</CardContent>
</Card>
<FindingRetestPanel key={id} findingId={id} readOnly={finding.inherited} onCompleted={load} />
<Card>
<CardHeader>
<CardTitle className="text-sm">Evidence / PoC</CardTitle>
<CardTitle className="text-sm">{t("Evidence / PoC")}</CardTitle>
</CardHeader>
<CardContent>
{finding.evidence ? (
@@ -208,14 +209,14 @@ function FindingDetailInner() {
{finding.evidence}
</pre>
) : (
<p className="text-sm text-muted-foreground">(no evidence)</p>
<p className="text-sm text-muted-foreground">{t("(no evidence)")}</p>
)}
</CardContent>
</Card>
{finding.counterevidence?.trim() && (
<Card>
<CardHeader>
<CardTitle className="text-sm">Counterevidence</CardTitle>
<CardTitle className="text-sm">{t("Counterevidence")}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm leading-relaxed whitespace-pre-wrap">{finding.counterevidence}</p>
@@ -225,7 +226,7 @@ function FindingDetailInner() {
{finding.confidence_rationale?.trim() && (
<Card>
<CardHeader>
<CardTitle className="text-sm">Confidence rationale</CardTitle>
<CardTitle className="text-sm">{t("Confidence rationale")}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm leading-relaxed whitespace-pre-wrap">{finding.confidence_rationale}</p>
@@ -242,19 +243,21 @@ function FindingDetailInner() {
{/* Below evidence: detailed report (rendered Markdown) */}
<Card>
<CardHeader className="flex-row items-center justify-between">
<CardTitle className="text-sm">Detailed report</CardTitle>
{finding.report && <CopyButton text={finding.report} successMessage="Detailed report copied" />}
<CardTitle className="text-sm">{t("Detailed report")}</CardTitle>
{finding.report && <CopyButton text={finding.report} successMessage={t("Detailed report copied")} />}
</CardHeader>
<CardContent>
{finding.report_stale ? (
<Alert>
<AlertDescription>Traffic evidence has changed; the detailed report is pending an update.</AlertDescription>
<AlertDescription>
{t("Traffic evidence has changed; the detailed report is pending an update.")}
</AlertDescription>
</Alert>
) : null}
{finding.report ? (
<Markdown text={finding.report} />
) : (
<p className="text-sm text-muted-foreground">No detailed report yet.</p>
<p className="text-sm text-muted-foreground">{t("No detailed report yet.")}</p>
)}
</CardContent>
</Card>
@@ -263,18 +266,18 @@ function FindingDetailInner() {
{/* Right column: status panel */}
<Card className="h-fit lg:sticky lg:top-24">
<CardHeader>
<CardTitle className="text-sm">Status</CardTitle>
<CardTitle className="text-sm">{t("Status")}</CardTitle>
</CardHeader>
<CardContent className="divide-y">
{/* Vulnerability ID */}
<FieldRow label="Vulnerability ID">
<FieldRow label={t("Vulnerability ID")}>
<code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs text-muted-foreground">
#{finding.id}
</code>
</FieldRow>
{/* Severity */}
<FieldRow label="Severity">
<FieldRow label={t("Severity")}>
{finding.inherited ? (
<StatusBadge domain="severity" value={finding.severity} dot />
) : (
@@ -296,7 +299,7 @@ function FindingDetailInner() {
</FieldRow>
{/* Triage status */}
<FieldRow label="Triage status">
<FieldRow label={t("Triage status")}>
{finding.inherited ? (
<StatusBadge domain="finding" value={finding.status} dot />
) : (
@@ -317,7 +320,7 @@ function FindingDetailInner() {
)}
</FieldRow>
<FieldRow label="Report stage">
<FieldRow label={t("Report stage")}>
{finding.inherited ? (
<ReportStateBadge state={finding.report_state} />
) : (
@@ -343,7 +346,7 @@ function FindingDetailInner() {
{/* Verification: automated outcome; the note explains any state other than verified */}
{finding.verification_status && (
<FieldRow label="Verification">
<FieldRow label={t("Verification")}>
<VerificationBadge finding={finding} />
{finding.verification_status !== "verified" && finding.verification_note?.trim() && (
<p className="whitespace-pre-wrap break-words text-muted-foreground text-xs">
@@ -354,7 +357,7 @@ function FindingDetailInner() {
)}
{/* Vulnerability type */}
<FieldRow label="Vulnerability type">
<FieldRow label={t("Vulnerability type")}>
{finding.vulnclass ? (
<code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">{finding.vulnclass}</code>
) : (
@@ -363,7 +366,7 @@ function FindingDetailInner() {
</FieldRow>
{/* Assets */}
<FieldRow label="Assets">
<FieldRow label={t("Assets")}>
{finding.assets && finding.assets.length > 0 ? (
<div className="flex flex-wrap justify-end gap-1">
{finding.assets.map((a) => (
@@ -382,7 +385,7 @@ function FindingDetailInner() {
</FieldRow>
{/* Task */}
<FieldRow label="Task">
<FieldRow label={t("Task")}>
{finding.task_id ? (
<Link
href={`/function/tasks/detail?id=${finding.task_id}`}
@@ -393,12 +396,12 @@ function FindingDetailInner() {
<ArrowUpRightIcon className="size-3 shrink-0" />
</Link>
) : (
<span className="text-muted-foreground">— (task deleted)</span>
<span className="text-muted-foreground">{t("— (task deleted)")}</span>
)}
</FieldRow>
{/* Found at */}
<FieldRow label="Found at">
<FieldRow label={t("Found at")}>
<span className="tabular-nums">{fmtTime(finding.ts)}</span>
</FieldRow>
</CardContent>
+109 -99
View File
@@ -73,6 +73,7 @@ import {
VERIFICATION_STATUSES,
} from "./_components/findings-table";
import { setVisibleInterval } from "@/lib/polling";
import { t } from "@/i18n";
const FINDING_LIST_PREFERENCE_KEY = "artex_finding_list_preferences";
@@ -201,7 +202,7 @@ export default function FindingsPage() {
setActiveRetests(Object.fromEntries(rows.map((item) => [item.finding_id, item])));
failed = false;
} catch (error) {
if (!disposed && !failed) toast.error(`Failed to load retest status: ${(error as Error).message}`);
if (!disposed && !failed) toast.error(t("Failed to load retest status: {error}", { error: (error as Error).message }));
failed = true;
} finally {
if (!disposed) timer = setTimeout(() => void refreshRetests(), 3000);
@@ -324,9 +325,9 @@ export default function FindingsPage() {
ids: [...selectedIds],
});
setExportOpen(false);
toast.success("Export download started");
toast.success(t("Export download started"));
} catch (e) {
toast.error(`Export failed: ${(e as Error).message}`);
toast.error(t("Export failed: {error}", { error: (e as Error).message }));
} finally {
setExporting(false);
}
@@ -420,7 +421,7 @@ export default function FindingsPage() {
} catch (e) {
if (request !== assetTreeRequest.current || activeFilterFingerprint.current !== requestFilter) return;
setAssetTree((current) => ({ ...current, loading: false }));
toast.error(`Failed to load the asset tree: ${(e as Error).message}`);
toast.error(t("Failed to load the asset tree: {error}", { error: (e as Error).message }));
}
}, [filterFingerprint, reportState, severity, status, verificationStatus, vulnclass, task, query, sort]);
@@ -669,7 +670,7 @@ export default function FindingsPage() {
setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, status: next } : x)));
try {
await api.setFindingStatus(f.finding_id, next);
toast.success(`Marked as "${statusMeta("finding", next).label}"`);
toast.success(t('Marked as "{label}"', { label: statusMeta("finding", next).label }));
// refresh stat cards (pending count) and drop the row if it no longer matches the status filter
api
.findingStats()
@@ -685,7 +686,7 @@ export default function FindingsPage() {
refreshAfterMutation(f);
} catch (e) {
setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, status: prev } : x)));
toast.error(`Update failed: ${(e as Error).message}`);
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
}
},
[refreshAfterMutation, setFindings, status],
@@ -698,7 +699,7 @@ export default function FindingsPage() {
setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, report_state: next } : x)));
try {
await api.setFindingReportState(f.finding_id, next);
toast.success(`Report stage set to "${REPORT_STATE_META[next].label}"`);
toast.success(t('Report stage set to "{label}"', { label: REPORT_STATE_META[next].label }));
api
.findingStats()
.then(setStats)
@@ -713,7 +714,7 @@ export default function FindingsPage() {
refreshAfterMutation(f);
} catch (e) {
setFindings((cur) => cur.map((x) => (isSameFinding(x, f) ? { ...x, report_state: prev } : x)));
toast.error(`Update failed: ${(e as Error).message}`);
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
}
},
[refreshAfterMutation, reportState, setFindings],
@@ -729,9 +730,7 @@ export default function FindingsPage() {
const r = await api.bulkSetFindingStatus([...selectedIds], next);
setSelectedIds(new Set());
const label = statusMeta("finding", next).label;
toast.success(
r.updated === 1 ? `Marked 1 finding as "${label}"` : `Marked ${r.updated} findings as "${label}"`,
);
toast.success(t('Marked {count} findings as "{label}"', { count: r.updated, label }));
void loadFlat();
if (view === "asset") void loadAssetTree();
api
@@ -741,7 +740,7 @@ export default function FindingsPage() {
// The list reload remains valid even if the aggregate refresh fails.
});
} catch (e) {
toast.error(`Bulk update failed: ${(e as Error).message}`);
toast.error(t("Bulk update failed: {error}", { error: (e as Error).message }));
} finally {
setBulkBusy(false);
}
@@ -757,11 +756,7 @@ export default function FindingsPage() {
const r = await api.bulkSetFindingReportState([...selectedIds], next);
setSelectedIds(new Set());
const label = REPORT_STATE_META[next].label;
toast.success(
r.updated === 1
? `Set report stage of 1 finding to "${label}"`
: `Set report stage of ${r.updated} findings to "${label}"`,
);
toast.success(t('Set report stage of {count} findings to "{label}"', { count: r.updated, label }));
void loadFlat();
if (view === "asset") void loadAssetTree();
api
@@ -771,7 +766,7 @@ export default function FindingsPage() {
// The list reload remains valid even if the aggregate refresh fails.
});
} catch (e) {
toast.error(`Bulk update failed: ${(e as Error).message}`);
toast.error(t("Bulk update failed: {error}", { error: (e as Error).message }));
} finally {
setBulkBusy(false);
}
@@ -828,7 +823,7 @@ export default function FindingsPage() {
: x,
),
);
toast.success("Saved");
toast.success(t("Saved"));
api
.findingStats()
.then(setStats)
@@ -837,7 +832,7 @@ export default function FindingsPage() {
});
refreshAfterMutation(f);
} catch (e) {
toast.error(`Save failed: ${(e as Error).message}`);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
}
@@ -861,7 +856,7 @@ export default function FindingsPage() {
setFlat((cur) => ({ ...cur, total: Math.max(0, cur.total - 1) }));
const rowKey = findingRowKey(f);
setExpanded((cur) => (cur === rowKey ? null : cur));
toast.success("Vulnerability deleted");
toast.success(t("Vulnerability deleted"));
api
.findingStats()
.then(setStats)
@@ -870,7 +865,7 @@ export default function FindingsPage() {
});
refreshAfterMutation(f, true);
} catch (e) {
toast.error(`Delete failed: ${(e as Error).message}`);
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
}
},
[refreshAfterMutation, setFindings],
@@ -888,28 +883,28 @@ export default function FindingsPage() {
const result = await api.deepenFinding(deepenFinding.finding_id, deepenDescription.trim());
toast.success(
result.queued
? `Deepen intent #${result.intent_id} has entered the task queue`
: `Created high-priority worker intent #${result.intent_id}`,
? t("Deepen intent #{id} has entered the task queue", { id: result.intent_id })
: t("Created high-priority worker intent #{id}", { id: result.intent_id }),
);
refreshAfterMutation(deepenFinding);
setDeepenFinding(null);
setDeepenDescription("");
} catch (error) {
toast.error(`Submit failed: ${(error as Error).message}`);
toast.error(t("Submit failed: {error}", { error: (error as Error).message }));
} finally {
setDeepening(false);
}
}
const statCards = [
{ label: "Total findings", value: stats.total, icon: BugIcon },
{ label: "Pending", value: stats.pending, tone: "text-amber-500", icon: ClockIcon },
{ label: "Submitted", value: stats.submitted, tone: "text-amber-500", icon: FileUpIcon },
{ label: "Accepted", value: stats.accepted, tone: "text-emerald-500", icon: CircleCheckIcon },
{ label: "Critical", value: stats.critical, tone: "text-rose-600", icon: ShieldAlertIcon },
{ label: "High", value: stats.high, tone: "text-red-500", icon: TriangleAlertIcon },
{ label: "Medium", value: stats.medium, tone: "text-amber-500", icon: TriangleAlertIcon },
{ label: "Low", value: stats.low, tone: "text-slate-500", icon: InfoIcon },
{ label: t("Total findings"), value: stats.total, icon: BugIcon },
{ label: t("Pending"), value: stats.pending, tone: "text-amber-500", icon: ClockIcon },
{ label: t("Submitted"), value: stats.submitted, tone: "text-amber-500", icon: FileUpIcon },
{ label: t("Accepted"), value: stats.accepted, tone: "text-emerald-500", icon: CircleCheckIcon },
{ label: t("Critical"), value: stats.critical, tone: "text-rose-600", icon: ShieldAlertIcon },
{ label: t("High"), value: stats.high, tone: "text-red-500", icon: TriangleAlertIcon },
{ label: t("Medium"), value: stats.medium, tone: "text-amber-500", icon: TriangleAlertIcon },
{ label: t("Low"), value: stats.low, tone: "text-slate-500", icon: InfoIcon },
];
// The "current filter" count in the export dialog: both views share the same filters, only the counting source differs.
@@ -949,7 +944,7 @@ export default function FindingsPage() {
</div>
) : (
<>
<FindingsTable items={flat.items} selectAllLabel="Select all on this page" {...rowProps} />
<FindingsTable items={flat.items} selectAllLabel={t("Select all on this page")} {...rowProps} />
<TablePagination
page={flatPage}
pageSize={flatPageSize}
@@ -971,14 +966,14 @@ export default function FindingsPage() {
<div className="flex flex-1 flex-col gap-4 md:gap-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-xl font-semibold tracking-tight">Findings</h1>
<p className="text-muted-foreground text-sm">Cross-task vulnerability overview</p>
<h1 className="text-xl font-semibold tracking-tight">{t("Findings")}</h1>
<p className="text-muted-foreground text-sm">{t("Cross-task vulnerability overview")}</p>
</div>
<Tabs value={view} onValueChange={(v) => setView(v as FindingView)}>
<TabsList>
<TabsTrigger value="flat">All findings</TabsTrigger>
<TabsTrigger value="grouped">By task</TabsTrigger>
<TabsTrigger value="asset">By asset</TabsTrigger>
<TabsTrigger value="flat">{t("All findings")}</TabsTrigger>
<TabsTrigger value="grouped">{t("By task")}</TabsTrigger>
<TabsTrigger value="asset">{t("By asset")}</TabsTrigger>
</TabsList>
</Tabs>
</div>
@@ -1006,8 +1001,8 @@ export default function FindingsPage() {
type="search"
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Search findings"
aria-label="Search findings"
placeholder={t("Search findings")}
aria-label={t("Search findings")}
/>
<InputGroupAddon>
<SearchIcon aria-hidden="true" />
@@ -1024,14 +1019,14 @@ export default function FindingsPage() {
>
{(
[
["all", "All"],
["critical", "Critical"],
["high", "High"],
["medium", "Medium"],
["low", "Low"],
["all", t("All")],
["critical", t("Critical")],
["high", t("High")],
["medium", t("Medium")],
["low", t("Low")],
] as const
).map(([val, label]) => (
<ToggleGroupItem key={val} value={val} aria-label={`Filter by ${label} severity`}>
<ToggleGroupItem key={val} value={val} aria-label={t("Filter by {label} severity", { label })}>
{label}
</ToggleGroupItem>
))}
@@ -1039,10 +1034,10 @@ export default function FindingsPage() {
<Select value={status} onValueChange={(v) => setStatus(v as "all" | FindingStatus)}>
<SelectTrigger size="sm" className="w-32">
<SelectValue placeholder="Status" />
<SelectValue placeholder={t("Status")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All statuses</SelectItem>
<SelectItem value="all">{t("All statuses")}</SelectItem>
{FINDING_STATUSES.map((st) => (
<SelectItem key={st} value={st}>
{statusMeta("finding", st).label}
@@ -1053,10 +1048,10 @@ export default function FindingsPage() {
<Select value={reportState} onValueChange={(v) => setReportState(v as "all" | FindingReportState)}>
<SelectTrigger size="sm" className="w-40">
<SelectValue placeholder="Report stage" />
<SelectValue placeholder={t("Report stage")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All report stages</SelectItem>
<SelectItem value="all">{t("All report stages")}</SelectItem>
{FINDING_REPORT_STATES.map((st) => (
<SelectItem key={st} value={st}>
{REPORT_STATE_META[st].label}
@@ -1070,10 +1065,10 @@ export default function FindingsPage() {
onValueChange={(v) => setVerificationStatus(v as "all" | VerificationStatus)}
>
<SelectTrigger size="sm" className="w-48">
<SelectValue placeholder="Verification" />
<SelectValue placeholder={t("Verification")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All verification states</SelectItem>
<SelectItem value="all">{t("All verification states")}</SelectItem>
{VERIFICATION_STATUSES.map((st) => (
<SelectItem key={st} value={st}>
{VERIFICATION_META[st].label}
@@ -1084,10 +1079,10 @@ export default function FindingsPage() {
<Select value={vulnclass} onValueChange={setVulnclass}>
<SelectTrigger size="sm" className="w-40">
<SelectValue placeholder="Vulnerability type" />
<SelectValue placeholder={t("Vulnerability type")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All types</SelectItem>
<SelectItem value="all">{t("All types")}</SelectItem>
{stats.vulnclasses.map((vc) => (
<SelectItem key={vc} value={vc}>
{vc}
@@ -1098,14 +1093,14 @@ export default function FindingsPage() {
<Select value={task} onValueChange={setTask}>
<SelectTrigger size="sm" className="w-48">
<SelectValue placeholder="Task" />
<SelectValue placeholder={t("Task")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All tasks</SelectItem>
<SelectItem value={UNASSIGNED_TASK}>Unlinked / task deleted</SelectItem>
{(stats.tasks ?? []).map((t) => {
const id = String(t.id);
const label = t.name || t.description || `Task #${id} (deleted)`;
<SelectItem value="all">{t("All tasks")}</SelectItem>
<SelectItem value={UNASSIGNED_TASK}>{t("Unlinked / task deleted")}</SelectItem>
{(stats.tasks ?? []).map((option) => {
const id = String(option.id);
const label = option.name || option.description || t("Task #{id} (deleted)", { id });
return (
<SelectItem key={id} value={id}>
<span className="flex w-full items-center gap-2">
@@ -1114,7 +1109,7 @@ export default function FindingsPage() {
</span>
<span className="inline-flex items-center gap-1 text-muted-foreground tabular-nums">
<BugIcon className="size-3.5" aria-hidden="true" />
{t.count}
{option.count}
</span>
</span>
</SelectItem>
@@ -1128,15 +1123,17 @@ export default function FindingsPage() {
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="severity">By severity</SelectItem>
<SelectItem value="time">By time</SelectItem>
<SelectItem value="severity">{t("By severity")}</SelectItem>
<SelectItem value="time">{t("By time")}</SelectItem>
</SelectContent>
</Select>
<div className="ml-auto flex items-center gap-3">
{selectedIds.size > 0 && (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground tabular-nums">{selectedIds.size} selected</span>
<span className="text-xs text-muted-foreground tabular-nums">
{t("{count} selected", { count: selectedIds.size })}
</span>
<Select
value=""
onValueChange={(v) => {
@@ -1144,8 +1141,8 @@ export default function FindingsPage() {
}}
disabled={bulkBusy}
>
<SelectTrigger size="sm" className="w-40" aria-label="Set the status of the selected findings">
<SelectValue placeholder={bulkBusy ? "Updating…" : "Set status"} />
<SelectTrigger size="sm" className="w-40" aria-label={t("Set the status of the selected findings")}>
<SelectValue placeholder={bulkBusy ? t("Updating…") : t("Set status")} />
</SelectTrigger>
<SelectContent>
{FINDING_STATUSES.map((st) => (
@@ -1162,8 +1159,8 @@ export default function FindingsPage() {
}}
disabled={bulkBusy}
>
<SelectTrigger size="sm" className="w-44" aria-label="Set the report stage of the selected findings">
<SelectValue placeholder={bulkBusy ? "Updating…" : "Set report stage"} />
<SelectTrigger size="sm" className="w-44" aria-label={t("Set the report stage of the selected findings")}>
<SelectValue placeholder={bulkBusy ? t("Updating…") : t("Set report stage")} />
</SelectTrigger>
<SelectContent>
{FINDING_REPORT_STATES.map((st) => (
@@ -1176,7 +1173,7 @@ export default function FindingsPage() {
</div>
)}
<Button size="sm" variant="outline" onClick={openExport}>
<DownloadIcon /> Export
<DownloadIcon /> {t("Export")}
</Button>
</div>
</div>
@@ -1212,7 +1209,7 @@ export default function FindingsPage() {
className={cn("hover:text-foreground", assetScope === null && "font-medium text-foreground")}
onClick={() => setAssetScope(null)}
>
All assets
{t("All assets")}
</button>
{assetPath.map((node) => (
<React.Fragment key={node.key}>
@@ -1230,7 +1227,7 @@ export default function FindingsPage() {
</button>
</React.Fragment>
))}
<span className="ml-auto shrink-0 text-xs tabular-nums">{flat.total} in total</span>
<span className="ml-auto shrink-0 text-xs tabular-nums">{t("{count} in total", { count: flat.total })}</span>
</div>
{flatListCard}
</div>
@@ -1269,13 +1266,13 @@ export default function FindingsPage() {
<div className="flex min-w-0 flex-col gap-1">
<CardTitle className="truncate text-sm">
{group.task_id === null
? "Unlinked / task deleted"
? t("Unlinked / task deleted")
: group.task_name
? `${group.task_name} (task #${group.task_id})`
: `Task #${group.task_id}`}
? t("{name} (task #{id})", { name: group.task_name, id: group.task_id })
: t("Task #{id}", { id: group.task_id })}
</CardTitle>
<CardDescription className="truncate" title={group.task_description}>
{group.task_description || "Source task unavailable"}
{group.task_description || t("Source task unavailable")}
</CardDescription>
</div>
</button>
@@ -1298,7 +1295,7 @@ export default function FindingsPage() {
<Button size="icon-sm" variant="ghost" asChild>
<Link
href={`/function/tasks/detail?id=${group.task_id}`}
aria-label={`View task #${group.task_id}`}
aria-label={t("View task #{id}", { id: group.task_id })}
>
<ArrowUpRightIcon />
</Link>
@@ -1315,7 +1312,11 @@ export default function FindingsPage() {
</div>
) : (
<>
<FindingsTable items={state.items} selectAllLabel="Select all on this page in this group" {...rowProps} />
<FindingsTable
items={state.items}
selectAllLabel={t("Select all on this page in this group")}
{...rowProps}
/>
<TablePagination
page={state.page}
pageSize={state.pageSize}
@@ -1332,7 +1333,7 @@ export default function FindingsPage() {
})}
{groups.length === 0 && (
<Card>
<CardContent className="py-12 text-center text-sm text-muted-foreground">No matching findings.</CardContent>
<CardContent className="py-12 text-center text-sm text-muted-foreground">{t("No matching findings.")}</CardContent>
</Card>
)}
<TablePagination
@@ -1381,25 +1382,30 @@ export default function FindingsPage() {
>
<DialogContent>
<DialogHeader>
<DialogTitle>Deepen exploitation</DialogTitle>
<DialogTitle>{t("Deepen exploitation")}</DialogTitle>
<DialogDescription className="break-words">
A priority-10 worker intent will be created in the original task #{deepenFinding?.task_id} to run secondary verification based on this vulnerability:
{t(
"A priority-10 worker intent will be created in the original task #{id} to run secondary verification based on this vulnerability:",
{ id: deepenFinding?.task_id ?? "" },
)}{" "}
{deepenFinding?.name || deepenFinding?.vulnclass || deepenFinding?.summary}
</DialogDescription>
</DialogHeader>
<FieldGroup>
<Field>
<FieldLabel htmlFor="finding-deepen-description">Exploitation description</FieldLabel>
<FieldLabel htmlFor="finding-deepen-description">{t("Exploitation description")}</FieldLabel>
<Textarea
id="finding-deepen-description"
value={deepenDescription}
onChange={(event) => setDeepenDescription(event.target.value)}
maxLength={4000}
placeholder="Describe the exploitation path to verify, boundary conditions, targets, or expected evidence"
placeholder={t(
"Describe the exploitation path to verify, boundary conditions, targets, or expected evidence",
)}
disabled={deepening}
/>
<FieldDescription className="flex justify-between gap-3">
<span>The new intent inherits this vulnerability's asset anchors.</span>
<span>{t("The new intent inherits this vulnerability's asset anchors.")}</span>
<span className="shrink-0 tabular-nums">{deepenDescription.length} / 4000</span>
</FieldDescription>
</Field>
@@ -1413,11 +1419,11 @@ export default function FindingsPage() {
}}
disabled={deepening}
>
Cancel
{t("Cancel")}
</Button>
<Button onClick={submitDeepen} disabled={deepening || !deepenDescription.trim()}>
{deepening && <Spinner data-icon="inline-start" />}
Create deepen intent
{t("Create deepen intent")}
</Button>
</DialogFooter>
</DialogContent>
@@ -1426,42 +1432,46 @@ export default function FindingsPage() {
<Dialog open={exportOpen} onOpenChange={setExportOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Export findings</DialogTitle>
<DialogDescription>Choose the export scope and format; the browser downloads the file automatically once generated.</DialogDescription>
<DialogTitle>{t("Export findings")}</DialogTitle>
<DialogDescription>
{t("Choose the export scope and format; the browser downloads the file automatically once generated.")}
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-5 py-1">
<div className="flex flex-col gap-2">
<span className="text-xs text-muted-foreground">Export scope</span>
<span className="text-xs text-muted-foreground">{t("Export scope")}</span>
<RadioGroup value={exportScope} onValueChange={(v) => setExportScope(v as typeof exportScope)}>
<label htmlFor="export-scope-filtered" className="flex items-center gap-2 text-sm">
<RadioGroupItem id="export-scope-filtered" value="filtered" /> Export the current filter results ({filteredTotal}{" "}
items)
<RadioGroupItem id="export-scope-filtered" value="filtered" />{" "}
{t("Export the current filter results ({count} items)", { count: filteredTotal })}
</label>
<label htmlFor="export-scope-all" className="flex items-center gap-2 text-sm">
<RadioGroupItem id="export-scope-all" value="all" /> Export all
<RadioGroupItem id="export-scope-all" value="all" /> {t("Export all")}
</label>
<label
htmlFor="export-scope-selected"
className={cn("flex items-center gap-2 text-sm", selectedIds.size === 0 && "text-muted-foreground")}
>
<RadioGroupItem id="export-scope-selected" value="selected" disabled={selectedIds.size === 0} />
Export the {selectedIds.size} selected items
{t("Export the {count} selected items", { count: selectedIds.size })}
</label>
</RadioGroup>
</div>
<div className="flex flex-col gap-2">
<span className="text-xs text-muted-foreground">Export format</span>
<span className="text-xs text-muted-foreground">{t("Export format")}</span>
<RadioGroup value={exportFormat} onValueChange={(v) => setExportFormat(v as typeof exportFormat)}>
<label htmlFor="export-format-md-single" className="flex items-center gap-2 text-sm">
<RadioGroupItem id="export-format-md-single" value="md-single" /> Markdown summary report (a single .md file)
<RadioGroupItem id="export-format-md-single" value="md-single" />{" "}
{t("Markdown summary report (a single .md file)")}
</label>
<label htmlFor="export-format-md-zip" className="flex items-center gap-2 text-sm">
<RadioGroupItem id="export-format-md-zip" value="md-zip" /> Markdown per finding (one .md per vulnerability, packaged as .zip)
<RadioGroupItem id="export-format-md-zip" value="md-zip" />{" "}
{t("Markdown per finding (one .md per vulnerability, packaged as .zip)")}
</label>
<label htmlFor="export-format-csv" className="flex items-center gap-2 text-sm">
<RadioGroupItem id="export-format-csv" value="csv" /> CSV table (.csv)
<RadioGroupItem id="export-format-csv" value="csv" /> {t("CSV table (.csv)")}
</label>
<label htmlFor="export-format-json" className="flex items-center gap-2 text-sm">
<RadioGroupItem id="export-format-json" value="json" /> JSON (.json)
@@ -1472,10 +1482,10 @@ export default function FindingsPage() {
<DialogFooter>
<Button variant="outline" onClick={() => setExportOpen(false)} disabled={exporting}>
Cancel
{t("Cancel")}
</Button>
<Button onClick={doExport} disabled={exporting || (exportScope === "selected" && selectedIds.size === 0)}>
<DownloadIcon /> {exporting ? "Exporting…" : "Export"}
<DownloadIcon /> {exporting ? t("Exporting…") : t("Export")}
</Button>
</DialogFooter>
</DialogContent>
@@ -45,11 +45,12 @@ import {
SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { intlLocale, t } from "@/i18n";
import { api } from "@/lib/api";
import type { LLMRecordItem, LLMRecordDetail, LLMTask } from "@/lib/types";
function fmtTime(ts: string) {
return new Date(ts).toLocaleString("zh-CN", {
return new Date(ts).toLocaleString(intlLocale, {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
@@ -109,7 +110,7 @@ function CopyButton({ text }: { text: string }) {
size="icon"
className="size-5 shrink-0"
disabled={disabled}
title={copied ? "Copied" : "Copy content"}
title={copied ? t("Copied") : t("Copy content")}
onClick={copy}
>
{copied ? <CheckIcon className="size-3 text-emerald-600" /> : <CopyIcon className="size-3" />}
@@ -267,7 +268,7 @@ export default function LLMRecordsPage() {
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-2">
<RadioIcon className="h-5 w-5 text-muted-foreground" />
<h1 className="text-xl font-semibold tracking-tight">LLM recording</h1>
<h1 className="text-xl font-semibold tracking-tight">{t("LLM recording")}</h1>
<Badge variant="secondary">{total}</Badge>
</div>
</div>
@@ -277,26 +278,26 @@ export default function LLMRecordsPage() {
<div className="relative max-w-sm flex-1">
<SearchIcon className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search Session ID..."
placeholder={t("Search Session ID...")}
value={session}
onChange={(e) => setSession(e.target.value)}
className="h-8 pl-8"
/>
</div>
<Input
placeholder="Model"
placeholder={t("Model")}
className="h-8 w-48"
value={model}
onChange={(e) => setModel(e.target.value)}
/>
<Select value={pickedTask} onValueChange={setPickedTask}>
<SelectTrigger size="sm" className="w-56">
<SelectValue placeholder="Select a task…" />
<SelectValue placeholder={t("Select a task…")} />
</SelectTrigger>
<SelectContent>
{tasks.length === 0 ? (
<SelectItem value="__none__" disabled>
No task records yet
{t("No task records yet")}
</SelectItem>
) : (
tasks.map((t) => (
@@ -313,11 +314,11 @@ export default function LLMRecordsPage() {
size="sm"
className="h-8"
disabled={!pickedTask || deleting}
title={pickedTask ? undefined : "Select a task above first"}
title={pickedTask ? undefined : t("Select a task above first")}
onClick={() => setDeleteOpen(true)}
>
<Trash2Icon className="size-3.5" />
Delete task conversations
{t("Delete task conversations")}
</Button>
<Select value={String(size)} onValueChange={(v) => setSize(Number(v))}>
<SelectTrigger size="sm" className="w-28">
@@ -326,7 +327,7 @@ export default function LLMRecordsPage() {
<SelectContent>
{PAGE_SIZES.map((n) => (
<SelectItem key={n} value={String(n)}>
{n} / page
{t("{count} / page", { count: n })}
</SelectItem>
))}
</SelectContent>
@@ -348,7 +349,7 @@ export default function LLMRecordsPage() {
recEnabled ? "text-foreground" : "text-muted-foreground",
)}
>
{recEnabled ? "Recording" : "Off"}
{recEnabled ? t("Recording") : t("Off")}
</label>
</div>
@@ -387,14 +388,14 @@ export default function LLMRecordsPage() {
<Table>
<TableHeader className="sticky top-0 z-10 bg-card">
<TableRow>
<TableHead className="w-[130px]">Time</TableHead>
<TableHead className="w-[60px]">Task</TableHead>
<TableHead className="w-[90px]">Worker</TableHead>
<TableHead className="w-[100px]">Profile</TableHead>
<TableHead className="w-[140px]">Model</TableHead>
<TableHead className="w-[70px]">Latency</TableHead>
<TableHead className="w-[90px]">Tokens</TableHead>
<TableHead className="w-[60px]">Status</TableHead>
<TableHead className="w-[130px]">{t("Time")}</TableHead>
<TableHead className="w-[60px]">{t("Task")}</TableHead>
<TableHead className="w-[90px]">{t("Worker")}</TableHead>
<TableHead className="w-[100px]">{t("Profile")}</TableHead>
<TableHead className="w-[140px]">{t("Model")}</TableHead>
<TableHead className="w-[70px]">{t("Latency")}</TableHead>
<TableHead className="w-[90px]">{t("Tokens")}</TableHead>
<TableHead className="w-[60px]">{t("Status")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -408,8 +409,8 @@ export default function LLMRecordsPage() {
<TableRow>
<TableCell colSpan={8} className="py-12 text-center text-sm text-muted-foreground">
{!recKnown || recEnabled
? "No LLM call records yet"
: "LLM call recording is off. Turn on the Recording toggle above to start capturing calls."}
? t("No LLM call records yet")
: t("LLM call recording is off. Turn on the Recording toggle above to start capturing calls.")}
</TableCell>
</TableRow>
) : (
@@ -451,9 +452,9 @@ export default function LLMRecordsPage() {
</TableCell>
<TableCell>
{rec.status === "ok" ? (
<Badge variant="secondary" className="text-xs text-emerald-600">OK</Badge>
<Badge variant="secondary" className="text-xs text-emerald-600">{t("OK")}</Badge>
) : (
<Badge variant="destructive" className="text-xs">Error</Badge>
<Badge variant="destructive" className="text-xs">{t("Error")}</Badge>
)}
</TableCell>
</TableRow>
@@ -480,7 +481,7 @@ export default function LLMRecordsPage() {
</Badge>
{selected.task_id && (
<Badge variant="outline" className="text-xs font-mono">
Task #{selected.task_id}
{t("Task #{id}", { id: selected.task_id })}
</Badge>
)}
<span className="text-xs text-muted-foreground">
@@ -490,9 +491,9 @@ export default function LLMRecordsPage() {
{fmtLatency(selected.latency_ms)}
</span>
{selected.status === "ok" ? (
<Badge variant="secondary" className="text-xs text-emerald-600">OK</Badge>
<Badge variant="secondary" className="text-xs text-emerald-600">{t("OK")}</Badge>
) : (
<Badge variant="destructive" className="text-xs">Error</Badge>
<Badge variant="destructive" className="text-xs">{t("Error")}</Badge>
)}
{/* Raw view toggle. Old records have no raw data; disable it rather than silently
falling back, to avoid looking like "raw matches parsed". */}
@@ -501,10 +502,14 @@ export default function LLMRecordsPage() {
size="sm"
className="ml-auto h-7 shrink-0 text-xs"
disabled={!hasRaw}
title={hasRaw ? "View the raw HTTP actually exchanged with the provider" : "This record was captured before the feature launched; no raw data"}
title={
hasRaw
? t("View the raw HTTP actually exchanged with the provider")
: t("This record was captured before the feature launched; no raw data")
}
onClick={() => setRawView((v) => !v)}
>
Raw
{t("Raw")}
</Button>
<Button
variant="ghost"
@@ -519,39 +524,39 @@ export default function LLMRecordsPage() {
<div className="grid min-h-0 flex-1 grid-cols-2 divide-x">
<div className="flex min-h-0 min-w-0 flex-col">
<div className="flex items-center gap-2 border-b py-0.5 pr-1.5 pl-3 text-[11px] font-medium text-muted-foreground">
<span>Request{showRaw && " · raw"}</span>
<span>{showRaw ? t("Request · raw") : t("Request")}</span>
<CopyButton text={reqText || ""} />
</div>
<div className="min-h-0 flex-1 overflow-auto">
{detailLoading ? (
<div className="flex items-center gap-2 p-3 text-xs text-muted-foreground">
<Loader2Icon className="size-3.5 animate-spin" />
Loading…
{t("Loading…")}
</div>
) : (
<pre className="p-3 font-mono text-xs break-all whitespace-pre-wrap">
{reqText || "(empty)"}
{reqText || t("(empty)")}
</pre>
)}
</div>
</div>
<div className="flex min-h-0 min-w-0 flex-col">
<div className="flex items-center gap-2 border-b py-0.5 pr-1.5 pl-3 text-[11px] font-medium text-muted-foreground">
<span>Response{showRaw && " · raw (SSE)"}</span>
<span>{showRaw ? t("Response · raw (SSE)") : t("Response")}</span>
<CopyButton text={respText || ""} />
</div>
<div className="min-h-0 flex-1 overflow-auto">
{detailLoading ? (
<div className="flex items-center gap-2 p-3 text-xs text-muted-foreground">
<Loader2Icon className="size-3.5 animate-spin" />
Loading…
{t("Loading…")}
</div>
) : (
<pre className={cn(
"p-3 font-mono text-xs break-all whitespace-pre-wrap",
selected.status !== "ok" && "text-red-600 dark:text-red-400",
)}>
{respText || "(empty)"}
{respText || t("(empty)")}
</pre>
)}
</div>
@@ -564,13 +569,15 @@ export default function LLMRecordsPage() {
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete all LLM conversations for task "{pickedTask}"?</AlertDialogTitle>
<AlertDialogTitle>{t('Delete all LLM conversations for task "{task}"?', { task: pickedTask })}</AlertDialogTitle>
<AlertDialogDescription>
This will permanently delete all LLM call records for this task (including raw requests/responses). This action cannot be undone.
{t(
"This will permanently delete all LLM call records for this task (including raw requests/responses). This action cannot be undone.",
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
<AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault();
@@ -579,7 +586,7 @@ export default function LLMRecordsPage() {
disabled={deleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleting ? "Deleting…" : "Confirm delete"}
{deleting ? t("Deleting…") : t("Confirm delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
+63 -53
View File
@@ -15,6 +15,7 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { api } from "@/lib/api";
import type { SSProject, SSTask } from "@/lib/types";
import { t } from "@/i18n";
type SSStatus = {
exists: boolean;
@@ -28,17 +29,17 @@ type SSStatus = {
type Dimension = "project" | "task";
const ASSET_TYPES: { key: string; label: string }[] = [
{ key: "subdomain", label: "Subdomain" },
{ key: "service", label: "Service" },
{ key: "app", label: "App" },
{ key: "subdomain", label: t("Subdomain") },
{ key: "service", label: t("Service") },
{ key: "app", label: t("App") },
];
export default function AssetSyncPage() {
return (
<div className="p-4 md:p-6">
<div className="mb-4">
<h1 className="font-semibold text-xl">Asset sync</h1>
<p className="text-muted-foreground text-sm">Sync assets into the store from external data sources</p>
<h1 className="font-semibold text-xl">{t("Asset sync")}</h1>
<p className="text-muted-foreground text-sm">{t("Sync assets into the store from external data sources")}</p>
</div>
<Tabs defaultValue="scopesentry">
<TabsList>
@@ -61,7 +62,7 @@ function ScopeSentryPanel() {
api
.ssStatus()
.then(setStatus)
.catch((e) => toast.error(`Failed to read data source status: ${e.message}`))
.catch((e) => toast.error(t("Failed to read data source status: {error}", { error: e.message })))
.finally(() => setLoadingStatus(false));
}, []);
@@ -79,7 +80,7 @@ function ScopeSentryPanel() {
) : (
<Card>
<CardContent className="py-8 text-center text-muted-foreground text-sm">
Once the data source is ready, you can pick projects / tasks to sync.
{t("Once the data source is ready, you can pick projects / tasks to sync.")}
</CardContent>
</Card>
)}
@@ -110,25 +111,25 @@ function DataSourceCard({
setBusy(true);
try {
await api.ssDatasource({});
toast.success("ScopeSentry data source created; fill in the URL and key");
toast.success(t("ScopeSentry data source created; fill in the URL and key"));
onChanged();
} catch (e) {
toast.error(`Create failed: ${(e as Error).message}`);
toast.error(t("Create failed: {error}", { error: (e as Error).message }));
} finally {
setBusy(false);
}
};
const save = async () => {
if (!url.trim()) return toast.error("Please enter the MCP URL");
if (!url.trim()) return toast.error(t("Please enter the MCP URL"));
setBusy(true);
try {
const r = await api.ssDatasource({ url: url.trim(), api_key: apiKey.trim() });
toast.success(r.enabled ? "Data source saved and enabled" : "Saved (enable conditions not yet met)");
toast.success(r.enabled ? t("Data source saved and enabled") : t("Saved (enable conditions not yet met)"));
setApiKey("");
onChanged();
} catch (e) {
toast.error(`Save failed: ${(e as Error).message}`);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setBusy(false);
}
@@ -138,32 +139,34 @@ function DataSourceCard({
<Card>
<CardHeader className="flex flex-row items-center justify-between">
<CardTitle className="flex items-center gap-2 text-base">
<PlugZapIcon className="size-4" /> Data source status
<PlugZapIcon className="size-4" /> {t("Data source status")}
<StatusBadge status={status} loading={loading} />
</CardTitle>
<Button variant="ghost" size="sm" onClick={onChanged} disabled={loading}>
<RefreshCwIcon className={loading ? "size-4 animate-spin" : "size-4"} /> Refresh
<RefreshCwIcon className={loading ? "size-4 animate-spin" : "size-4"} /> {t("Refresh")}
</Button>
</CardHeader>
<CardContent className="space-y-3">
{!status?.exists ? (
<div className="flex items-center justify-between gap-4">
<p className="text-muted-foreground text-sm">
No ScopeSentry data source yet. Creating one adds a placeholder MCP (empty URL/key, disabled).
{t("No ScopeSentry data source yet. Creating one adds a placeholder MCP (empty URL/key, disabled).")}
</p>
<Button onClick={create} disabled={busy}>
Create data source
{t("Create data source")}
</Button>
</div>
) : (
<>
{!status.configured && (
<p className="text-amber-600 text-sm dark:text-amber-500">
The data source is created but not configured; fill in the MCP URL and API key, then enable it.
{t("The data source is created but not configured; fill in the MCP URL and API key, then enable it.")}
</p>
)}
{status.configured && !status.enabled && (
<p className="text-amber-600 text-sm dark:text-amber-500">The data source is configured but not enabled; it will be enabled automatically on save.</p>
<p className="text-amber-600 text-sm dark:text-amber-500">
{t("The data source is configured but not enabled; it will be enabled automatically on save.")}
</p>
)}
<div className="grid gap-3 md:grid-cols-2">
<div className="space-y-1.5">
@@ -171,7 +174,7 @@ function DataSourceCard({
<Input placeholder="http://<host>:8082/mcp" value={url} onChange={(e) => setUrl(e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>API Key (X-API-Key; leave empty to keep the current value)</Label>
<Label>{t("API Key (X-API-Key; leave empty to keep the current value)")}</Label>
<Input
type="password"
placeholder="ssk_..."
@@ -182,10 +185,12 @@ function DataSourceCard({
</div>
<div className="flex items-center gap-2">
<Button onClick={save} disabled={busy}>
Save & enable
{t("Save & enable")}
</Button>
{status.enabled && status.tools.length > 0 && (
<span className="text-muted-foreground text-xs">{status.tools.length} tools discovered</span>
<span className="text-muted-foreground text-xs">
{t("{count} tools discovered", { count: status.tools.length })}
</span>
)}
</div>
</>
@@ -196,19 +201,19 @@ function DataSourceCard({
}
function StatusBadge({ status, loading }: { status: SSStatus | null; loading: boolean }) {
if (loading || !status) return <Badge variant="secondary">Checking…</Badge>;
if (!status.exists) return <Badge variant="destructive">Not created</Badge>;
if (!status.configured) return <Badge variant="outline">Not configured</Badge>;
if (!status.enabled) return <Badge variant="outline">Not enabled</Badge>;
if (loading || !status) return <Badge variant="secondary">{t("Checking…")}</Badge>;
if (!status.exists) return <Badge variant="destructive">{t("Not created")}</Badge>;
if (!status.configured) return <Badge variant="outline">{t("Not configured")}</Badge>;
if (!status.enabled) return <Badge variant="outline">{t("Not enabled")}</Badge>;
if (status.reachable)
return (
<Badge className="bg-emerald-600 hover:bg-emerald-600">
<CheckCircle2Icon className="mr-1 size-3" /> Connected
<CheckCircle2Icon className="mr-1 size-3" /> {t("Connected")}
</Badge>
);
return (
<Badge variant="destructive">
<AlertCircleIcon className="mr-1 size-3" /> Unreachable
<AlertCircleIcon className="mr-1 size-3" /> {t("Unreachable")}
</Badge>
);
}
@@ -241,7 +246,9 @@ function SyncWorkbench() {
dimension === "project"
? api.ssProjects(page, 50, search).then((r) => setProjects(r.projects))
: api.ssTasks(page, 50, search).then(setTasks);
fn.catch((e) => toast.error(`Failed to load the list: ${e.message}`)).finally(() => setLoading(false));
fn.catch((e) => toast.error(t("Failed to load the list: {error}", { error: e.message }))).finally(() =>
setLoading(false),
);
}, [dimension, page, search]);
React.useEffect(() => {
@@ -266,8 +273,9 @@ function SyncWorkbench() {
const chosenTypes = ASSET_TYPES.filter((t) => assetTypes[t.key]).map((t) => t.key);
const runSync = async () => {
if (selected.size === 0) return toast.error(`Select at least one ${dimension === "project" ? "project" : "task"}`);
if (chosenTypes.length === 0) return toast.error("Select at least one asset type");
if (selected.size === 0)
return toast.error(dimension === "project" ? t("Select at least one project") : t("Select at least one task"));
if (chosenTypes.length === 0) return toast.error(t("Select at least one asset type"));
setSyncing(true);
setResult(null);
try {
@@ -279,9 +287,9 @@ function SyncWorkbench() {
});
setResult(r);
const total = Object.values(r.synced ?? {}).reduce((a, b) => a + b, 0);
toast.success(`Sync finished; ${total} assets ingested in total`);
toast.success(t("Sync finished; {count} assets ingested in total", { count: total }));
} catch (e) {
toast.error(`Sync failed: ${(e as Error).message}`);
toast.error(t("Sync failed: {error}", { error: (e as Error).message }));
} finally {
setSyncing(false);
}
@@ -292,7 +300,7 @@ function SyncWorkbench() {
return (
<TableRow>
<TableCell colSpan={4} className="py-8 text-center text-muted-foreground text-sm">
Loading…
{t("Loading…")}
</TableCell>
</TableRow>
);
@@ -301,7 +309,7 @@ function SyncWorkbench() {
return (
<TableRow>
<TableCell colSpan={4} className="py-8 text-center text-muted-foreground text-sm">
No data
{t("No data")}
</TableCell>
</TableRow>
);
@@ -337,7 +345,7 @@ function SyncWorkbench() {
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Pick data to sync</CardTitle>
<CardTitle className="text-base">{t("Pick data to sync")}</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Dimension switch */}
@@ -349,14 +357,14 @@ function SyncWorkbench() {
}}
>
<TabsList>
<TabsTrigger value="project">By project</TabsTrigger>
<TabsTrigger value="task">By task</TabsTrigger>
<TabsTrigger value="project">{t("By project")}</TabsTrigger>
<TabsTrigger value="task">{t("By task")}</TabsTrigger>
</TabsList>
</Tabs>
{/* Asset types + options */}
<div className="flex flex-wrap items-center gap-4">
<span className="font-medium text-sm">Assets to sync:</span>
<span className="font-medium text-sm">{t("Assets to sync:")}</span>
{ASSET_TYPES.map((t) => (
<label key={t.key} htmlFor={`at-${t.key}`} className="flex items-center gap-1.5 text-sm">
<Checkbox
@@ -370,7 +378,7 @@ function SyncWorkbench() {
{dimension === "project" && (
<label htmlFor="create-company" className="flex items-center gap-1.5 text-sm">
<Checkbox id="create-company" checked={createCompany} onCheckedChange={(c) => setCreateCompany(!!c)} />
Create a company per project and write its asset scope
{t("Create a company per project and write its asset scope")}
</label>
)}
</div>
@@ -381,7 +389,7 @@ function SyncWorkbench() {
<SearchIcon className="absolute top-1/2 left-2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
className="pl-8"
placeholder={dimension === "project" ? "Search project names" : "Search task names"}
placeholder={dimension === "project" ? t("Search project names") : t("Search task names")}
value={search}
onChange={(e) => setSearch(e.target.value)}
onKeyDown={(e) => {
@@ -396,9 +404,9 @@ function SyncWorkbench() {
<RefreshCwIcon className={loading ? "size-4 animate-spin" : "size-4"} />
</Button>
<div className="flex-1" />
<span className="text-muted-foreground text-xs">{selected.size} selected</span>
<span className="text-muted-foreground text-xs">{t("{count} selected", { count: selected.size })}</span>
<Button onClick={runSync} disabled={syncing || selected.size === 0}>
<DownloadIcon className={syncing ? "size-4 animate-pulse" : "size-4"} /> Sync selected
<DownloadIcon className={syncing ? "size-4 animate-pulse" : "size-4"} /> {t("Sync selected")}
</Button>
</div>
@@ -410,16 +418,16 @@ function SyncWorkbench() {
<TableHead className="w-10">
<Checkbox checked={rows.length > 0 && selected.size === rows.length} onCheckedChange={toggleAll} />
</TableHead>
<TableHead>{dimension === "project" ? "Project name" : "Task name"}</TableHead>
<TableHead>{dimension === "project" ? t("Project name") : t("Task name")}</TableHead>
{dimension === "project" ? (
<>
<TableHead>Tag</TableHead>
<TableHead className="text-right">Assets</TableHead>
<TableHead>{t("Tag")}</TableHead>
<TableHead className="text-right">{t("Assets")}</TableHead>
</>
) : (
<>
<TableHead>Status</TableHead>
<TableHead>Time</TableHead>
<TableHead>{t("Status")}</TableHead>
<TableHead>{t("Time")}</TableHead>
</>
)}
</TableRow>
@@ -431,16 +439,16 @@ function SyncWorkbench() {
{/* Pagination */}
<div className="flex items-center justify-end gap-2">
<Button variant="outline" size="sm" disabled={page <= 1 || loading} onClick={() => setPage((p) => p - 1)}>
Previous
{t("Previous")}
</Button>
<span className="text-muted-foreground text-xs">Page {page}</span>
<span className="text-muted-foreground text-xs">{t("Page {page}", { page })}</span>
<Button
variant="outline"
size="sm"
disabled={rows.length < 50 || loading}
onClick={() => setPage((p) => p + 1)}
>
Next
{t("Next")}
</Button>
</div>
@@ -453,7 +461,7 @@ function SyncWorkbench() {
function SyncResult({ result }: { result: Awaited<ReturnType<typeof api.ssSync>> }) {
const synced = result.synced ?? {};
const labels: Record<string, string> = { subdomain: "Subdomain", service: "Service", app: "App", ip: "IP" };
const labels: Record<string, string> = { subdomain: t("Subdomain"), service: t("Service"), app: t("App"), ip: "IP" };
return (
<div className="space-y-2 rounded-md border bg-muted/40 p-3 text-sm">
<div className="flex flex-wrap gap-3">
@@ -464,7 +472,9 @@ function SyncResult({ result }: { result: Awaited<ReturnType<typeof api.ssSync>>
))}
</div>
{result.companies && result.companies.length > 0 && (
<p className="text-muted-foreground">Companies created/updated: {result.companies.join(", ")}</p>
<p className="text-muted-foreground">
{t("Companies created/updated: {names}", { names: result.companies.join(", ") })}
</p>
)}
{result.warnings && result.warnings.length > 0 && (
<ul className="list-inside list-disc text-amber-600 dark:text-amber-500">
@@ -478,7 +488,7 @@ function SyncResult({ result }: { result: Awaited<ReturnType<typeof api.ssSync>>
{result.errors.slice(0, 20).map((em) => (
<li key={em}>{em}</li>
))}
{result.errors.length > 20 && <li>… {result.errors.length} errors in total</li>}
{result.errors.length > 20 && <li>{t("… {count} errors in total", { count: result.errors.length })}</li>}
</ul>
)}
</div>
@@ -44,6 +44,7 @@ import { taskAssetSourceLabel } from "@/lib/task-assets";
import type { Asset, NewAssetType } from "@/lib/types";
import { cn } from "@/lib/utils";
import { setVisibleInterval } from "@/lib/polling";
import { t } from "@/i18n";
const PAGE_SIZES = [25, 50, 100, 200];
@@ -58,12 +59,12 @@ const METHOD_COLOR: Record<string, string> = {
};
const TABS: { key: NewAssetType; label: string; icon: LucideIcon }[] = [
{ key: "root_domain", label: "Root domain", icon: GlobeIcon },
{ key: "root_domain", label: t("Root domain"), icon: GlobeIcon },
{ key: "ip", label: "IP", icon: NetworkIcon },
{ key: "subdomain", label: "Subdomain", icon: GlobeIcon },
{ key: "app", label: "App", icon: SmartphoneIcon },
{ key: "service", label: "Service", icon: LayoutTemplateIcon },
{ key: "endpoint", label: "Endpoint", icon: LinkIcon },
{ key: "subdomain", label: t("Subdomain"), icon: GlobeIcon },
{ key: "app", label: t("App"), icon: SmartphoneIcon },
{ key: "service", label: t("Service"), icon: LayoutTemplateIcon },
{ key: "endpoint", label: t("Endpoint"), icon: LinkIcon },
];
function firstText(values: Array<string | undefined>, fallback: string): string {
@@ -134,7 +135,10 @@ function Chips({ items, mono }: { items: string[]; mono?: boolean }) {
function SourceCell({ asset }: { asset: Asset }) {
const source = firstText([asset.task_source], "legacy");
const summary = firstText([asset.task_source_summary], "Migrated from a historical task's asset association; no more detailed source information");
const summary = firstText(
[asset.task_source_summary],
t("Migrated from a historical task's asset association; no more detailed source information"),
);
return (
<Tooltip>
<TooltipTrigger asChild>
@@ -147,7 +151,7 @@ function SourceCell({ asset }: { asset: Asset }) {
<span className="font-medium">{taskAssetSourceLabel(source)}</span>
<span className="[overflow-wrap:anywhere]">{summary}</span>
{asset.task_source_node_id ? (
<span className="font-mono opacity-80">Source node #{asset.task_source_node_id}</span>
<span className="font-mono opacity-80">{t("Source node #{id}", { id: asset.task_source_node_id })}</span>
) : null}
</div>
</TooltipContent>
@@ -193,7 +197,7 @@ function AssetCard({
tableRows = (
<TableRow>
<TableCell colSpan={cols.length} className="py-10 text-center text-muted-foreground text-sm">
No test assets in this category yet
{t("No test assets in this category yet")}
</TableCell>
</TableRow>
);
@@ -228,7 +232,7 @@ function AssetCard({
<SelectGroup>
{PAGE_SIZES.map((value) => (
<SelectItem key={value} value={String(value)}>
{value} / page
{t("{count} / page", { count: value })}
</SelectItem>
))}
</SelectGroup>
@@ -244,7 +248,7 @@ function AssetCard({
size="icon-sm"
disabled={page <= 0}
onClick={() => onPage(Math.max(0, page - 1))}
aria-label="Previous page"
aria-label={t("Previous page")}
>
<ChevronLeftIcon />
</Button>
@@ -256,7 +260,7 @@ function AssetCard({
size="icon-sm"
disabled={page + 1 >= pageCount}
onClick={() => onPage(Math.min(pageCount - 1, page + 1))}
aria-label="Next page"
aria-label={t("Next page")}
>
<ChevronRightIcon />
</Button>
@@ -294,11 +298,16 @@ function AddTaskAssetsSheet({
try {
const result = await api.registerTaskAssetScopes(taskId, parsedScope.rules);
const assetSummary = result.assets_linked + result.assets_existing;
toast.success(`Registered ${result.requested} scopes, linked ${assetSummary} domain/IP assets`);
toast.success(
t("Registered {scopes} scopes, linked {assets} domain/IP assets", {
scopes: result.requested,
assets: assetSummary,
}),
);
onAttached();
onOpenChange(false);
} catch (reason) {
toast.error(`Failed to add: ${String((reason as Error)?.message ?? reason)}`);
toast.error(t("Failed to add: {error}", { error: String((reason as Error)?.message ?? reason) }));
} finally {
setSaving(false);
}
@@ -308,9 +317,11 @@ function AddTaskAssetsSheet({
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="w-full sm:max-w-xl">
<SheetHeader>
<SheetTitle>Add test assets</SheetTitle>
<SheetTitle>{t("Add test assets")}</SheetTitle>
<SheetDescription>
Enter the test scope directly. Domains and IPs create or reuse global assets; CIDRs, ICP records, and keywords act as agent scope context.
{t(
"Enter the test scope directly. Domains and IPs create or reuse global assets; CIDRs, ICP records, and keywords act as agent scope context.",
)}
</SheetDescription>
</SheetHeader>
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-4">
@@ -319,20 +330,24 @@ function AddTaskAssetsSheet({
value={scopeText}
onValueChange={setScopeText}
parsed={parsedScope}
label="Test assets and scope"
description="One entry per line; domains, IPs, CIDRs, ICP records, and keywords are recognized automatically."
label={t("Test assets and scope")}
description={t(
"One entry per line; domains, IPs, CIDRs, ICP records, and keywords are recognized automatically.",
)}
/>
</div>
<SheetFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
Cancel
{t("Cancel")}
</Button>
<Button
onClick={() => void attach()}
disabled={saving || parsedScope.rules.length === 0 || parsedScope.errors.length > 0}
>
{saving ? <Spinner data-icon="inline-start" /> : <PlusIcon data-icon="inline-start" />}
Register {parsedScope.rules.length > 0 ? parsedScope.rules.length : ""} entries
{parsedScope.rules.length > 0
? t("Register {count} entries", { count: parsedScope.rules.length })
: t("Register entries")}
</Button>
</SheetFooter>
</SheetContent>
@@ -405,7 +420,7 @@ export function AssetsTab({ taskId }: { taskId: string }) {
setRows([]);
setTotal(0);
} else {
toast.error(`Failed to load task assets: ${message}`);
toast.error(t("Failed to load task assets: {error}", { error: message }));
}
} finally {
if (active && assetsRequestRef.current === request) {
@@ -439,11 +454,11 @@ export function AssetsTab({ taskId }: { taskId: string }) {
setRemoving(true);
try {
await api.detachTaskAsset(taskId, removeTarget.id);
toast.success(`Removed ${assetLabel(removeTarget)} from the current task`);
toast.success(t("Removed {label} from the current task", { label: assetLabel(removeTarget) }));
setRemoveTarget(null);
refresh();
} catch (reason) {
toast.error(`Failed to remove: ${String((reason as Error)?.message ?? reason)}`);
toast.error(t("Failed to remove: {error}", { error: String((reason as Error)?.message ?? reason) }));
} finally {
setRemoving(false);
}
@@ -454,8 +469,8 @@ export function AssetsTab({ taskId }: { taskId: string }) {
variant="ghost"
size="icon-sm"
onClick={() => setRemoveTarget(asset)}
aria-label={`Remove asset ${assetLabel(asset)} from the task`}
title="Remove from task"
aria-label={t("Remove asset {label} from the task", { label: assetLabel(asset) })}
title={t("Remove from task")}
>
<Trash2Icon />
</Button>
@@ -478,12 +493,14 @@ export function AssetsTab({ taskId }: { taskId: string }) {
<div className="flex min-h-0 flex-1 flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0">
<h2 className="font-medium text-sm">Test assets</h2>
<p className="text-muted-foreground text-xs">This task is linked to {totalAll} assets in total</p>
<h2 className="font-medium text-sm">{t("Test assets")}</h2>
<p className="text-muted-foreground text-xs">
{t("This task is linked to {count} assets in total", { count: totalAll })}
</p>
</div>
<Button size="sm" onClick={() => setAddOpen(true)}>
<PlusIcon data-icon="inline-start" />
Add test assets
{t("Add test assets")}
</Button>
</div>
@@ -507,7 +524,7 @@ export function AssetsTab({ taskId }: { taskId: string }) {
{searchBox}
<TabsContent value="root_domain" className="mt-0 flex min-h-0 flex-1 flex-col">
<AssetCard cols={["Domain", "ICP record", "Source", "Actions"]} {...commonCardProps}>
<AssetCard cols={[t("Domain"), t("ICP record"), t("Source"), t("Actions")]} {...commonCardProps}>
{rows.map((asset) => (
<TableRow key={asset.id}>
<TableCell className="font-medium font-mono text-xs">{asset.domain}</TableCell>
@@ -522,7 +539,10 @@ export function AssetsTab({ taskId }: { taskId: string }) {
</TabsContent>
<TabsContent value="ip" className="mt-0 flex min-h-0 flex-1 flex-col">
<AssetCard cols={["IP", "C segment", "Bound domains", "Open ports", "Source", "Actions"]} {...commonCardProps}>
<AssetCard
cols={["IP", t("C segment"), t("Bound domains"), t("Open ports"), t("Source"), t("Actions")]}
{...commonCardProps}
>
{rows.map((asset) => (
<TableRow key={asset.id}>
<TableCell className="font-medium font-mono text-xs">{asset.ip}</TableCell>
@@ -548,7 +568,10 @@ export function AssetsTab({ taskId }: { taskId: string }) {
</TabsContent>
<TabsContent value="subdomain" className="mt-0 flex min-h-0 flex-1 flex-col">
<AssetCard cols={["Domain", "Root domain", "Record type", "Record value", "Source", "Actions"]} {...commonCardProps}>
<AssetCard
cols={[t("Domain"), t("Root domain"), t("Record type"), t("Record value"), t("Source"), t("Actions")]}
{...commonCardProps}
>
{rows.map((asset) => (
<TableRow key={asset.id}>
<TableCell className="font-medium font-mono text-xs">{asset.domain}</TableCell>
@@ -567,7 +590,10 @@ export function AssetsTab({ taskId }: { taskId: string }) {
</TabsContent>
<TabsContent value="app" className="mt-0 flex min-h-0 flex-1 flex-col">
<AssetCard cols={["App", "Address", "Category", "Title", "Fingerprints", "Source", "Actions"]} {...commonCardProps}>
<AssetCard
cols={[t("App"), t("Address"), t("Category"), t("Title"), t("Fingerprints"), t("Source"), t("Actions")]}
{...commonCardProps}
>
{rows.map((asset) => (
<TableRow key={asset.id}>
<TableCell className="max-w-48 truncate font-medium text-xs">{asset.app_name || "—"}</TableCell>
@@ -590,7 +616,16 @@ export function AssetsTab({ taskId }: { taskId: string }) {
<TabsContent value="service" className="mt-0 flex min-h-0 flex-1 flex-col">
<AssetCard
cols={["Address / service", "Status code", "Title", "Response size", "Fingerprints", "Auth", "Source", "Actions"]}
cols={[
t("Address / service"),
t("Status code"),
t("Title"),
t("Response size"),
t("Fingerprints"),
t("Auth"),
t("Source"),
t("Actions"),
]}
{...commonCardProps}
>
{rows.map((asset) => {
@@ -631,7 +666,7 @@ export function AssetsTab({ taskId }: { taskId: string }) {
className="inline-flex items-center gap-1 text-[11px]"
>
<KeyRoundIcon className="size-3 text-muted-foreground" />
<span className="font-mono">{item.type || item.username || "Auth"}</span>
<span className="font-mono">{item.type || item.username || t("Auth")}</span>
</span>
);
})
@@ -648,7 +683,7 @@ export function AssetsTab({ taskId }: { taskId: string }) {
</TabsContent>
<TabsContent value="endpoint" className="mt-0 flex min-h-0 flex-1 flex-col">
<AssetCard cols={["Method", "Full URL", "Params", "Source", "Actions"]} {...commonCardProps}>
<AssetCard cols={[t("Method"), t("Full URL"), t("Params"), t("Source"), t("Actions")]} {...commonCardProps}>
{rows.map((asset) => (
<TableRow key={asset.id}>
<TableCell className="w-16">
@@ -681,14 +716,16 @@ export function AssetsTab({ taskId }: { taskId: string }) {
<AlertDialog open={Boolean(removeTarget)} onOpenChange={(open) => !open && !removing && setRemoveTarget(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Remove from this task?</AlertDialogTitle>
<AlertDialogTitle>{t("Remove from this task?")}</AlertDialogTitle>
<AlertDialogDescription className="[overflow-wrap:anywhere]">
{removeTarget ? `Remove "${assetLabel(removeTarget)}" from this task's test assets.` : ""}
Global assets, linked traffic, and historical blackboard anchors are kept.
{removeTarget
? `${t('Remove "{label}" from this task\'s test assets.', { label: assetLabel(removeTarget) })} `
: ""}
{t("Global assets, linked traffic, and historical blackboard anchors are kept.")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={removing}>Cancel</AlertDialogCancel>
<AlertDialogCancel disabled={removing}>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
disabled={removing}
@@ -698,7 +735,7 @@ export function AssetsTab({ taskId }: { taskId: string }) {
}}
>
{removing ? <Spinner data-icon="inline-start" /> : <Trash2Icon data-icon="inline-start" />}
{removing ? "Removing" : "Remove"}
{removing ? t("Removing") : t("Remove")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -34,6 +34,7 @@ import { taskAssetTypeLabel } from "@/lib/task-assets";
import type { Edge, ExploreKind, FindingAsset, NewAssetType, TaskNode } from "@/lib/types";
import { cn } from "@/lib/utils";
import { setVisibleInterval } from "@/lib/polling";
import { intlLocale, t } from "@/i18n";
const PAGE_SIZES = [20, 50, 100];
const POLL_MS = 8000;
@@ -44,49 +45,49 @@ type KindMeta = { label: string; icon: LucideIcon; dot: string; chip: string };
// the broadcast a stream view (timeline rows); the two differ in information density and color needs, so they evolve separately.
const KIND_META: Record<string, KindMeta> = {
begin: {
label: "Start",
label: t("Start"),
icon: FlagIcon,
dot: "bg-slate-500",
chip: "bg-slate-500/15 text-slate-600 dark:text-slate-300",
},
task: {
label: "Root task",
label: t("Root task"),
icon: FlagIcon,
dot: "bg-slate-500",
chip: "bg-slate-500/15 text-slate-600 dark:text-slate-300",
},
goal: {
label: "Goal",
label: t("Goal"),
icon: TargetIcon,
dot: "bg-emerald-500",
chip: "bg-emerald-500/15 text-emerald-600 dark:text-emerald-400",
},
intent: {
label: "Intent",
label: t("Intent"),
icon: CompassIcon,
dot: "bg-blue-500",
chip: "bg-blue-500/15 text-blue-600 dark:text-blue-400",
},
fact: {
label: "Fact",
label: t("Fact"),
icon: FlaskConicalIcon,
dot: "bg-amber-500",
chip: "bg-amber-500/15 text-amber-600 dark:text-amber-400",
},
finding: {
label: "Vulnerability",
label: t("Vulnerability"),
icon: BugIcon,
dot: "bg-rose-500",
chip: "bg-rose-500/15 text-rose-600 dark:text-rose-400",
},
hint: {
label: "Hint",
label: t("Hint"),
icon: LightbulbIcon,
dot: "bg-violet-500",
chip: "bg-violet-500/15 text-violet-600 dark:text-violet-400",
},
digest: {
label: "Digest",
label: t("Digest"),
icon: LayersIcon,
dot: "bg-teal-500",
chip: "bg-teal-500/15 text-teal-600 dark:text-teal-400",
@@ -97,32 +98,32 @@ const KIND_META: Record<string, KindMeta> = {
const FILTER_KINDS: ExploreKind[] = ["goal", "intent", "fact", "finding", "hint", "digest"];
const REL_LABEL: Record<string, string> = {
spawns: "Spawns",
derived_from: "Intent chain",
yields: "Yields",
proves: "Proves",
covers: "Compresses",
spawns: t("Spawns"),
derived_from: t("Intent chain"),
yields: t("Yields"),
proves: t("Proves"),
covers: t("Compresses"),
};
// State semantics for goal / intent come from the global status table (StatusBadge); the other kinds' states only
// appear in the graph and broadcast, so they are defined here.
const STATE_META: Record<string, Record<string, { label: string; tone: Tone }>> = {
fact: {
origin: { label: "Start", tone: "slate" },
confirmed: { label: "Confirmed", tone: "green" },
dismissed: { label: "Dismissed", tone: "slate" },
origin: { label: t("Start"), tone: "slate" },
confirmed: { label: t("Confirmed"), tone: "green" },
dismissed: { label: t("Dismissed"), tone: "slate" },
},
finding: {
confirmed: { label: "Confirmed", tone: "red" },
dismissed: { label: "Excluded", tone: "slate" },
confirmed: { label: t("Confirmed"), tone: "red" },
dismissed: { label: t("Excluded"), tone: "slate" },
},
hint: {
active: { label: "Pending adoption", tone: "violet" },
consumed: { label: "Adopted", tone: "slate" },
active: { label: t("Pending adoption"), tone: "violet" },
consumed: { label: t("Adopted"), tone: "slate" },
},
digest: {
active: { label: "Active", tone: "green" },
superseded: { label: "Superseded", tone: "slate" },
active: { label: t("Active"), tone: "green" },
superseded: { label: t("Superseded"), tone: "slate" },
},
};
@@ -160,7 +161,7 @@ function summaryOf(n: TaskNode): string {
}
function prettyPayload(raw?: string): string {
if (!raw?.trim()) return "(no payload)";
if (!raw?.trim()) return t("(no payload)");
try {
return JSON.stringify(JSON.parse(raw), null, 2);
} catch {
@@ -171,14 +172,14 @@ function prettyPayload(raw?: string): string {
function relTime(ts: number, now: number): string {
if (!now || !ts) return "";
const sec = Math.max(0, (now - ts) / 1000);
if (sec < 60) return "just now";
if (sec < 3600) return `${Math.floor(sec / 60)} minutes ago`;
if (sec < 86400) return `${Math.floor(sec / 3600)} hours ago`;
return `${Math.floor(sec / 86400)} days ago`;
if (sec < 60) return t("just now");
if (sec < 3600) return t("{count} minutes ago", { count: Math.floor(sec / 60) });
if (sec < 86400) return t("{count} hours ago", { count: Math.floor(sec / 3600) });
return t("{count} days ago", { count: Math.floor(sec / 86400) });
}
const dayFmt = new Intl.DateTimeFormat("zh-CN", { month: "long", day: "numeric", weekday: "short" });
const clockFmt = new Intl.DateTimeFormat("zh-CN", {
const dayFmt = new Intl.DateTimeFormat(intlLocale, { month: "long", day: "numeric", weekday: "short" });
const clockFmt = new Intl.DateTimeFormat(intlLocale, {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
@@ -216,7 +217,9 @@ function AssetList({ assets, dense = false }: { assets: FindingAsset[]; dense?:
if (assets.length === 0) return null;
return (
<div>
<div className="mb-1.5 text-xs font-medium text-muted-foreground">Assets involved · {assets.length}</div>
<div className="mb-1.5 text-xs font-medium text-muted-foreground">
{t("Assets involved · {count}", { count: assets.length })}
</div>
<ul className="flex flex-wrap gap-1.5">
{assets.map((a) => {
// At runtime a.type may be a kind not covered by the label table; fall back to the raw string. The type cast keeps the fallback from being flagged as redundant.
@@ -259,11 +262,11 @@ function RelatedNodeCard({ node, assets }: { node: TaskNode; assets: FindingAsse
)}
</div>
<div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-muted-foreground">
<span>Type {meta.label}</span>
<span>Source {node.origin || "system"}</span>
<span>{Number.isNaN(ts) ? node.ts : new Date(ts).toLocaleString("zh-CN")}</span>
<span>{t("Type {type}", { type: meta.label })}</span>
<span>{t("Source {source}", { source: node.origin || "system" })}</span>
<span>{Number.isNaN(ts) ? node.ts : new Date(ts).toLocaleString(intlLocale)}</span>
</div>
<p className="line-clamp-4 text-xs break-words">{summary || "(no summary)"}</p>
<p className="line-clamp-4 text-xs break-words">{summary || t("(no summary)")}</p>
<AssetList assets={assets} dense />
<pre className="max-h-40 overflow-auto rounded border bg-muted/40 p-2 font-mono text-[11px] whitespace-pre-wrap">
{prettyPayload(node.payload)}
@@ -304,7 +307,7 @@ function RelatedList({
className="flex min-w-0 cursor-help items-center gap-2 text-left hover:underline"
>
<KindChip kind={viewKind(node)} />
<span className="truncate">{summaryOf(node) || `Node #${node.id}`}</span>
<span className="truncate">{summaryOf(node) || t("Node #{id}", { id: node.id })}</span>
</button>
</HoverCardTrigger>
<HoverCardContent align="start" className="w-96">
@@ -312,7 +315,7 @@ function RelatedList({
</HoverCardContent>
</HoverCard>
) : (
<span className="text-muted-foreground">Node #{row.id}</span>
<span className="text-muted-foreground">{t("Node #{id}", { id: row.id })}</span>
)}
</li>
);
@@ -387,12 +390,12 @@ function BroadcastRow({
)}
{fresh && (
<span className="rounded bg-primary px-1.5 py-0.5 text-[10px] font-semibold text-primary-foreground">
New
{t("New")}
</span>
)}
<span className="ml-auto shrink-0 text-xs text-muted-foreground">{node.origin || "system"}</span>
</div>
<p className={cn("mt-1 text-sm", !open && "line-clamp-2")}>{summary || `Node #${node.id}`}</p>
<p className={cn("mt-1 text-sm", !open && "line-clamp-2")}>{summary || t("Node #{id}", { id: node.id })}</p>
</div>
</button>
@@ -400,23 +403,23 @@ function BroadcastRow({
<div className="mt-2 ml-5 flex flex-col gap-3 rounded-md border bg-muted/30 p-3">
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
<span>
Node <code className="font-mono">#{node.id}</code>
{t("Node")} <code className="font-mono">#{node.id}</code>
</span>
<span>Type {meta.label}</span>
<span>Source {node.origin || "system"}</span>
<span>{Number.isNaN(ts) ? node.ts : new Date(ts).toLocaleString("zh-CN")}</span>
<span>{t("Type {type}", { type: meta.label })}</span>
<span>{t("Source {source}", { source: node.origin || "system" })}</span>
<span>{Number.isNaN(ts) ? node.ts : new Date(ts).toLocaleString(intlLocale)}</span>
</div>
{node.state === "deleted" && node.delete_reason && (
<div className="rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs">
<span className="font-medium text-destructive">Deletion reason</span>
<span className="font-medium text-destructive">{t("Deletion reason")}</span>
<span className="ml-2 break-words text-muted-foreground">{node.delete_reason}</span>
</div>
)}
<AssetList assets={assets[node.id] ?? []} />
{(upstream.length > 0 || downstream.length > 0) && (
<div className="flex flex-col gap-3 sm:flex-row">
<RelatedList title="Upstream · comes from these" rows={upstream} refs={refs} assets={assets} />
<RelatedList title="Downstream · produced by this" rows={downstream} refs={refs} assets={assets} />
<RelatedList title={t("Upstream · comes from these")} rows={upstream} refs={refs} assets={assets} />
<RelatedList title={t("Downstream · produced by this")} rows={downstream} refs={refs} assets={assets} />
</div>
)}
<div>
@@ -559,7 +562,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
const groups: Array<{ day: string; rows: TaskNode[] }> = [];
for (const node of items) {
const ts = Date.parse(node.ts);
const day = Number.isNaN(ts) ? "Unknown date" : dayFmt.format(ts);
const day = Number.isNaN(ts) ? t("Unknown date") : dayFmt.format(ts);
const last = groups[groups.length - 1];
if (last && last.day === day) last.rows.push(node);
else groups.push({ day, rows: [node] });
@@ -574,9 +577,9 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
<Input
value={queryInput}
onChange={(e) => setQueryInput(e.target.value)}
placeholder="Search content / source / node id"
placeholder={t("Search content / source / node id")}
className="h-8 pl-8"
aria-label="Search broadcasts"
aria-label={t("Search broadcasts")}
/>
</div>
<div className="flex flex-wrap items-center gap-1">
@@ -608,7 +611,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
setPage(1);
}}
>
Clear
{t("Clear")}
</Button>
)}
</div>
@@ -621,20 +624,24 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
setOrder((o) => (o === "desc" ? "asc" : "desc"));
setPage(1);
}}
aria-label={order === "desc" ? "Currently newest first; click to switch to oldest first" : "Currently oldest first; click to switch to newest first"}
aria-label={
order === "desc"
? t("Currently newest first; click to switch to oldest first")
: t("Currently oldest first; click to switch to newest first")
}
>
{order === "desc" ? <ArrowDownIcon /> : <ArrowUpIcon />}
{order === "desc" ? "Newest first" : "Oldest first"}
{order === "desc" ? t("Newest first") : t("Oldest first")}
</Button>
<Button
variant={live ? "outline" : "secondary"}
size="sm"
className="h-8"
onClick={() => setLive((v) => !v)}
aria-label={live ? "Pause auto-refresh" : "Resume auto-refresh"}
aria-label={live ? t("Pause auto-refresh") : t("Resume auto-refresh")}
>
{live ? <PauseIcon /> : <PlayIcon />}
{live ? "Auto-refresh" : "Paused"}
{live ? t("Auto-refresh") : t("Paused")}
</Button>
</div>
</div>
@@ -647,7 +654,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
className="flex w-full items-center justify-center gap-1.5 border-b bg-primary/10 py-1.5 text-xs font-medium text-primary hover:bg-primary/15"
>
<ArrowUpToLineIcon className="size-3.5" />
{pending > 99 ? "99+" : pending} new broadcasts · Back to latest
{t("{count} new broadcasts · Back to latest", { count: pending > 99 ? "99+" : pending })}
</button>
)}
@@ -660,7 +667,9 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
</div>
) : items.length === 0 ? (
<p className="py-10 text-center text-sm text-muted-foreground">
{query || kinds.length > 0 ? "No broadcasts match the filters." : "This task has not produced any exploration nodes yet."}
{query || kinds.length > 0
? t("No broadcasts match the filters.")
: t("This task has not produced any exploration nodes yet.")}
</p>
) : (
groups.map((group) => (
@@ -697,7 +706,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
<SelectGroup>
{PAGE_SIZES.map((n) => (
<SelectItem key={n} value={String(n)}>
{n} / page
{t("{count} / page", { count: n })}
</SelectItem>
))}
</SelectGroup>
@@ -712,7 +721,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
size="icon-sm"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
aria-label="Previous page"
aria-label={t("Previous page")}
>
<ChevronLeftIcon />
</Button>
@@ -724,7 +733,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
size="icon-sm"
disabled={page >= pageCount}
onClick={() => setPage((p) => Math.min(pageCount, p + 1))}
aria-label="Next page"
aria-label={t("Next page")}
>
<ChevronRightIcon />
</Button>
@@ -24,7 +24,9 @@ import {
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import { statusMeta } from "@/lib/status";
import type { CoverageAssetRef, CoverageAssetRefs, CoverageGraphEdge, CoverageGraphNode } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -37,13 +39,13 @@ type Kind = CoverageGraphNode["kind"];
type KindMeta = { label: string; icon: LucideIcon; iconBg: string; hex: string; size: number };
const kindMeta: Record<Kind, KindMeta> = {
company: { label: "Company", icon: Building2, iconBg: "bg-slate-500", hex: "#64748b", size: 46 },
root_domain: { label: "Root domain", icon: Globe, iconBg: "bg-indigo-500", hex: "#6366f1", size: 38 },
subdomain: { label: "Subdomain", icon: Waypoints, iconBg: "bg-blue-500", hex: "#3b82f6", size: 30 },
company: { label: t("Company"), icon: Building2, iconBg: "bg-slate-500", hex: "#64748b", size: 46 },
root_domain: { label: t("Root domain"), icon: Globe, iconBg: "bg-indigo-500", hex: "#6366f1", size: 38 },
subdomain: { label: t("Subdomain"), icon: Waypoints, iconBg: "bg-blue-500", hex: "#3b82f6", size: 30 },
ip: { label: "IP", icon: Server, iconBg: "bg-cyan-600", hex: "#0891b2", size: 28 },
service: { label: "Service", icon: Radio, iconBg: "bg-amber-500", hex: "#f59e0b", size: 26 },
app: { label: "App", icon: AppWindow, iconBg: "bg-fuchsia-500", hex: "#d946ef", size: 26 },
endpoint: { label: "Endpoint", icon: Link2, iconBg: "bg-rose-500", hex: "#f43f5e", size: 20 },
service: { label: t("Service"), icon: Radio, iconBg: "bg-amber-500", hex: "#f59e0b", size: 26 },
app: { label: t("App"), icon: AppWindow, iconBg: "bg-fuchsia-500", hex: "#d946ef", size: 26 },
endpoint: { label: t("Endpoint"), icon: Link2, iconBg: "bg-rose-500", hex: "#f43f5e", size: 20 },
};
// G6 node icons use the platform's lucide icons: render lucide SVG paths (v1.22) as white-stroked
@@ -220,7 +222,7 @@ function toG6Nodes(renderNodes: RenderNode[]): G6NodeDatum[] {
fold: true,
tested: false,
inScope: false,
lbl: `${rn.hidden.length} more ${kindMeta[rn.kind].label}`,
lbl: t("{count} more {kind}", { count: rn.hidden.length, kind: kindMeta[rn.kind].label }),
size: 24,
};
}
@@ -280,11 +282,15 @@ function RefList({ title, items }: { title: string; items: CoverageAssetRef[] })
className="flex flex-wrap items-start gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-xs"
>
<span className="shrink-0 font-mono text-muted-foreground">#{r.id}</span>
{r.state && <span className="shrink-0 text-muted-foreground">{r.state}</span>}
{r.state && (
<span className="shrink-0 text-muted-foreground">
{statusMeta(r.kind === "intent" ? "intent" : "node", r.state).label}
</span>
)}
<span className="min-w-32 flex-1 break-words text-foreground">{r.summary || "—"}</span>
{r.inherited && r.source_task_id && (
<Badge variant="outline" className="shrink-0">
Source #{r.source_task_id} · read-only
{t("Source #{id} · read-only", { id: r.source_task_id })}
</Badge>
)}
</div>
@@ -345,42 +351,42 @@ function AssetSheet({
<ScrollArea className="min-h-0 flex-1">
<div className="flex w-full min-w-0 flex-col gap-4 p-4">
<section>
<h4 className="text-muted-foreground mb-1 text-xs font-medium">Properties</h4>
<DetailRow label="Type">{meta.label}</DetailRow>
<DetailRow label="Test status">
<h4 className="text-muted-foreground mb-1 text-xs font-medium">{t("Properties")}</h4>
<DetailRow label={t("Type")}>{meta.label}</DetailRow>
<DetailRow label={t("Test status")}>
{node.in_scope ? (
node.tested ? (
<span className="text-emerald-600 dark:text-emerald-400">Tested</span>
<span className="text-emerald-600 dark:text-emerald-400">{t("Tested")}</span>
) : (
<span className="text-neutral-500">Untested</span>
<span className="text-neutral-500">{t("Untested")}</span>
)
) : (
<span className="text-neutral-400">Out of scope (connecting node)</span>
<span className="text-neutral-400">{t("Out of scope (connecting node)")}</span>
)}
</DetailRow>
<DetailRow label="Domain">{node.domain}</DetailRow>
<DetailRow label="Root domain">{node.root_domain}</DetailRow>
<DetailRow label={t("Domain")}>{node.domain}</DetailRow>
<DetailRow label={t("Root domain")}>{node.root_domain}</DetailRow>
<DetailRow label="IP">{node.ip}</DetailRow>
<DetailRow label="Port">{node.port ? node.port : undefined}</DetailRow>
<DetailRow label={t("Port")}>{node.port ? node.port : undefined}</DetailRow>
<DetailRow label="URL">
{node.url ? <span className="font-mono text-xs break-all">{node.url}</span> : undefined}
</DetailRow>
<DetailRow label="Title">{node.page_title}</DetailRow>
<DetailRow label="Status code">{node.status_code ? node.status_code : undefined}</DetailRow>
<DetailRow label="App">{node.app_name}</DetailRow>
<DetailRow label="Asset ID">
<DetailRow label={t("Title")}>{node.page_title}</DetailRow>
<DetailRow label={t("Status code")}>{node.status_code ? node.status_code : undefined}</DetailRow>
<DetailRow label={t("App")}>{node.app_name}</DetailRow>
<DetailRow label={t("Asset ID")}>
{node.asset_id ? <span className="font-mono text-xs">{node.asset_id}</span> : undefined}
</DetailRow>
</section>
{refs && (refs.intents.length > 0 || refs.facts.length > 0 || refs.findings.length > 0) && (
<section className="flex flex-col gap-3 border-t pt-3">
<RefList title="Related intents" items={refs.intents} />
<RefList title="Related facts" items={refs.facts} />
<RefList title="Related findings" items={refs.findings} />
<RefList title={t("Related intents")} items={refs.intents} />
<RefList title={t("Related facts")} items={refs.facts} />
<RefList title={t("Related findings")} items={refs.findings} />
</section>
)}
<section className="border-t pt-3">
<h4 className="text-muted-foreground mb-1.5 text-xs font-medium">Raw data</h4>
<h4 className="text-muted-foreground mb-1.5 text-xs font-medium">{t("Raw data")}</h4>
<pre className="bg-muted/50 text-foreground max-w-full overflow-hidden rounded-md border p-3 font-mono text-xs leading-relaxed break-all whitespace-pre-wrap">
{raw}
</pre>
@@ -414,9 +420,11 @@ function FoldSheet({
<>
<SheetHeader className="border-b p-4">
<SheetTitle className="text-base">
Hidden {meta.label} ({fold.hidden.length})
{t("Hidden {kind} ({count})", { kind: meta.label, count: fold.hidden.length })}
</SheetTitle>
<p className="text-muted-foreground text-xs">Tested items are shown first. Click "Show more" to pull the next batch into the graph.</p>
<p className="text-muted-foreground text-xs">
{t('Tested items are shown first. Click "Show more" to pull the next batch into the graph.')}
</p>
</SheetHeader>
<ScrollArea className="min-h-0 flex-1">
<div className="flex flex-col gap-1 p-3">
@@ -445,7 +453,7 @@ function FoldSheet({
</ScrollArea>
<div className="border-t p-3">
<Button className="w-full" variant="outline" onClick={() => onShowMore(fold.groupId)}>
Show more (+{FOLD_STEP})
{t("Show more (+{count})", { count: FOLD_STEP })}
</Button>
</div>
</>
@@ -644,19 +652,21 @@ function GraphInner({ taskId, coverageEnabled = true }: { taskId: string; covera
<div className="flex items-center justify-between gap-3">
{total > 0 ? (
<span className="text-muted-foreground">
In scope <span className="text-foreground font-semibold tabular-nums">{inScope}</span>
{t("In scope")} <span className="text-foreground font-semibold tabular-nums">{inScope}</span>
{coverageEnabled && (
<>
{" "}
· Tested{" "}
· {t("Tested")}{" "}
<span className="font-semibold tabular-nums text-emerald-600 dark:text-emerald-400">{tested}</span>
</>
)}
</span>
) : (
<span className="text-muted-foreground">{loading ? "Loading…" : "No in-scope assets yet (anchor the task scope first)"}</span>
<span className="text-muted-foreground">
{loading ? t("Loading…") : t("No in-scope assets yet (anchor the task scope first)")}
</span>
)}
<Button variant="ghost" size="icon" className="size-6" onClick={fetchGraph} title="Refresh">
<Button variant="ghost" size="icon" className="size-6" onClick={fetchGraph} title={t("Refresh")}>
<RefreshCw className={cn("size-3.5", loading && "animate-spin")} />
</Button>
</div>
@@ -678,19 +688,20 @@ function GraphInner({ taskId, coverageEnabled = true }: { taskId: string; covera
{coverageEnabled && (
<>
<span className="inline-flex items-center gap-1.5">
<span className="size-3 rounded-full bg-emerald-500" /> Tested (highlighted)
<span className="size-3 rounded-full bg-emerald-500" /> {t("Tested (highlighted)")}
</span>
<span className="inline-flex items-center gap-1.5">
<span className="size-3 rounded-full bg-neutral-400" /> Untested
<span className="size-3 rounded-full bg-neutral-400" /> {t("Untested")}
</span>
</>
)}
<span className="inline-flex items-center gap-1.5">
<span className="size-3 rounded-full border border-dashed border-neutral-400 bg-neutral-200" /> Out of scope
<span className="size-3 rounded-full border border-dashed border-neutral-400 bg-neutral-200" />{" "}
{t("Out of scope")}
</span>
</div>
<p className="text-muted-foreground/80 border-border/60 border-t pt-2 leading-relaxed">
Force-directed layout; drag nodes and scroll to zoom. The gray "⋯" is a fold node — click it to expand more.
{t('Force-directed layout; drag nodes and scroll to zoom. The gray "⋯" is a fold node — click it to expand more.')}
</p>
</div>
@@ -10,6 +10,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { TaskCredential } from "@/lib/types";
import { setVisibleInterval } from "@/lib/polling";
@@ -77,9 +78,9 @@ export function CredentialsTab({ taskId }: { taskId: string }) {
return (
<Card>
<CardHeader>
<CardTitle>Test accounts</CardTitle>
<CardTitle>{t("Test accounts")}</CardTitle>
<CardDescription>
Test accounts for this task. Entries with an empty password mean the agent registers that account and records it. Agent-recorded accounts appear here automatically.
{t("Test accounts for this task. Entries with an empty password mean the agent registers that account and records it. Agent-recorded accounts appear here automatically.")}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
@@ -89,9 +90,9 @@ export function CredentialsTab({ taskId }: { taskId: string }) {
) : items.length === 0 ? (
<Empty>
<EmptyHeader>
<EmptyTitle>No test accounts</EmptyTitle>
<EmptyTitle>{t("No test accounts")}</EmptyTitle>
<EmptyDescription>
Add one below, or declare them when creating the task — the agent reuses them for authenticated testing.
{t("Add one below, or declare them when creating the task — the agent reuses them for authenticated testing.")}
</EmptyDescription>
</EmptyHeader>
</Empty>
@@ -102,13 +103,13 @@ export function CredentialsTab({ taskId }: { taskId: string }) {
<code className="text-sm font-medium">{c.domain}</code>
<span className="text-muted-foreground text-sm">{c.username}</span>
<Badge variant={c.source === "agent" ? "secondary" : "outline"}>
{c.source === "agent" ? "agent-recorded" : "declared"}
{c.source === "agent" ? t("agent-recorded") : t("declared")}
</Badge>
<div className="ml-auto flex items-center gap-1">
<code className="max-w-40 truncate rounded bg-muted px-2 py-0.5 text-sm">
{c.password === "" ? "— agent generates —" : "stored, hidden"}
{c.password === "" ? t("— agent generates —") : t("stored, hidden")}
</code>
<Button size="icon" variant="ghost" className="size-7" aria-label="Delete credential" onClick={() => remove(c.id)}>
<Button size="icon" variant="ghost" className="size-7" aria-label={t("Delete credential")} onClick={() => remove(c.id)}>
<TrashIcon />
</Button>
</div>
@@ -118,18 +119,18 @@ export function CredentialsTab({ taskId }: { taskId: string }) {
</div>
)}
<div className="grid gap-2 sm:grid-cols-[1fr_1fr_1fr_auto]">
<Input placeholder="domain (e.g. target.example.com)" value={domain} onChange={(e) => setDomain(e.target.value)} />
<Input placeholder="email or username" value={username} onChange={(e) => setUsername(e.target.value)} />
<Input placeholder={t("domain (e.g. target.example.com)")} value={domain} onChange={(e) => setDomain(e.target.value)} />
<Input placeholder={t("email or username")} value={username} onChange={(e) => setUsername(e.target.value)} />
<Input
placeholder="password (empty = agent generates)"
placeholder={t("password (empty = agent generates)")}
type="text"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Button variant="outline" disabled={adding || !domain.trim() || !username.trim()} onClick={add}>
<PlusIcon /> Add
<PlusIcon /> {t("Add")}
</Button>
<Input className="sm:col-span-4" placeholder="note (optional, e.g. program alias account)" value={note} onChange={(e) => setNote(e.target.value)} />
<Input className="sm:col-span-4" placeholder={t("note (optional, e.g. program alias account)")} value={note} onChange={(e) => setNote(e.target.value)} />
</div>
</CardContent>
</Card>
@@ -11,6 +11,7 @@ import { StatusBadge } from "@/components/status-badge";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger } from "@/components/ui/select";
import { intlLocale, t } from "@/i18n";
import { api } from "@/lib/api";
import { useStoredSortPreference } from "@/lib/sort-preference";
import { statusMeta } from "@/lib/status";
@@ -26,7 +27,7 @@ const FINDING_SORT_PREFERENCE_KEY = "artex_task_findings_sort";
function findingLabel(finding: Finding): string {
if (finding.name?.trim()) return finding.name;
if (finding.vulnclass?.trim()) return finding.vulnclass;
return "Uncategorized";
return t("Uncategorized");
}
const FINDING_STATUSES: FindingStatus[] = [
@@ -68,14 +69,14 @@ function Row({
<span className="truncate font-medium">{findingLabel(f)}</span>
{f.inherited && f.source_task_id && (
<Badge variant="outline" className="shrink-0">
Source #{f.source_task_id} · read-only
{t("Source #{id} · read-only", { id: f.source_task_id })}
</Badge>
)}
</div>
<span className="truncate text-xs text-muted-foreground">{f.summary}</span>
</div>
</button>
<Badge variant="outline">Traffic evidence {f.traffic_count ?? 0}</Badge>
<Badge variant="outline">{t("Traffic evidence {count}", { count: f.traffic_count ?? 0 })}</Badge>
{f.assets && f.assets.length > 0 && (
<div className="hidden shrink-0 flex-wrap justify-end gap-1 sm:flex">
{f.assets.slice(0, 2).map((a) => (
@@ -109,7 +110,7 @@ function Row({
<StatusBadge domain="finding" value={f.status} dot />
)}
<span className="hidden shrink-0 text-xs text-muted-foreground md:block">
{new Date(f.ts).toLocaleString("zh-CN")}
{new Date(f.ts).toLocaleString(intlLocale)}
</span>
{f.finding_id && (
<Link
@@ -119,16 +120,16 @@ function Row({
: `/function/findings/detail?id=${f.finding_id}`
}
className="text-muted-foreground hover:text-primary inline-flex shrink-0 items-center gap-0.5 text-xs"
title="View vulnerability details"
title={t("View vulnerability details")}
>
Details
{t("Details")}
<ArrowUpRightIcon className="size-3" />
</Link>
)}
</div>
{open && (
<div className="bg-muted/30 px-4 pb-4 pl-11">
<div className="mb-1 text-xs font-medium text-muted-foreground">Evidence / PoC</div>
<div className="mb-1 text-xs font-medium text-muted-foreground">{t("Evidence / PoC")}</div>
<pre className="overflow-auto rounded-md border bg-background p-3 font-mono text-xs whitespace-pre-wrap">
{f.evidence}
</pre>
@@ -173,10 +174,10 @@ export function FindingsTab({ taskId }: { taskId: string }) {
setFindings((cur) => cur.map((x) => (x.id === f.id ? { ...x, status: next } : x)));
try {
await api.setFindingStatus(f.finding_id, next);
toast.success(`Marked as "${statusMeta("finding", next).label}"`);
toast.success(t("Marked as \"{status}\"", { status: statusMeta("finding", next).label }));
} catch (e) {
setFindings((cur) => cur.map((x) => (x.id === f.id ? { ...x, status: prev } : x)));
toast.error("Update failed: " + (e as Error).message);
toast.error(t("Update failed: {error}", { error: (e as Error).message }));
}
}, []);
@@ -192,11 +193,15 @@ export function FindingsTab({ taskId }: { taskId: string }) {
<Card className="overflow-hidden py-0">
<CardContent className="px-0">
<div className="flex items-center border-b px-4 py-2 text-xs text-muted-foreground">
<span className="min-w-0 flex-1">Vulnerabilities</span>
<span className="min-w-0 flex-1">{t("Vulnerabilities")}</span>
<button
type="button"
className="inline-flex items-center gap-1 outline-none focus-visible:underline"
aria-label={`Discovery time currently ${sortPreference.direction === "asc" ? "ascending" : "descending"}, click to toggle sort direction`}
aria-label={
sortPreference.direction === "asc"
? t("Discovery time currently ascending, click to toggle sort direction")
: t("Discovery time currently descending, click to toggle sort direction")
}
onClick={() =>
setSortPreference((current) => ({
field: "time",
@@ -204,7 +209,7 @@ export function FindingsTab({ taskId }: { taskId: string }) {
}))
}
>
<span>Discovery time</span>
<span>{t("Discovery time")}</span>
{sortPreference.direction === "asc" ? (
<ArrowUpIcon className="size-3.5" />
) : (
@@ -216,7 +221,7 @@ export function FindingsTab({ taskId }: { taskId: string }) {
<Row key={f.id} f={f} contextTaskId={taskId} onStatus={onStatus} />
))}
{items.length === 0 && (
<p className="px-4 py-8 text-center text-sm text-muted-foreground">No confirmed findings yet for this task or its directly linked tasks.</p>
<p className="px-4 py-8 text-center text-sm text-muted-foreground">{t("No confirmed findings yet for this task or its directly linked tasks.")}</p>
)}
</CardContent>
</Card>
@@ -28,11 +28,13 @@ import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select"
import { Progress } from "@/components/ui/progress";
import { Switch } from "@/components/ui/switch";
import { api } from "@/lib/api";
import { taskAssetTypeLabel } from "@/lib/task-assets";
import type {
AssetInterceptKind,
AssetInterceptRule,
Finding,
ModelTokenStat,
NewAssetType,
Stats,
Task,
TaskConstraint,
@@ -41,6 +43,7 @@ import type {
TaskScopeRow,
} from "@/lib/types";
import { setVisibleInterval } from "@/lib/polling";
import { intlLocale, t } from "@/i18n";
// Compact token count formatting (12345 → 12.3k, 2000000 → 2M).
function fmtTokens(n: number): string {
@@ -60,24 +63,24 @@ function scopeValue(row: TaskScopeRow): string {
if (row.value) return row.value;
if (row.domain) return row.domain;
if (row.net) return row.net;
if (row.company_id) return row.company_name?.trim() ? row.company_name : `Company #${row.company_id}`;
if (row.company_id) return row.company_name?.trim() ? row.company_name : t("Company #{id}", { id: row.company_id });
return "—";
}
const SCOPE_KIND_LABELS: Record<TaskScopeRow["kind"], string> = {
company: "Company",
root_domain: "Root domain",
subdomain: "Subdomain",
company: t("Company"),
root_domain: t("Root domain"),
subdomain: t("Subdomain"),
ip: "IP",
cidr: "CIDR",
icp: "ICP",
keyword: "Keyword",
keyword: t("Keyword"),
};
const SCOPE_SOURCE_LABELS: Record<TaskScopeRow["source"], string> = {
auto: "Auto",
agent: "Agent",
manual: "Manual",
auto: t("Auto"),
agent: t("Agent"),
manual: t("Manual"),
};
function StatCard({
@@ -186,7 +189,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
setGoalVuln("");
await loadGoals();
} catch (e) {
setGoalErr(e instanceof Error ? e.message : "Failed to add");
setGoalErr(e instanceof Error ? e.message : t("Failed to add"));
} finally {
setGoalBusy(false);
}
@@ -214,7 +217,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
cancelEditGoal();
await loadGoals();
} catch (e) {
setGoalErr(e instanceof Error ? e.message : "Failed to save");
setGoalErr(e instanceof Error ? e.message : t("Failed to save"));
} finally {
setGoalBusy(false);
}
@@ -248,7 +251,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
setConText("");
await loadConstraints();
} catch (e) {
setConErr(e instanceof Error ? e.message : "Failed to add");
setConErr(e instanceof Error ? e.message : t("Failed to add"));
} finally {
setConBusy(false);
}
@@ -276,7 +279,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
cancelEditConstraint();
await loadConstraints();
} catch (e) {
setConErr(e instanceof Error ? e.message : "Failed to save");
setConErr(e instanceof Error ? e.message : t("Failed to save"));
} finally {
setConBusy(false);
}
@@ -301,7 +304,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
setScopeValueInput("");
await loadScope();
} catch (e) {
setScopeErr(e instanceof Error ? e.message : "Failed to add");
setScopeErr(e instanceof Error ? e.message : t("Failed to add"));
} finally {
setScopeBusy(false);
}
@@ -439,16 +442,16 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<TargetIcon className="size-4 text-primary" /> Task description & goal
<TargetIcon className="size-4 text-primary" /> {t("Task description & goal")}
</CardTitle>
</CardHeader>
<CardContent className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-1.5">
<div className="text-xs font-medium text-muted-foreground">Description</div>
<div className="text-xs font-medium text-muted-foreground">{t("Description")}</div>
<p className="text-sm whitespace-pre-wrap break-words">{task?.description?.trim() || "—"}</p>
</div>
<div className="flex flex-col gap-1.5">
<div className="text-xs font-medium text-muted-foreground">Goal</div>
<div className="text-xs font-medium text-muted-foreground">{t("Goal")}</div>
<p className="text-sm whitespace-pre-wrap break-words">{task?.goal?.trim() || "—"}</p>
</div>
</CardContent>
@@ -458,9 +461,11 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ListChecksIcon className="size-4 text-primary" /> Goal management
<ListChecksIcon className="size-4 text-primary" /> {t("Goal management")}
<span className="text-muted-foreground text-xs font-normal">
(final verifiable goals, {goals.length} in total; adds/edits notify the planner and revive the task)
{t("(final verifiable goals, {count} in total; adds/edits notify the planner and revive the task)", {
count: goals.length,
})}
</span>
</CardTitle>
</CardHeader>
@@ -469,7 +474,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<div className="flex flex-wrap items-center gap-2">
<Input
className="h-7 min-w-56 flex-1 text-sm"
placeholder="Add a goal, e.g. 'gain unauthorized access with an admin account'"
placeholder={t("Add a goal, e.g. 'gain unauthorized access with an admin account'")}
value={goalText}
onChange={(e) => setGoalText(e.target.value)}
onKeyDown={(e) => {
@@ -479,7 +484,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
/>
<Input
className="h-7 w-32 text-sm"
placeholder="Vulnerability class (optional)"
placeholder={t("Vulnerability class (optional)")}
value={goalVuln}
onChange={(e) => setGoalVuln(e.target.value)}
onKeyDown={(e) => {
@@ -488,7 +493,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
disabled={goalBusy}
/>
<Button size="sm" variant="outline" disabled={goalBusy || !goalText.trim()} onClick={() => void addGoal()}>
<PlusIcon className="size-3.5" /> Add
<PlusIcon className="size-3.5" /> {t("Add")}
</Button>
{goalErr && <span className="text-xs text-red-500">{goalErr}</span>}
</div>
@@ -511,7 +516,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
/>
<Input
className="h-7 w-32 text-sm"
placeholder="Vulnerability class (optional)"
placeholder={t("Vulnerability class (optional)")}
value={editVuln}
onChange={(e) => setEditVuln(e.target.value)}
onKeyDown={(e) => {
@@ -571,7 +576,9 @@ export function OverviewTab({ taskId }: { taskId: string }) {
)}
</div>
) : (
<p className="text-muted-foreground text-sm">No goals yet. Once added, the planner dispatches exploration intents from them and judges completion.</p>
<p className="text-muted-foreground text-sm">
{t("No goals yet. Once added, the planner dispatches exploration intents from them and judges completion.")}
</p>
)}
</CardContent>
</Card>
@@ -581,9 +588,12 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ShieldAlertIcon className="size-4 text-amber-500" /> Operation constraints
<ShieldAlertIcon className="size-4 text-amber-500" /> {t("Operation constraints")}
<span className="text-muted-foreground text-xs font-normal">
(bounds planner/worker exploration, {constraints.length} in total; changes take effect at the next planning round)
{t(
"(bounds planner/worker exploration, {count} in total; changes take effect at the next planning round)",
{ count: constraints.length },
)}
</span>
</CardTitle>
</CardHeader>
@@ -595,12 +605,12 @@ export function OverviewTab({ taskId }: { taskId: string }) {
value={conKind}
onChange={(e) => setConKind(e.target.value as TaskConstraint["kind"])}
>
<NativeSelectOption value="deny">Deny</NativeSelectOption>
<NativeSelectOption value="allow">Allow</NativeSelectOption>
<NativeSelectOption value="deny">{t("Deny")}</NativeSelectOption>
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
</NativeSelect>
<Input
className="h-7 min-w-56 flex-1 text-sm"
placeholder="One operation constraint, e.g. 'test only the current port, do not scan other ports'"
placeholder={t("One operation constraint, e.g. 'test only the current port, do not scan other ports'")}
value={conText}
onChange={(e) => setConText(e.target.value)}
onKeyDown={(e) => {
@@ -614,7 +624,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
disabled={conBusy || !conText.trim()}
onClick={() => void addConstraint()}
>
<PlusIcon className="size-3.5" /> Add
<PlusIcon className="size-3.5" /> {t("Add")}
</Button>
{conErr && <span className="text-xs text-red-500">{conErr}</span>}
</div>
@@ -629,8 +639,8 @@ export function OverviewTab({ taskId }: { taskId: string }) {
value={editConKind}
onChange={(e) => setEditConKind(e.target.value as TaskConstraint["kind"])}
>
<NativeSelectOption value="deny">Deny</NativeSelectOption>
<NativeSelectOption value="allow">Allow</NativeSelectOption>
<NativeSelectOption value="deny">{t("Deny")}</NativeSelectOption>
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
</NativeSelect>
<Input
className="h-7 min-w-56 flex-1 text-sm"
@@ -671,7 +681,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
: "bg-red-500/15 text-red-600 dark:text-red-400"
}`}
>
{c.kind === "allow" ? "Allow" : "Deny"}
{c.kind === "allow" ? t("Allow") : t("Deny")}
</span>
<span className="min-w-0 flex-1 break-words">{c.text}</span>
<Button
@@ -698,7 +708,9 @@ export function OverviewTab({ taskId }: { taskId: string }) {
</div>
) : (
<p className="text-muted-foreground text-sm">
No operation constraints yet. They are extracted automatically from the description/goal at task creation; you can also add, edit, or delete them here to bound which operations are allowed/denied.
{t(
"No operation constraints yet. They are extracted automatically from the description/goal at task creation; you can also add, edit, or delete them here to bound which operations are allowed/denied.",
)}
</p>
)}
</CardContent>
@@ -708,8 +720,8 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<TargetIcon className="size-4 text-emerald-500" /> Asset test coverage
<span className="text-muted-foreground text-xs font-normal">(rough estimate, for reference only)</span>
<TargetIcon className="size-4 text-emerald-500" /> {t("Asset test coverage")}
<span className="text-muted-foreground text-xs font-normal">{t("(rough estimate, for reference only)")}</span>
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
@@ -718,7 +730,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
{coverage.pct != null ? Math.round(coverage.pct * 100) + "%" : "—"}
</span>
<span className="text-muted-foreground text-sm">
Tested {coverage.tested} / in scope {coverage.denominator}
{t("Tested {tested} / in scope {total}", { tested: coverage.tested, total: coverage.denominator })}
</span>
</div>
{coverage.pct != null && <Progress value={Math.round(coverage.pct * 100)} />}
@@ -726,7 +738,10 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<div className="flex flex-wrap gap-1.5 text-xs">
{coverage.by_type.map((b) => (
<span key={b.type} className="bg-muted rounded px-1.5 py-0.5">
<span className="text-muted-foreground">{b.type}</span>{" "}
<span className="text-muted-foreground">
{(taskAssetTypeLabel as (x: NewAssetType) => string | undefined)(b.type as NewAssetType) ||
b.type}
</span>{" "}
<span className="tabular-nums font-medium">
{b.tested}/{b.total}
</span>
@@ -739,11 +754,11 @@ export function OverviewTab({ taskId }: { taskId: string }) {
)}
{coverage.gaps && (
<div className="text-xs">
<span className="font-medium">Coverage gaps: {coverage.gaps.length}</span>
<span className="font-medium">{t("Coverage gaps: {count}", { count: coverage.gaps.length })}</span>
<ul className="text-muted-foreground mt-1 list-disc pl-4">
{coverage.gaps.map((g, i) => (
<li key={i}>
{g.kind} {g.surface ? g.surface + " " : ""}
{t(g.kind)} {g.surface ? g.surface + " " : ""}
{g.risk_area}
</li>
))}
@@ -757,9 +772,11 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<CoinsIcon className="size-4 text-amber-500" /> LLM token usage
<CoinsIcon className="size-4 text-amber-500" /> {t("LLM token usage")}
<span className="text-muted-foreground text-xs font-normal">
(per model{tokenTotals.calls > 0 ? `, ${tokenTotals.calls} calls in total` : ""})
{tokenTotals.calls > 0
? t("(per model, {count} calls in total)", { count: tokenTotals.calls })
: t("(per model)")}
</span>
</CardTitle>
</CardHeader>
@@ -769,19 +786,19 @@ export function OverviewTab({ taskId }: { taskId: string }) {
{/* Totals overview */}
<div className="flex flex-wrap items-baseline gap-x-4 gap-y-1 text-sm">
<span className="tabular-nums">
<span className="text-muted-foreground">Input </span>
<span className="text-muted-foreground">{t("Input")} </span>
<span className="font-semibold">{fmtTokens(tokenTotals.input)}</span>
</span>
<span className="tabular-nums">
<span className="text-muted-foreground">Output </span>
<span className="text-muted-foreground">{t("Output")} </span>
<span className="font-semibold">{fmtTokens(tokenTotals.output)}</span>
</span>
<span className="tabular-nums">
<span className="text-muted-foreground">Cache read </span>
<span className="text-muted-foreground">{t("Cache read")} </span>
<span className="font-semibold">{fmtTokens(tokenTotals.cacheRead)}</span>
</span>
<span className="tabular-nums">
<span className="text-muted-foreground">Cache hit rate </span>
<span className="text-muted-foreground">{t("Cache hit rate")} </span>
<span className="font-semibold text-emerald-500">
{cacheHitRate(tokenTotals.cacheRead, tokenTotals.input)}
</span>
@@ -792,12 +809,12 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<table className="w-full text-sm">
<thead>
<tr className="text-muted-foreground border-b text-left text-xs">
<th className="py-1.5 pr-3 font-medium">Model</th>
<th className="py-1.5 pr-3 text-right font-medium">Calls</th>
<th className="py-1.5 pr-3 text-right font-medium">Input</th>
<th className="py-1.5 pr-3 text-right font-medium">Output</th>
<th className="py-1.5 pr-3 text-right font-medium">Cache read</th>
<th className="py-1.5 text-right font-medium">Hit rate</th>
<th className="py-1.5 pr-3 font-medium">{t("Model")}</th>
<th className="py-1.5 pr-3 text-right font-medium">{t("Calls")}</th>
<th className="py-1.5 pr-3 text-right font-medium">{t("Input")}</th>
<th className="py-1.5 pr-3 text-right font-medium">{t("Output")}</th>
<th className="py-1.5 pr-3 text-right font-medium">{t("Cache read")}</th>
<th className="py-1.5 text-right font-medium">{t("Hit rate")}</th>
</tr>
</thead>
<tbody>
@@ -820,7 +837,9 @@ export function OverviewTab({ taskId }: { taskId: string }) {
</div>
</>
) : (
<p className="text-muted-foreground text-sm">No LLM usage yet (the task has made no calls, or records are still being written).</p>
<p className="text-muted-foreground text-sm">
{t("No LLM usage yet (the task has made no calls, or records are still being written).")}
</p>
)}
</CardContent>
</Card>
@@ -828,9 +847,9 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ShieldCheckIcon className="size-4 text-emerald-500" /> Test scope
<ShieldCheckIcon className="size-4 text-emerald-500" /> {t("Test scope")}
<span className="text-muted-foreground text-xs font-normal">
(coverage scope, not enforced, {scope.length} in total)
{t("(coverage scope, not enforced, {count} in total)", { count: scope.length })}
</span>
</CardTitle>
</CardHeader>
@@ -842,26 +861,26 @@ export function OverviewTab({ taskId }: { taskId: string }) {
value={scopeKind}
onChange={(e) => setScopeKind(e.target.value as TaskScopeRow["kind"])}
>
<NativeSelectOption value="root_domain">Root domain</NativeSelectOption>
<NativeSelectOption value="subdomain">Subdomain</NativeSelectOption>
<NativeSelectOption value="root_domain">{t("Root domain")}</NativeSelectOption>
<NativeSelectOption value="subdomain">{t("Subdomain")}</NativeSelectOption>
<NativeSelectOption value="ip">IP</NativeSelectOption>
<NativeSelectOption value="cidr">CIDR</NativeSelectOption>
<NativeSelectOption value="icp">ICP</NativeSelectOption>
<NativeSelectOption value="keyword">Keyword</NativeSelectOption>
<NativeSelectOption value="company">Company</NativeSelectOption>
<NativeSelectOption value="keyword">{t("Keyword")}</NativeSelectOption>
<NativeSelectOption value="company">{t("Company")}</NativeSelectOption>
</NativeSelect>
<Input
className="h-7 w-56 text-sm"
placeholder={
scopeKind === "company"
? "Company name or id"
? t("Company name or id")
: scopeKind === "ip" || scopeKind === "cidr"
? "e.g. 10.0.0.1 or 10.0.0.0/24"
? t("e.g. 10.0.0.1 or 10.0.0.0/24")
: scopeKind === "icp"
? "e.g. Beijing ICP No.12345678-1"
? t("e.g. Beijing ICP No.12345678-1")
: scopeKind === "keyword"
? "e.g. a company-name keyword"
: "e.g. example.com"
? t("e.g. a company-name keyword")
: t("e.g. example.com")
}
value={scopeValueInput}
onChange={(e) => setScopeValueInput(e.target.value)}
@@ -876,7 +895,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
disabled={scopeBusy || !scopeValueInput.trim()}
onClick={() => void addScope()}
>
<PlusIcon className="size-3.5" /> Add
<PlusIcon className="size-3.5" /> {t("Add")}
</Button>
{scopeErr && <span className="text-xs text-red-500">{scopeErr}</span>}
</div>
@@ -900,13 +919,15 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Trash2Icon className="size-3.5 text-red-500" />
</Button>
) : (
<span className="text-muted-foreground shrink-0 text-xs">Inherited</span>
<span className="text-muted-foreground shrink-0 text-xs">{t("Inherited")}</span>
)}
</div>
))}
</div>
) : (
<p className="text-muted-foreground text-sm">No test scope yet; once added it serves as the asset coverage denominator.</p>
<p className="text-muted-foreground text-sm">
{t("No test scope yet; once added it serves as the asset coverage denominator.")}
</p>
)}
</CardContent>
</Card>
@@ -914,12 +935,12 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ActivityIcon className="size-4 text-blue-500" /> Heartbeat
<ActivityIcon className="size-4 text-blue-500" /> {t("Heartbeat")}
</CardTitle>
</CardHeader>
<CardContent className="grid grid-cols-2 gap-4 sm:grid-cols-4">
<div>
<div className="text-xs text-muted-foreground">Engine state</div>
<div className="text-xs text-muted-foreground">{t("Engine state")}</div>
<StatusBadge
domain="engine"
value={stats?.engine_mode ?? task?.engine_mode ?? "idle"}
@@ -928,28 +949,28 @@ export function OverviewTab({ taskId }: { taskId: string }) {
/>
</div>
<div>
<div className="text-xs text-muted-foreground">Running workers</div>
<div className="text-xs text-muted-foreground">{t("Running workers")}</div>
<div className="mt-1 text-lg font-semibold tabular-nums">{running.length}</div>
</div>
<div>
<div className="text-xs text-muted-foreground">Last activity</div>
<div className="text-xs text-muted-foreground">{t("Last activity")}</div>
<div className="mt-1 inline-flex items-center gap-1 text-sm">
<ClockIcon className="size-3.5" />
{task?.last_activity ? new Date(task.last_activity).toLocaleTimeString("zh-CN") : "—"}
{task?.last_activity ? new Date(task.last_activity).toLocaleTimeString(intlLocale) : "—"}
</div>
</div>
<div>
<div className="text-xs text-muted-foreground">
Goals {task?.goals_met ?? 0}/{task?.goals_total ?? 0}
{t("Goals {met}/{total}", { met: task?.goals_met ?? 0, total: task?.goals_total ?? 0 })}
</div>
<Progress value={goalsPct} className="mt-2" />
</div>
{task?.completed_unix && task.completed_unix > 0 ? (
<div>
<div className="text-xs text-muted-foreground">Completed at</div>
<div className="text-xs text-muted-foreground">{t("Completed at")}</div>
<div className="mt-1 inline-flex items-center gap-1 text-sm">
<ClockIcon className="size-3.5" />
{new Date(task.completed_unix * 1000).toLocaleString("zh-CN")}
{new Date(task.completed_unix * 1000).toLocaleString(intlLocale)}
</div>
</div>
) : null}
@@ -961,7 +982,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm">
<TargetIcon className="size-4" /> Running intents
<TargetIcon className="size-4" /> {t("Running intents")}
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2">
@@ -971,32 +992,32 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<span className="min-w-0 flex-1 truncate">{i.payload}</span>
</div>
))}
{running.length === 0 && <p className="text-sm text-muted-foreground">No running intents</p>}
{running.length === 0 && <p className="text-sm text-muted-foreground">{t("No running intents")}</p>}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm">
<AlertTriangleIcon className="size-4 text-amber-500" /> Needs attention
<AlertTriangleIcon className="size-4 text-amber-500" /> {t("Needs attention")}
</CardTitle>
</CardHeader>
<CardContent className="grid grid-cols-2 gap-3 text-sm">
<div>
<div className="text-2xl font-semibold tabular-nums text-red-600">{taskFindings.length}</div>
<div className="text-xs text-muted-foreground">Confirmed vulnerabilities</div>
<div className="text-xs text-muted-foreground">{t("Confirmed vulnerabilities")}</div>
</div>
<div>
<div className="text-2xl font-semibold tabular-nums text-blue-600">{running.length}</div>
<div className="text-xs text-muted-foreground">Running</div>
<div className="text-xs text-muted-foreground">{t("Running")}</div>
</div>
<div>
<div className="text-2xl font-semibold tabular-nums">{open.length}</div>
<div className="text-xs text-muted-foreground">frontier open</div>
<div className="text-xs text-muted-foreground">{t("frontier open")}</div>
</div>
<div>
<div className="text-2xl font-semibold tabular-nums text-red-600">{blocked.length}</div>
<div className="text-xs text-muted-foreground">Blocked intents</div>
<div className="text-xs text-muted-foreground">{t("Blocked intents")}</div>
</div>
</CardContent>
</Card>
@@ -1004,7 +1025,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm">
<BugIcon className="size-4 text-red-500" /> Recent findings
<BugIcon className="size-4 text-red-500" /> {t("Recent findings")}
</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-2">
@@ -1014,7 +1035,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<span className="min-w-0 flex-1 truncate">{f.summary}</span>
</div>
))}
{taskFindings.length === 0 && <p className="text-sm text-muted-foreground">No findings yet</p>}
{taskFindings.length === 0 && <p className="text-sm text-muted-foreground">{t("No findings yet")}</p>}
</CardContent>
</Card>
</div>
@@ -1025,12 +1046,14 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Card className="border-red-500/30">
<CardHeader className="flex-row items-center justify-between gap-2 space-y-0">
<CardTitle className="flex items-center gap-2 text-sm">
<AlertTriangleIcon className="size-4 text-red-500" /> Blocked/errored intents
<span className="text-xs font-normal text-muted-foreground">({blocked.length} in total, re-runnable)</span>
<AlertTriangleIcon className="size-4 text-red-500" /> {t("Blocked/errored intents")}
<span className="text-xs font-normal text-muted-foreground">
{t("({count} in total, re-runnable)", { count: blocked.length })}
</span>
</CardTitle>
<Button size="sm" variant="outline" disabled={rerunning.has("__all__")} onClick={() => void rerunAll()}>
<RefreshCwIcon className={`size-3.5 ${rerunning.has("__all__") ? "animate-spin" : ""}`} />
Re-run all
{t("Re-run all")}
</Button>
</CardHeader>
<CardContent className="flex flex-col gap-2">
@@ -1046,13 +1069,15 @@ export function OverviewTab({ taskId }: { taskId: string }) {
onClick={() => void rerunOne(i.id)}
>
<RefreshCwIcon className={`size-3 ${rerunning.has(i.id) ? "animate-spin" : ""}`} />
Re-run
{t("Re-run")}
</Button>
</div>
))}
{blocked.length > 20 && (
<p className="text-xs text-muted-foreground">
Only the first 20 are shown; click "Re-run all" to handle the remaining {blocked.length - 20}.
{t('Only the first 20 are shown; click "Re-run all" to handle the remaining {count}.', {
count: blocked.length - 20,
})}
</p>
)}
</CardContent>
@@ -1061,21 +1086,26 @@ export function OverviewTab({ taskId }: { taskId: string }) {
{/* Stat cards */}
<div className="grid grid-cols-2 gap-4 lg:grid-cols-3">
<StatCard label="Open intents" value={open.length} icon={ShieldCheckIcon} sub="frontier open" />
<StatCard label="Confirmed findings" value={taskFindings.length} icon={BugIcon} sub="this task" />
<StatCard label="Total intents" value={intents.length} icon={AlertTriangleIcon} sub="all intents of this task" />
<StatCard label={t("Open intents")} value={open.length} icon={ShieldCheckIcon} sub={t("frontier open")} />
<StatCard label={t("Confirmed findings")} value={taskFindings.length} icon={BugIcon} sub={t("this task")} />
<StatCard
label={t("Total intents")}
value={intents.length}
icon={AlertTriangleIcon}
sub={t("all intents of this task")}
/>
</div>
</div>
);
}
const TASK_RULE_KIND_OPTIONS: { value: AssetInterceptKind; label: string; placeholder: string }[] = [
{ value: "exact_domain", label: "Domain (exact)", placeholder: "example.gov.cn" },
{ value: "exact_ip", label: "IP (exact)", placeholder: "203.0.113.10" },
{ value: "exact_url", label: "URL (exact)", placeholder: "https://example.com/login" },
{ value: "fuzzy_domain", label: "Domain (fuzzy)", placeholder: ".gov.cn" },
{ value: "fuzzy_ip", label: "IP (fuzzy)", placeholder: "203.0.113." },
{ value: "fuzzy_url", label: "URL (fuzzy)", placeholder: "/admin" },
{ value: "exact_domain", label: t("Domain (exact)"), placeholder: "example.gov.cn" },
{ value: "exact_ip", label: t("IP (exact)"), placeholder: "203.0.113.10" },
{ value: "exact_url", label: t("URL (exact)"), placeholder: "https://example.com/login" },
{ value: "fuzzy_domain", label: t("Domain (fuzzy)"), placeholder: ".gov.cn" },
{ value: "fuzzy_ip", label: t("IP (fuzzy)"), placeholder: "203.0.113." },
{ value: "fuzzy_url", label: t("URL (fuzzy)"), placeholder: "/admin" },
{ value: "cidr", label: "CIDR", placeholder: "192.168.0.0/16" },
];
@@ -1187,9 +1217,11 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ShieldCheckIcon className="size-4 text-sky-500" /> Task-level asset intercept / allow
<ShieldCheckIcon className="size-4 text-sky-500" /> {t("Task-level asset intercept / allow")}
<span className="text-muted-foreground text-xs font-normal">
(this task only, never global; block rules evaluate before allow rules, {rules.length} in total)
{t("(this task only, never global; block rules evaluate before allow rules, {count} in total)", {
count: rules.length,
})}
</span>
</CardTitle>
</CardHeader>
@@ -1197,8 +1229,8 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
{/* Add form */}
<div className="flex flex-wrap items-center gap-2">
<NativeSelect size="sm" value={newAction} onChange={(e) => setNewAction(e.target.value as "block" | "allow")}>
<NativeSelectOption value="block">Block</NativeSelectOption>
<NativeSelectOption value="allow">Allow</NativeSelectOption>
<NativeSelectOption value="block">{t("Block")}</NativeSelectOption>
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
</NativeSelect>
<NativeSelect size="sm" value={newKind} onChange={(e) => setNewKind(e.target.value as AssetInterceptKind)}>
{TASK_RULE_KIND_OPTIONS.map((o) => (
@@ -1219,13 +1251,13 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
/>
<Input
className="h-7 w-36 text-sm"
placeholder="Note (optional)"
placeholder={t("Note (optional)")}
value={newNote}
onChange={(e) => setNewNote(e.target.value)}
disabled={busy}
/>
<Button size="sm" variant="outline" disabled={busy || !newPattern.trim()} onClick={() => void add()}>
<PlusIcon className="size-3.5" /> Add
<PlusIcon className="size-3.5" /> {t("Add")}
</Button>
{err && <span className="text-xs text-red-500">{err}</span>}
</div>
@@ -1240,8 +1272,8 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
value={editAction}
onChange={(e) => setEditAction(e.target.value as "block" | "allow")}
>
<NativeSelectOption value="block">Block</NativeSelectOption>
<NativeSelectOption value="allow">Allow</NativeSelectOption>
<NativeSelectOption value="block">{t("Block")}</NativeSelectOption>
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
</NativeSelect>
<NativeSelect
size="sm"
@@ -1267,7 +1299,7 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
/>
<Input
className="h-7 w-36 text-sm"
placeholder="Note (optional)"
placeholder={t("Note (optional)")}
value={editNote}
onChange={(e) => setEditNote(e.target.value)}
disabled={busy}
@@ -1300,7 +1332,7 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
: "bg-red-500/15 text-red-600 dark:text-red-400"
}`}
>
{r.action === "allow" ? "Allow" : "Block"}
{r.action === "allow" ? t("Allow") : t("Block")}
</span>
<span className="text-muted-foreground shrink-0 text-xs">{TASK_RULE_KIND_LABEL[r.kind]}</span>
<code className="bg-muted min-w-0 flex-1 truncate rounded px-1.5 py-0.5 text-xs">{r.pattern}</code>
@@ -1332,7 +1364,9 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
</div>
) : (
<p className="text-muted-foreground text-sm">
No task-level rules. A "Block" hit forbids testing; "Allow" is a whitelist — once configured, this task only permits assets that match an allow rule (no whitelist when unconfigured).
{t(
'No task-level rules. A "Block" hit forbids testing; "Allow" is a whitelist — once configured, this task only permits assets that match an allow rule (no whitelist when unconfigured).',
)}
</p>
)}
</CardContent>
@@ -8,6 +8,7 @@ import { toast } from "sonner";
import { Markdown } from "@/components/markdown";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import { copyText } from "@/lib/utils";
@@ -40,10 +41,10 @@ export function ReportTab({ taskId }: { taskId: string }) {
const ok = await copyText(report);
if (ok) {
setCopied(true);
toast.success("Markdown copied");
toast.success(t("Markdown copied"));
setTimeout(() => setCopied(false), 1500);
} else {
toast.error("Copy failed; please select the text and copy it manually");
toast.error(t("Copy failed; please select the text and copy it manually"));
}
}
@@ -52,7 +53,7 @@ export function ReportTab({ taskId }: { taskId: string }) {
content = (
<div className="flex flex-col items-center justify-center gap-2 rounded-md border border-dashed py-16 text-muted-foreground text-sm">
<FileTextIcon className="size-8 opacity-40" />
Loading…
{t("Loading…")}
</div>
);
} else if (report) {
@@ -65,7 +66,7 @@ export function ReportTab({ taskId }: { taskId: string }) {
content = (
<div className="flex flex-col items-center justify-center gap-2 rounded-md border border-dashed py-16 text-muted-foreground text-sm">
<FileTextIcon className="size-8 opacity-40" />
No report yet
{t("No report yet")}
</div>
);
}
@@ -74,12 +75,12 @@ export function ReportTab({ taskId }: { taskId: string }) {
<Card>
<CardHeader className="flex-row items-center justify-between">
<CardTitle className="flex items-center gap-2 text-sm">
<FileTextIcon className="size-4" /> Penetration test report (Markdown)
<FileTextIcon className="size-4" /> {t("Penetration test report (Markdown)")}
</CardTitle>
<div className="flex gap-2">
{report && (
<Button size="sm" variant="outline" onClick={copy}>
{copied ? <CheckIcon /> : <CopyIcon />} Copy
{copied ? <CheckIcon /> : <CopyIcon />} {t("Copy")}
</Button>
)}
</div>
@@ -14,13 +14,14 @@ import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle }
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { Finding, FindingsPage } from "@/lib/types";
const PAGE_SIZE = 20;
function findingLabel(finding: Finding) {
return finding.name?.trim() || finding.vulnclass.trim() || "Uncategorized";
return finding.name?.trim() || finding.vulnclass.trim() || t("Uncategorized");
}
export function RetestsTab({ taskId }: { taskId: string }) {
@@ -73,9 +74,9 @@ export function RetestsTab({ taskId }: { taskId: string }) {
{error ? (
<Alert variant="destructive">
<AlertDescription>
Failed to load task vulnerabilities: {error}
{t("Failed to load task vulnerabilities: {error}", { error })}
<Button variant="outline" size="sm" onClick={refresh}>
Retry
{t("Retry")}
</Button>
</AlertDescription>
</Alert>
@@ -83,8 +84,8 @@ export function RetestsTab({ taskId }: { taskId: string }) {
<div className="grid items-start gap-4 lg:grid-cols-[minmax(16rem,22rem)_minmax(0,1fr)]">
<Card className="min-w-0">
<CardHeader>
<CardTitle>Select a vulnerability{data ? ` · ${data.total}` : ""}</CardTitle>
<CardDescription>View retest history for this task's vulnerabilities, or start a new retest.</CardDescription>
<CardTitle>{t("Select a vulnerability")}{data ? ` · ${data.total}` : ""}</CardTitle>
<CardDescription>{t("View retest history for this task's vulnerabilities, or start a new retest.")}</CardDescription>
</CardHeader>
<CardContent className="flex max-h-[32rem] flex-col overflow-y-auto">
{!loaded && !error ? <Skeleton className="h-24 w-full" /> : null}
@@ -94,7 +95,7 @@ export function RetestsTab({ taskId }: { taskId: string }) {
<Button
variant={finding.id === selectedId ? "secondary" : "ghost"}
className="h-auto w-full shrink-0 flex-col items-start gap-2 whitespace-normal py-3 text-left"
aria-label={`Select vulnerability: ${findingLabel(finding)}`}
aria-label={t("Select vulnerability: {name}", { name: findingLabel(finding) })}
aria-pressed={finding.id === selectedId}
onClick={() => setSelectedId(finding.id)}
>
@@ -109,8 +110,8 @@ export function RetestsTab({ taskId }: { taskId: string }) {
{loaded && findings.length === 0 ? (
<Empty>
<EmptyHeader>
<EmptyTitle>No vulnerabilities to retest</EmptyTitle>
<EmptyDescription>Once this task discovers vulnerabilities, you can manually start a retest here.</EmptyDescription>
<EmptyTitle>{t("No vulnerabilities to retest")}</EmptyTitle>
<EmptyDescription>{t("Once this task discovers vulnerabilities, you can manually start a retest here.")}</EmptyDescription>
</EmptyHeader>
</Empty>
) : null}
@@ -120,19 +121,19 @@ export function RetestsTab({ taskId }: { taskId: string }) {
<Button
variant="outline"
size="icon-sm"
aria-label="Previous page of vulnerabilities"
aria-label={t("Previous page of vulnerabilities")}
disabled={page === 1}
onClick={() => setPage(page - 1)}
>
<ChevronLeftIcon />
</Button>
<span className="text-muted-foreground text-xs">
Page {page} / {Math.ceil(data.total / PAGE_SIZE)}
{t("Page {page} / {total}", { page, total: Math.ceil(data.total / PAGE_SIZE) })}
</span>
<Button
variant="outline"
size="icon-sm"
aria-label="Next page of vulnerabilities"
aria-label={t("Next page of vulnerabilities")}
disabled={page * PAGE_SIZE >= data.total}
onClick={() => setPage(page + 1)}
>
@@ -148,7 +149,7 @@ export function RetestsTab({ taskId }: { taskId: string }) {
<h2 className="min-w-0 flex-1 break-words font-medium">{findingLabel(selected)}</h2>
<Button asChild variant="ghost" size="sm">
<Link href={`/function/findings/detail?id=${selected.finding_id || selected.id}`}>
Vulnerability details <ArrowUpRightIcon data-icon="inline-end" />
{t("Vulnerability details")} <ArrowUpRightIcon data-icon="inline-end" />
</Link>
</Button>
</div>
@@ -70,12 +70,13 @@ import type {
} from "@/lib/types";
import { cn } from "@/lib/utils";
import { setVisibleInterval } from "@/lib/polling";
import { intlLocale, t } from "@/i18n";
// resolutionLabel names the LLM a session runs on. The badge shows this alone and
// keeps the model id in its tooltip. Env-backed configs can arrive without a name,
// so fall back to the model id rather than rendering an empty badge.
function resolutionLabel(r: TaskLLMResolution): string {
return r.name || r.model || "Unnamed config";
return r.name || r.model || t("Unnamed config");
}
// fmtBytes renders a human file size for attachment chips (mirrors transcript.tsx).
@@ -109,6 +110,15 @@ function newWorkerMessageRequestID(): string {
);
}
// boldMarkup renders a translated sentence whose **marked** spans are bold, so the
// emphasis can move with Turkish word order instead of splitting the sentence.
function boldMarkup(text: string): React.ReactNode {
return text.split(/\*\*(.+?)\*\*/g).map((part, index) =>
// biome-ignore lint/suspicious/noArrayIndexKey: static split of a fixed string
index % 2 === 1 ? <strong key={index}>{part}</strong> : <React.Fragment key={index}>{part}</React.Fragment>,
);
}
function workerMessageCharCount(value: string): number {
return Array.from(value).length;
}
@@ -203,7 +213,7 @@ const TokenMetrics = React.forwardRef<
labels?: "short" | "long";
}
>(({ input, cache, output, labels = "short", className, ...props }, ref) => {
const names = labels === "short" ? ["In", "Cache", "Out"] : ["input", "cache", "output"];
const names = labels === "short" ? [t("In"), t("Cache"), t("Out")] : [t("input"), t("cache"), t("output")];
const values = [input, cache, output];
return (
<span
@@ -235,10 +245,10 @@ function fmtDuration(ms: number): string {
}
const roleMeta = {
mainagent: { label: "Main Agent", icon: UserIcon },
planner: { label: "Planner", icon: BrainIcon },
worker: { label: "Workers", icon: RadioIcon },
system: { label: "System audit", icon: HistoryIcon },
mainagent: { label: t("Main Agent"), icon: UserIcon },
planner: { label: t("Planner"), icon: BrainIcon },
worker: { label: t("Workers"), icon: RadioIcon },
system: { label: t("System audit"), icon: HistoryIcon },
} as const;
// The main-agent session is the interactive entry point of this tab and has no
@@ -250,7 +260,7 @@ const roleMeta = {
// segment is a switchable UI session; only the current (highest) one is writable.
const mainSessionId = (seg: number) => `s-main-${seg}`;
const mainSessionKey = (seg: number) => `main:${seg}`;
const mainSessionTitle = (seg: number) => `Main Agent · Session #${seg + 1}`;
const mainSessionTitle = (seg: number) => t("Main Agent · Session #{n}", { n: seg + 1 });
const MAIN_ID = mainSessionId(0);
const MAIN_SESSION: Session = {
id: MAIN_ID,
@@ -270,7 +280,7 @@ const PLANNER_ID = "s-planner";
const PLANNER_SESSION: Session = {
id: PLANNER_ID,
role: "planner",
title: "Planner · situational analysis",
title: t("Planner · situational analysis"),
status: "running",
live: true,
last_activity: "",
@@ -283,7 +293,7 @@ const SYSTEM_ID = "s-system";
const SYSTEM_SESSION: Session = {
id: SYSTEM_ID,
role: "system",
title: "System events · LLM failover",
title: t("System events · LLM failover"),
status: "done",
live: false,
last_activity: "",
@@ -327,7 +337,7 @@ function intentToSession(n: TaskNode): Session {
return {
id: n.id,
role: "worker",
title: label || `Intent ${n.id}`,
title: label || t("Intent {id}", { id: n.id }),
status: state,
live: !n.inherited && state === "running",
last_activity: n.ts,
@@ -392,7 +402,7 @@ function SessionItem({
)}
{s.inherited && s.source_task_id && (
<Badge variant="outline" className="shrink-0">
Source #{s.source_task_id}
{t("Source #{id}", { id: s.source_task_id })}
</Badge>
)}
<span
@@ -402,7 +412,7 @@ function SessionItem({
</span>
{deleted && (
<Badge variant="outline" className="shrink-0 border-destructive/40 text-destructive">
Deleted
{t("Deleted")}
</Badge>
)}
{hasPending && <ShieldAlertIcon className="size-3.5 shrink-0 text-amber-500" />}
@@ -414,7 +424,7 @@ function SessionItem({
{s.live && (
<span className="inline-flex items-center gap-1 rounded bg-blue-500/15 px-1.5 py-0.5 text-[10px] font-medium text-blue-600 dark:text-blue-400">
<span className="size-1 animate-pulse rounded-full bg-blue-500" />
Live
{t("Live")}
</span>
)}
</button>
@@ -426,8 +436,8 @@ function SessionItem({
size="icon-xs"
onClick={onCancel}
disabled={controlling}
title="Delete this intent (reason required; soft or hard delete)"
aria-label="Delete this intent (reason required; soft or hard delete)"
title={t("Delete this intent (reason required; soft or hard delete)")}
aria-label={t("Delete this intent (reason required; soft or hard delete)")}
className="text-destructive hover:text-destructive"
>
<Trash2Icon />
@@ -457,7 +467,7 @@ function WorkerAssetBadge({ assets }: { assets: IntentAsset[] }) {
<Tooltip>
<TooltipTrigger asChild>
<Badge variant="outline" className="max-w-60 shrink-0 font-normal" title={firstRawLabel}>
<span className="truncate">Current assets: {firstLabel}</span>
<span className="truncate">{t("Current assets: {label}", { label: firstLabel })}</span>
{displayAssets.length > 1 && <span className="shrink-0 tabular-nums">+{displayAssets.length - 1}</span>}
</Badge>
</TooltipTrigger>
@@ -468,7 +478,7 @@ function WorkerAssetBadge({ assets }: { assets: IntentAsset[] }) {
<div className="break-all font-mono text-xs">{asset.label.trim() || `#${asset.asset_id}`}</div>
<div className="mt-0.5 text-xs text-muted-foreground">
{taskAssetTypeLabel(asset.type)} · {taskAssetSourceLabel(asset.source)}
{asset.inherited ? ` · from source task #${asset.source_task_id}` : ""}
{asset.inherited ? ` · ${t("from source task #{id}", { id: asset.source_task_id ?? "" })}` : ""}
</div>
<div className="mt-0.5 [overflow-wrap:anywhere] text-xs">{asset.source_summary}</div>
</div>
@@ -496,7 +506,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
id,
role: "worker",
intent_id: id,
title: `Worker #${id}`,
title: t("Worker #{id}", { id }),
status: "done",
live: false,
last_activity: source.items[0]?.ts ?? "",
@@ -554,7 +564,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
const r = await api.chatUpload("task", taskId, Array.from(files));
setAttachments((prev) => [...prev, ...r.attachments]);
} catch (e) {
toast.error(`Upload failed: ${(e as Error).message}`);
toast.error(t("Upload failed: {error}", { error: (e as Error).message }));
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
@@ -577,7 +587,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
setListOpen(false);
setInput("");
} catch (e) {
toast.error(`Failed to create session: ${(e as Error).message}`);
toast.error(t("Failed to create session: {error}", { error: (e as Error).message }));
} finally {
setCreatingMain(false);
setConfirmNewMain(false);
@@ -597,7 +607,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
async (session: Session, action: "pause" | "resume" | "cancel", reason?: string, mode?: "soft" | "hard") => {
if (!session.intent_id || session.inherited || controllingIntent) return;
if (action === "cancel" && !reason?.trim()) {
toast.error("Please provide a deletion reason");
toast.error(t("Please provide a deletion reason"));
return;
}
setControllingIntent(session.intent_id);
@@ -605,25 +615,31 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
const res = await api.controlIntent(taskId, session.intent_id, action, reason, mode);
if (action === "pause") {
patchIntentState(session.intent_id, "paused");
toast.success(`Worker #${session.intent_id} paused`);
toast.success(t("Worker #{id} paused", { id: session.intent_id }));
} else if (action === "resume") {
patchIntentState(session.intent_id, "open");
toast.success(`Worker #${session.intent_id} resumed, waiting to be re-claimed`);
toast.success(t("Worker #{id} resumed, waiting to be re-claimed", { id: session.intent_id }));
} else if (mode === "hard") {
// Hard delete: the intent and its exclusive downstream are physically removed; drop the row from the list.
patchIntentState(session.intent_id);
const d = res.deleted;
const extra = d ? ` (including ${d.intents} intents / ${d.facts} facts / ${d.findings} findings)` : "";
toast.success(`Worker #${session.intent_id} and its exclusive downstream were permanently deleted${extra}`);
toast.success(
d
? t(
"Worker #{id} and its exclusive downstream were permanently deleted (including {intents} intents / {facts} facts / {findings} findings)",
{ id: session.intent_id, intents: d.intents, facts: d.facts, findings: d.findings },
)
: t("Worker #{id} and its exclusive downstream were permanently deleted", { id: session.intent_id }),
);
setCancelReason("");
} else {
// Soft delete: the intent is set to deleted with the reason recorded; nodes and output are kept.
patchIntentState(session.intent_id, "deleted");
toast.success(`Worker #${session.intent_id} deleted (reason recorded; the planner will re-plan accordingly)`);
toast.success(t("Worker #{id} deleted (reason recorded; the planner will re-plan accordingly)", { id: session.intent_id }));
setCancelReason("");
}
} catch (error) {
toast.error(`Worker operation failed: ${(error as Error).message}`);
toast.error(t("Worker operation failed: {error}", { error: (error as Error).message }));
} finally {
setControllingIntent(null);
setCancelIntent(null);
@@ -711,7 +727,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
patchStore(key, (s) => ({
...s,
loading: false,
error: (error as Error).message || "Failed to load",
error: (error as Error).message || t("Failed to load"),
}));
})
.finally(() => loadingKeysRef.current.delete(key));
@@ -739,7 +755,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
})
.catch((e) => {
if (reqTokenRef.current[key] !== token) return;
patchStore(key, (s) => ({ ...s, loading: false, error: (e as Error).message || "Failed to load" }));
patchStore(key, (s) => ({ ...s, loading: false, error: (e as Error).message || t("Failed to load") }));
})
.finally(() => loadingKeysRef.current.delete(key));
},
@@ -1037,7 +1053,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
.catch((err) => {
if (!alive || reqTokenRef.current.mainboot !== token) return;
if ((err as Error).message === "superseded") return;
patchStore(bootKey, (s) => ({ ...s, loading: false, error: (err as Error).message || "Failed to load" }));
patchStore(bootKey, (s) => ({ ...s, loading: false, error: (err as Error).message || t("Failed to load") }));
})
.finally(() => loadingKeysRef.current.delete(bootKey));
@@ -1155,7 +1171,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
const sessionMeta = React.useMemo(() => {
const map = new Map<string, { title: string; json: unknown; deleted: boolean; deleteReason: string }>();
for (const node of allIntents) {
let title = `Intent ${node.id}`;
let title = t("Intent {id}", { id: node.id });
let parsedPayload: unknown = node.payload;
// Soft delete: the intent's state='deleted'; the deletion reason lives on the separate delete_reason field.
const deleted = node.state === "deleted";
@@ -1517,7 +1533,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
.catch((e) => {
setInput(text); // restore so the user doesn't lose their text / attachments
setAttachments(atts);
toast.error(`Send failed: ${(e as Error).message || "please retry later"}`);
toast.error(t("Send failed: {error}", { error: (e as Error).message || t("please retry later") }));
})
.finally(() => setSending(false));
}
@@ -1528,7 +1544,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
if (side.handleCommand(message, () => setWorkerMessage(""))) return;
if (!intentId || active.inherited || active.status !== "paused" || workerMessageSending || !message) return;
if (workerMessageCharCount(message) > MAX_WORKER_MESSAGE_CHARS) {
toast.error(`Messages cannot exceed ${MAX_WORKER_MESSAGE_CHARS} characters`);
toast.error(t("Messages cannot exceed {count} characters", { count: MAX_WORKER_MESSAGE_CHARS }));
return;
}
const requestId = workerMessageRequestId || newWorkerMessageRequestID();
@@ -1542,10 +1558,10 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
patchIntentState(intentId, result.state);
setWorkerMessage("");
setWorkerMessageRequestId("");
toast.success(`Message sent to Worker #${intentId}; execution resumed immediately`);
toast.success(t("Message sent to Worker #{id}; execution resumed immediately", { id: intentId }));
})
.catch((error) => {
toast.error(`Send failed: ${(error as Error).message || "please retry later"}`);
toast.error(t("Send failed: {error}", { error: (error as Error).message || t("please retry later") }));
})
.finally(() => setWorkerMessageSending(false));
}
@@ -1591,7 +1607,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
<ChevronDownIcon
className={cn("size-3.5 shrink-0 transition-transform lg:hidden", !listOpen && "-rotate-90")}
/>
<span className="shrink-0">Sessions</span>
<span className="shrink-0">{t("Sessions")}</span>
{!listOpen && (
<>
<span className="min-w-0 truncate text-foreground lg:hidden" title={activeDisplayTitle}>
@@ -1611,17 +1627,21 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
"inline-flex items-center gap-1 text-[10px]",
sseLive ? "text-emerald-500" : "text-amber-500",
)}
title={sseLive ? "Live connection healthy" : "Live connection lost, reconnecting automatically (history still visible)"}
title={
sseLive
? t("Live connection healthy")
: t("Live connection lost, reconnecting automatically (history still visible)")
}
>
{sseLive ? (
<>
<span className="size-1 animate-pulse rounded-full bg-emerald-500" />
Live
{t("Live")}
</>
) : (
<>
<WifiOffIcon className="size-3" />
Reconnecting
{t("Reconnecting")}
</>
)}
</span>
@@ -1631,7 +1651,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
<Tooltip>
<TooltipTrigger asChild>
<div className="mt-2 flex min-w-0 flex-wrap items-center gap-1 text-xs text-muted-foreground">
<span>Task total</span>
<span>{t("Task total")}</span>
<span>·</span>
<TokenMetrics
input={taskTokens.input_tokens}
@@ -1641,9 +1661,12 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
</div>
</TooltipTrigger>
<TooltipContent>
Input {taskTokens.input_tokens.toLocaleString()} · Output {taskTokens.output_tokens.toLocaleString()} ·
Cache read {taskTokens.cache_read_tokens.toLocaleString()} · Cache write{" "}
{taskTokens.cache_write_tokens.toLocaleString()}
{t("Input {input} · Output {output} · Cache read {cacheRead} · Cache write {cacheWrite}", {
input: taskTokens.input_tokens.toLocaleString(intlLocale),
output: taskTokens.output_tokens.toLocaleString(intlLocale),
cacheRead: taskTokens.cache_read_tokens.toLocaleString(intlLocale),
cacheWrite: taskTokens.cache_write_tokens.toLocaleString(intlLocale),
})}
</TooltipContent>
</Tooltip>
)}
@@ -1671,8 +1694,8 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
type="button"
onClick={() => setConfirmNewMain(true)}
disabled={creatingMain}
title="New main agent session (clears context, task state preserved)"
aria-label="New main agent session"
title={t("New main agent session (clears context, task state preserved)")}
aria-label={t("New main agent session")}
className="ml-auto flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-muted-foreground hover:bg-accent/60 hover:text-foreground disabled:opacity-50"
>
{creatingMain ? (
@@ -1680,7 +1703,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
) : (
<PlusIcon className="size-3.5" />
)}
New
{t("New")}
</button>
)}
</div>
@@ -1721,14 +1744,14 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
) : (
<RotateCwIcon className="size-3.5" />
)}
Load earlier workers
{t("Load earlier workers")}
</button>
)}
</div>
);
})}
{mainLoaded && !workerSessions.length && (
<div className="px-2 py-1 text-xs text-muted-foreground">No running worker sessions.</div>
<div className="px-2 py-1 text-xs text-muted-foreground">{t("No running worker sessions.")}</div>
)}
</div>
</ScrollArea>
@@ -1737,7 +1760,11 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
{/* Right: transcript */}
<SideQuestionWorkspace
side={side}
label={active.role === "worker" ? `Worker #${active.intent_id} · ${activeDisplayTitle}` : activeDisplayTitle}
label={
active.role === "worker"
? `${t("Worker #{id}", { id: active.intent_id ?? "" })} · ${activeDisplayTitle}`
: activeDisplayTitle
}
>
<div className="flex min-h-0 flex-1 min-w-0 flex-col overflow-hidden rounded-lg border bg-card">
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 border-b px-3 py-2 sm:px-4 sm:py-2.5">
@@ -1746,7 +1773,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
const meta = isWorker ? sessionMeta.get(active.id) : undefined;
// Worker: the intent moved into the transcript as a message, so the
// header shows a stable generic label (intent JSON stays on hover).
const title = isWorker ? "Worker execution session" : active.title;
const title = isWorker ? t("Worker execution session") : active.title;
const titleEl = <span className="min-w-0 truncate text-sm font-medium">{title}</span>;
return meta?.json ? (
<Tooltip>
@@ -1767,34 +1794,38 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
variant="outline"
className="max-w-28 shrink-0 font-normal"
aria-label={
activeResolution.available ? `Current config: ${resolutionLabel(activeResolution)}` : "Model unavailable"
activeResolution.available
? t("Current config: {name}", { name: resolutionLabel(activeResolution) })
: t("Model unavailable")
}
>
<span className="truncate">
{activeResolution.available ? resolutionLabel(activeResolution) : "Model unavailable"}
{activeResolution.available ? resolutionLabel(activeResolution) : t("Model unavailable")}
</span>
</Badge>
</TooltipTrigger>
<TooltipContent side="bottom" className="max-w-xs [overflow-wrap:anywhere]">
{activeResolution.available
? [resolutionLabel(activeResolution), activeResolution.model].filter(Boolean).join(" / ")
: activeResolution.reason || "No available LLM config"}
: activeResolution.reason || t("No available LLM config")}
</TooltipContent>
</Tooltip>
)}
{activeAssets && activeAssets.length > 0 && <WorkerAssetBadge assets={activeAssets} />}
{active.inherited && active.source_task_id && (
<Badge variant="outline">Source task #{active.source_task_id} · read-only history</Badge>
<Badge variant="outline">
{t("Source task #{id} · read-only history", { id: active.source_task_id })}
</Badge>
)}
{active.live && (
<span className="inline-flex items-center gap-1 rounded bg-blue-500/15 px-1.5 py-0.5 text-[10px] font-medium text-blue-600 dark:text-blue-400">
<span className="size-1 animate-pulse rounded-full bg-blue-500" />
Live
{t("Live")}
</span>
)}
{activeState?.hasMore && (
<span className="text-[10px] text-muted-foreground" title="Scroll up to load earlier history">
↑ Earlier history
<span className="text-[10px] text-muted-foreground" title={t("Scroll up to load earlier history")}>
↑ {t("Earlier history")}
</span>
)}
<div className="ml-auto flex min-w-0 max-w-full items-center justify-end gap-x-3 gap-y-1 text-xs text-muted-foreground max-sm:w-full max-sm:flex-wrap">
@@ -1820,20 +1851,22 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
</span>
</TooltipTrigger>
<TooltipContent>
Input {activeTokens.input_tokens.toLocaleString()} · Output{" "}
{activeTokens.output_tokens.toLocaleString()} · Cache read{" "}
{activeTokens.cache_read_tokens.toLocaleString()} · Cache write{" "}
{activeTokens.cache_write_tokens.toLocaleString()}
{t("Input {input} · Output {output} · Cache read {cacheRead} · Cache write {cacheWrite}", {
input: activeTokens.input_tokens.toLocaleString(intlLocale),
output: activeTokens.output_tokens.toLocaleString(intlLocale),
cacheRead: activeTokens.cache_read_tokens.toLocaleString(intlLocale),
cacheWrite: activeTokens.cache_write_tokens.toLocaleString(intlLocale),
})}
</TooltipContent>
</Tooltip>
)}
{runDuration != null && (
<span className="inline-flex items-center gap-1" title="Run duration (first step → last step)">
<span className="inline-flex items-center gap-1" title={t("Run duration (first step → last step)")}>
<ClockIcon className="size-3" />
{fmtDuration(runDuration)}
</span>
)}
{isMain && <span>Interactive</span>}
{isMain && <span>{t("Interactive")}</span>}
</div>
</div>
{(() => {
@@ -1843,13 +1876,15 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
<div className="flex items-start gap-2 border-b border-destructive/30 bg-destructive/5 px-4 py-2.5 text-xs">
<Trash2Icon className="mt-0.5 size-3.5 shrink-0 text-destructive" />
<div className="min-w-0">
<span className="font-medium text-destructive">This intent was deleted by the user</span>
<span className="font-medium text-destructive">{t("This intent was deleted by the user")}</span>
<span className="text-muted-foreground">
(execution stopped and the planner notified; the intent and its output are kept — view the history below)
{t(
"(execution stopped and the planner notified; the intent and its output are kept — view the history below)",
)}
</span>
{dm.deleteReason && (
<p className="mt-1 break-words text-foreground">
<span className="text-muted-foreground">Deletion reason: </span>
<span className="text-muted-foreground">{t("Deletion reason:")} </span>
{dm.deleteReason}
</p>
)}
@@ -1876,25 +1911,25 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
{activeState?.loadingMore && (
<div className="flex items-center justify-center gap-2 pb-2 text-xs text-muted-foreground">
<Loader2Icon className="size-3.5 animate-spin" />
Loading earlier history…
{t("Loading earlier history…")}
</div>
)}
{showLoader ? (
<div className="flex items-center gap-2 pl-9 text-xs text-muted-foreground">
<Loader2Icon className="size-3.5 animate-spin" />
Loading activity stream…
{t("Loading activity stream…")}
</div>
) : activeState?.error ? (
<div className="flex items-center gap-2 pl-9 text-xs text-red-500">
<CircleXIcon className="size-3.5" />
Failed to load: {activeState.error}
{t("Failed to load: {error}", { error: activeState.error })}
<Button
size="sm"
variant="ghost"
className="h-6 px-2 text-xs"
onClick={() => loadSession(activeKey)}
>
Retry
{t("Retry")}
</Button>
</div>
) : activity.length ? (
@@ -1907,7 +1942,9 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
/>
) : (
<div className="pl-9 text-xs text-muted-foreground">
{isMain ? "No conversation yet. Message the main agent below to steer exploration or step into the flow." : "No activity records."}
{isMain
? t("No conversation yet. Message the main agent below to steer exploration or step into the flow.")
: t("No activity records.")}
</div>
)}
</div>
@@ -1929,7 +1966,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
type="button"
className="ml-0.5 text-muted-foreground hover:text-foreground"
onClick={() => setAttachments((p) => p.filter((x) => x.path !== a.path))}
title="Remove"
title={t("Remove")}
>
<XIcon className="size-3" />
</button>
@@ -1948,9 +1985,11 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
<MentionTextarea
inputGroup
rows={1}
aria-label="Message the main agent"
aria-label={t("Message the main agent")}
placeholder={
mainBusy ? "The main agent is running; type /btw to ask a side question…" : "Message the main agent; @ to reference findings, assets, and more…"
mainBusy
? t("The main agent is running; type /btw to ask a side question…")
: t("Message the main agent; @ to reference findings, assets, and more…")
}
value={input}
disabled={sending}
@@ -1968,13 +2007,13 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
variant="ghost"
onClick={() => fileInputRef.current?.click()}
disabled={mainBusy || uploading}
title="Upload file"
aria-label="Upload file"
title={t("Upload file")}
aria-label={t("Upload file")}
>
{uploading ? <Loader2Icon className="animate-spin" /> : <PaperclipIcon />}
</InputGroupButton>
{mainBusy && isBtwCommand(input) && (
<InputGroupButton size="icon-xs" onClick={send} aria-label="Send side question">
<InputGroupButton size="icon-xs" onClick={send} aria-label={t("Send side question")}>
<ArrowUpIcon />
</InputGroupButton>
)}
@@ -1985,8 +2024,8 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
variant="destructive"
onClick={stop}
disabled={stopping}
title="Stop current execution"
aria-label="Stop current execution"
title={t("Stop current execution")}
aria-label={t("Stop current execution")}
>
{stopping ? <Loader2Icon className="animate-spin" /> : <SquareIcon />}
</InputGroupButton>
@@ -1997,8 +2036,8 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
variant="default"
onClick={send}
disabled={(!input.trim() && attachments.length === 0) || sending}
title="Send message"
aria-label="Send message"
title={t("Send message")}
aria-label={t("Send message")}
>
{sending ? <Loader2Icon className="animate-spin" /> : <ArrowUpIcon />}
</InputGroupButton>
@@ -2014,8 +2053,10 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
<MentionTextarea
inputGroup
rows={1}
aria-label={`Message Worker #${active.intent_id}`}
placeholder={`Message Worker #${active.intent_id}; @ to reference records and adjust execution direction…`}
aria-label={t("Message Worker #{id}", { id: active.intent_id ?? "" })}
placeholder={t("Message Worker #{id}; @ to reference records and adjust execution direction…", {
id: active.intent_id ?? "",
})}
value={workerMessage}
onValueChange={(value) => {
setWorkerMessage(value);
@@ -2040,7 +2081,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
{workerMessageCharCount(workerMessage)}/{MAX_WORKER_MESSAGE_CHARS}
</span>
{active.status === "running" && isBtwCommand(workerMessage) && (
<InputGroupButton size="icon-xs" onClick={sendWorkerChat} aria-label="Send side question">
<InputGroupButton size="icon-xs" onClick={sendWorkerChat} aria-label={t("Send side question")}>
<ArrowUpIcon />
</InputGroupButton>
)}
@@ -2051,8 +2092,8 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
variant="destructive"
onClick={() => void controlWorker(active, "pause")}
disabled={controllingIntent === active.intent_id}
title="Pause current worker"
aria-label="Pause current worker"
title={t("Pause current worker")}
aria-label={t("Pause current worker")}
>
{controllingIntent === active.intent_id ? (
<Loader2Icon className="animate-spin" />
@@ -2068,13 +2109,13 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
variant="ghost"
onClick={() => void controlWorker(active, "resume")}
disabled={controllingIntent === active.intent_id || workerMessageSending}
title="Continue execution directly without sending a message"
aria-label="Continue execution directly"
title={t("Continue execution directly without sending a message")}
aria-label={t("Continue execution directly")}
>
{controllingIntent === active.intent_id ? (
<Loader2Icon className="animate-spin" />
) : (
"Continue directly"
t("Continue directly")
)}
</InputGroupButton>
<InputGroupButton
@@ -2086,8 +2127,8 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
!workerMessage.trim() ||
workerMessageCharCount(workerMessage) > MAX_WORKER_MESSAGE_CHARS
}
title="Send message"
aria-label="Send message"
title={t("Send message")}
aria-label={t("Send message")}
>
{workerMessageSending ? <Spinner /> : <ArrowUpIcon />}
</InputGroupButton>
@@ -2118,19 +2159,20 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
>
<AlertDialogContent className="max-w-[min(32rem,calc(100vw-2rem))]">
<AlertDialogHeader>
<AlertDialogTitle>Delete Worker #{cancelIntent?.intent_id}?</AlertDialogTitle>
<AlertDialogTitle>{t("Delete Worker #{id}?", { id: cancelIntent?.intent_id ?? "" })}</AlertDialogTitle>
<AlertDialogDescription className="break-words whitespace-normal">
{deleteMode === "hard" ? (
<>
<strong>Hard delete</strong> physically removes this intent and the downstream nodes <strong>supported solely by it</strong>
(cascading to the leaves to avoid orphaned data); shared nodes, goals, and the task's root facts are kept.
<strong>This action is irreversible.</strong> The planner is notified of the deletion and re-plans accordingly.
</>
boldMarkup(
t(
"**Hard delete** physically removes this intent and the downstream nodes **supported solely by it** (cascading to the leaves to avoid orphaned data); shared nodes, goals, and the task's root facts are kept. **This action is irreversible.** The planner is notified of the deletion and re-plans accordingly.",
),
)
) : (
<>
<strong>Soft delete</strong> marks the intent as "deleted" and records the reason; the intent node, execution records,
registered facts, and findings <strong>are all kept</strong>. The planner receives "intent deleted by user + reason" and re-plans accordingly.
</>
boldMarkup(
t(
'**Soft delete** marks the intent as "deleted" and records the reason; the intent node, execution records, registered facts, and findings **are all kept**. The planner receives "intent deleted by user + reason" and re-plans accordingly.',
),
)
)}
</AlertDialogDescription>
</AlertDialogHeader>
@@ -2144,8 +2186,8 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
deleteMode === "soft" ? "border-primary bg-primary/5" : "hover:bg-accent",
)}
>
<div className="font-medium">Soft delete</div>
<div className="text-xs text-muted-foreground">Data kept, traceable</div>
<div className="font-medium">{t("Soft delete")}</div>
<div className="text-xs text-muted-foreground">{t("Data kept, traceable")}</div>
</button>
<button
type="button"
@@ -2155,33 +2197,35 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
deleteMode === "hard" ? "border-destructive bg-destructive/5" : "hover:bg-accent",
)}
>
<div className="font-medium">Hard delete</div>
<div className="text-xs text-muted-foreground">Cascade removal, irreversible</div>
<div className="font-medium">{t("Hard delete")}</div>
<div className="text-xs text-muted-foreground">{t("Cascade removal, irreversible")}</div>
</button>
</div>
<div className="grid gap-2">
<label htmlFor="cancel-reason" className="text-sm font-medium">
Deletion reason (required)
{t("Deletion reason (required)")}
</label>
<Textarea
id="cancel-reason"
value={cancelReason}
onChange={(e) => setCancelReason(e.target.value)}
placeholder="Explain why this intent is being deleted, e.g. wrong direction / goal obsolete / duplicate of another intent…"
placeholder={t(
"Explain why this intent is being deleted, e.g. wrong direction / goal obsolete / duplicate of another intent…",
)}
rows={3}
autoFocus
/>
</div>
</div>
<AlertDialogFooter>
<AlertDialogCancel>Back</AlertDialogCancel>
<AlertDialogCancel>{t("Back")}</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
disabled={!cancelIntent || controllingIntent !== null || !cancelReason.trim()}
onClick={() => cancelIntent && void controlWorker(cancelIntent, "cancel", cancelReason, deleteMode)}
>
{controllingIntent ? <Loader2Icon className="animate-spin" /> : <Trash2Icon />}
{deleteMode === "hard" ? "Delete permanently" : "Confirm delete"}
{deleteMode === "hard" ? t("Delete permanently") : t("Confirm delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -2190,15 +2234,17 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
<AlertDialog open={confirmNewMain} onOpenChange={(open) => !open && setConfirmNewMain(false)}>
<AlertDialogContent className="max-w-[min(32rem,calc(100vw-2rem))]">
<AlertDialogHeader>
<AlertDialogTitle>Start a new session?</AlertDialogTitle>
<AlertDialogTitle>{t("Start a new session?")}</AlertDialogTitle>
<AlertDialogDescription className="break-words whitespace-normal">
The current session will be archived (you can switch back anytime) and the main agent continues with a clean context. The task's graph, assets, and goals are unaffected.
{t(
"The current session will be archived (you can switch back anytime) and the main agent continues with a clean context. The task's graph, assets, and goals are unaffected.",
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={creatingMain}>Cancel</AlertDialogCancel>
<AlertDialogCancel disabled={creatingMain}>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction disabled={creatingMain} onClick={() => void createMainSession()}>
{creatingMain ? "Starting…" : "Start new session"}
{creatingMain ? t("Starting…") : t("Start new session")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -36,6 +36,7 @@ import { SidebarTrigger } from "@/components/ui/sidebar";
import { Spinner } from "@/components/ui/spinner";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { LLMProfile, Task } from "@/lib/types";
@@ -53,17 +54,17 @@ import { SessionsTab } from "./_tabs/sessions-tab";
import { setVisibleInterval } from "@/lib/polling";
const TABS = [
{ value: "sessions", label: "Sessions" },
{ value: "overview", label: "Overview" },
{ value: "graph", label: "Exploration graph" },
{ value: "broadcast", label: "Broadcast" },
{ value: "findings", label: "Findings" },
{ value: "retests", label: "Retests" },
{ value: "assets", label: "Test assets" },
{ value: "credentials", label: "Credentials" },
{ value: "coverage", label: "Asset coverage" },
{ value: "intercept", label: "Interception approval" },
{ value: "report", label: "Report" },
{ value: "sessions", label: t("Sessions") },
{ value: "overview", label: t("Overview") },
{ value: "graph", label: t("Exploration graph") },
{ value: "broadcast", label: t("Broadcast") },
{ value: "findings", label: t("Findings") },
{ value: "retests", label: t("Retests") },
{ value: "assets", label: t("Test assets") },
{ value: "credentials", label: t("Credentials") },
{ value: "coverage", label: t("Asset coverage") },
{ value: "intercept", label: t("Interception approval") },
{ value: "report", label: t("Report") },
];
function taskProfileIDs(task: Task): string[] {
@@ -96,20 +97,22 @@ function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: L
if (task.active_llm_profile_id) activeID = String(task.active_llm_profile_id);
const activeProfile = profiles.find((profile) => profile.id === activeID);
const currentLabel = exhausted
? "Configuration chain exhausted"
? t("Configuration chain exhausted")
: task.llm_rotate
? `Worker rotation (${chain.length})`
: (activeProfile?.name ?? (activeID ? `Config #${activeID}` : "Follow default config"));
? t("Worker rotation ({count})", { count: chain.length })
: (activeProfile?.name ?? (activeID ? t("Config #{id}", { id: activeID }) : t("Follow default config")));
const activeIndex = chain.indexOf(activeID);
const backupCount = activeIndex >= 0 ? Math.max(0, chain.length - activeIndex - 1) : 0;
const currentTitle = [currentLabel, activeProfile?.model, backupCount > 0 ? `${backupCount} backups` : ""]
const currentTitle = [currentLabel, activeProfile?.model, backupCount > 0 ? t("{count} backups", { count: backupCount }) : ""]
.filter(Boolean)
.join(" · ");
let editorDescription = "Rotation changes apply to new worker intents. Profile changes apply to subsequent LLM calls; in-flight calls keep their provider. Saving resets exhausted profiles.";
if (terminal) editorDescription = "The task has ended; changes only affect subsequent main agent conversations.";
let saveLabel = "Save";
if (exhausted) saveLabel = "Save and reset";
if (saving) saveLabel = "Saving";
let editorDescription = t(
"Rotation changes apply to new worker intents. Profile changes apply to subsequent LLM calls; in-flight calls keep their provider. Saving resets exhausted profiles.",
);
if (terminal) editorDescription = t("The task has ended; changes only affect subsequent main agent conversations.");
let saveLabel = t("Save");
if (exhausted) saveLabel = t("Save and reset");
if (saving) saveLabel = t("Saving");
const syncDraft = React.useCallback(() => {
const next = taskProfileIDs(task);
@@ -142,14 +145,14 @@ function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: L
} else {
toast.success(
result.reopened_intents > 0
? `LLM configs updated and ${result.reopened_intents} quota-blocked intents reopened`
: "LLM configs updated",
? t("LLM configs updated and {count} quota-blocked intents reopened", { count: result.reopened_intents })
: t("LLM configs updated"),
);
}
setOpen(false);
onUpdated();
} catch (error) {
toast.error("Update failed: " + (error as Error).message);
toast.error(t("Update failed: {error}", { error: (error as Error).message }));
} finally {
setSaving(false);
}
@@ -161,7 +164,7 @@ function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: L
<Button
size="sm"
variant={exhausted ? "destructive" : "outline"}
aria-label="View or switch the task LLM config"
aria-label={t("View or switch the task LLM config")}
title={currentTitle}
>
<BrainIcon data-icon="inline-start" />
@@ -171,16 +174,19 @@ function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: L
</PopoverTrigger>
<PopoverContent ref={popoverContentRef} align="start" className="w-[min(28rem,calc(100vw-2rem))] gap-4 p-4">
<PopoverHeader>
<PopoverTitle>Task LLM config chain{task.llm_rotate ? " · Worker rotation on" : ""}</PopoverTitle>
<PopoverTitle>
{task.llm_rotate ? t("Task LLM config chain · Worker rotation on") : t("Task LLM config chain")}
</PopoverTitle>
<PopoverDescription>{editorDescription}</PopoverDescription>
</PopoverHeader>
{exhausted && (
<Alert variant="destructive">
<CircleAlertIcon />
<AlertTitle>Configuration chain quota exhausted</AlertTitle>
<AlertTitle>{t("Configuration chain quota exhausted")}</AlertTitle>
<AlertDescription>
{task.llm_failover_reason ?? "All selected configs were judged to be out of quota. Saving the chain resets the failure state."}
{task.llm_failover_reason ??
t("All selected configs were judged to be out of quota. Saving the chain resets the failure state.")}
</AlertDescription>
</Alert>
)}
@@ -200,7 +206,7 @@ function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: L
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" size="sm" onClick={() => setOpen(false)}>
Close
{t("Close")}
</Button>
<Button type="button" size="sm" onClick={save} disabled={saving}>
{saving && <Spinner data-icon="inline-start" />}
@@ -291,9 +297,9 @@ function TaskDetailInner() {
try {
await api.controlTask(id, next ? "pause" : "resume");
setPaused(next);
toast.success(next ? "Exploration paused" : "Exploration resumed");
toast.success(next ? t("Exploration paused") : t("Exploration resumed"));
} catch (e) {
toast.error("Operation failed: " + (e as Error).message);
toast.error(t("Operation failed: {error}", { error: (e as Error).message }));
}
}
@@ -302,10 +308,10 @@ function TaskDetailInner() {
setArchiving(true);
try {
await api.archiveTask(task.id);
toast.success("Task queued for archiving");
toast.success(t("Task queued for archiving"));
router.push("/function/tasks");
} catch (error) {
toast.error(`Archive failed: ${(error as Error).message}`);
toast.error(t("Archive failed: {error}", { error: (error as Error).message }));
setArchiving(false);
}
}
@@ -313,11 +319,11 @@ function TaskDetailInner() {
if (!task) {
return (
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-10 text-center">
<p className="text-muted-foreground">{loaded ? `Task ${id} was deleted, archived, or does not exist` : "Loading…"}</p>
<p className="text-muted-foreground">{loaded ? t("Task {id} was deleted, archived, or does not exist", { id }) : t("Loading…")}</p>
{loaded && (
<Button asChild variant="outline">
<Link href="/function/tasks">
<ArrowLeftIcon /> Back to task list
<ArrowLeftIcon /> {t("Back to task list")}
</Link>
</Button>
)}
@@ -329,29 +335,32 @@ function TaskDetailInner() {
const terminal = ["done", "failed", "timeout"].includes(task.status);
const archiveLifecycleEligible = terminal || paused || task.status === "paused";
const canArchive = archiveLifecycleEligible && !task.archive_blocked_by_task_id;
let archiveDisabledReason = task.queued ? "Queued tasks must be paused first" : "Running tasks must be paused first";
let archiveDisabledReason = task.queued ? t("Queued tasks must be paused first") : t("Running tasks must be paused first");
if (archiveLifecycleEligible && task.archive_blocked_by_task_id) {
archiveDisabledReason = `The task is directly inherited by unarchived task #${task.archive_blocked_by_task_id}; archive the dependent task first`;
archiveDisabledReason = t(
"The task is directly inherited by unarchived task #{id}; archive the dependent task first",
{ id: task.archive_blocked_by_task_id },
);
}
const engineMode = paused ? "paused" : (task.engine_mode ?? "idle");
let controlVariant: "default" | "secondary" | "outline" = "outline";
let controlIcon = <PauseIcon data-icon="inline-start" />;
let controlLabel = "Pause";
let controlLabel = t("Pause");
if (terminal) {
controlVariant = "secondary";
controlIcon = <CheckIcon data-icon="inline-start" />;
controlLabel = completed ? "Completed" : "Ended";
controlLabel = completed ? t("Completed") : t("Ended");
} else if (paused) {
controlVariant = "default";
controlIcon = <PlayIcon data-icon="inline-start" />;
controlLabel = "Resume";
controlLabel = t("Resume");
}
const archiveTrigger = (
<Button
size="icon-sm"
variant="ghost"
disabled={!canArchive || archiving}
aria-label={canArchive ? "Archive task" : archiveDisabledReason}
aria-label={canArchive ? t("Archive task") : archiveDisabledReason}
>
{archiving ? <Spinner /> : <ArchiveIcon />}
</Button>
@@ -382,15 +391,16 @@ function TaskDetailInner() {
<AlertDialogTrigger asChild>{archiveTrigger}</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Archive task #{task.id}?</AlertDialogTitle>
<AlertDialogTitle>{t("Archive task #{id}?", { id: task.id })}</AlertDialogTitle>
<AlertDialogDescription>
The task graph, related records, exclusive assets and traffic, working files, and LLM
history will be compressed into cold storage. Once archiving completes, restore it from the "Archived" tab of the task list.
{t(
"The task graph, related records, exclusive assets and traffic, working files, and LLM history will be compressed into cold storage. Once archiving completes, restore it from the \"Archived\" tab of the task list.",
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => void archiveTask()}>Confirm archive</AlertDialogAction>
<AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={() => void archiveTask()}>{t("Confirm archive")}</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
@@ -411,10 +421,10 @@ function TaskDetailInner() {
{/* Tabs */}
<div className="no-scrollbar min-w-0 overflow-x-auto">
<TabsList variant="default" className="min-w-max">
{TABS.map((t) => (
<TabsTrigger key={t.value} value={t.value}>
{t.label}
{t.value === "intercept" && interceptPendingCount > 0 && (
{TABS.map((tabItem) => (
<TabsTrigger key={tabItem.value} value={tabItem.value}>
{tabItem.label}
{tabItem.value === "intercept" && interceptPendingCount > 0 && (
<span className="ml-1.5 inline-flex h-4 min-w-[16px] items-center justify-center rounded-full bg-amber-500 px-1 text-[10px] font-semibold leading-none text-white">
{interceptPendingCount > 99 ? "99+" : interceptPendingCount}
</span>
File diff suppressed because it is too large Load Diff
@@ -14,6 +14,7 @@ import { ApiError, api } from "@/lib/api";
import { parseRawRequest, splitReplayHeaders } from "@/lib/replay";
import type { TrafficExchange, TrafficReplayHeader, TrafficReplayResult } from "@/lib/types";
import { cn } from "@/lib/utils";
import { t } from "@/i18n";
type HeaderRow = TrafficReplayHeader & { key: number };
@@ -46,18 +47,18 @@ function initialForm(exchange: TrafficExchange, raw: string): ReplayForm {
}
const ERROR_TITLES: Record<number, string> = {
400: "Invalid request",
413: "Request body too large",
502: "Proxy or upstream error",
503: "Traffic capture is disabled",
504: "Timed out",
400: t("Invalid request"),
413: t("Request body too large"),
502: t("Proxy or upstream error"),
503: t("Traffic capture is disabled"),
504: t("Timed out"),
};
// The server's message, under a title that says what the status means.
function describeError(e: unknown): { title: string; message: string } {
const message = e instanceof Error ? e.message : String(e);
if (!(e instanceof ApiError)) return { title: "Replay failed", message };
return { title: ERROR_TITLES[e.status] ?? `Replay failed (${e.status})`, message };
if (!(e instanceof ApiError)) return { title: t("Replay failed"), message };
return { title: ERROR_TITLES[e.status] ?? t("Replay failed ({status})", { status: e.status }), message };
}
// ReplayPanel edits the selected exchange's request and sends it again through
@@ -135,7 +136,8 @@ export function ReplayPanel({
<div className="space-y-4 p-5">
<div className="flex gap-2">
<Input
aria-label="Method"
aria-label={t("Method")}
lang="en"
className="w-32 font-mono uppercase"
list={methodListId}
value={form.method}
@@ -156,42 +158,42 @@ export function ReplayPanel({
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="font-medium text-sm">Headers</span>
<span className="font-medium text-sm">{t("Headers")}</span>
<Button
size="sm"
variant="outline"
onClick={() => update({ rows: [...form.rows, ...toRows([{ name: "", value: "" }])] })}
>
<PlusIcon />
Add header
{t("Add header")}
</Button>
</div>
<p className="text-muted-foreground text-xs">Host is taken from the URL.</p>
<p className="text-muted-foreground text-xs">{t("Host is taken from the URL.")}</p>
{form.dropped.length > 0 && (
<p className="text-muted-foreground text-xs">
Not sent (hop-by-hop or recomputed by the server): {form.dropped.join(", ")}
{t("Not sent (hop-by-hop or recomputed by the server): {headers}", { headers: form.dropped.join(", ") })}
</p>
)}
{form.rows.map((row) => (
<div key={row.key} className="flex items-center gap-2">
<Input
aria-label="Header name"
aria-label={t("Header name")}
className={cn("w-48 font-mono text-xs", ignored.has(row.name.trim().toLowerCase()) && "line-through")}
placeholder="Name"
placeholder={t("Name")}
value={row.name}
onChange={(e) => updateRow(row.key, { name: e.target.value })}
/>
<Input
aria-label="Header value"
aria-label={t("Header value")}
className="flex-1 font-mono text-xs"
placeholder="Value"
placeholder={t("Value")}
value={row.value}
onChange={(e) => updateRow(row.key, { value: e.target.value })}
/>
<Button
size="icon"
variant="ghost"
aria-label="Remove header"
aria-label={t("Remove header")}
onClick={() => update({ rows: form.rows.filter((r) => r.key !== row.key) })}
>
<XIcon />
@@ -199,28 +201,29 @@ export function ReplayPanel({
</div>
))}
{ignored.size > 0 && (
<p className="text-muted-foreground text-xs">Struck-through headers are not sent by the server.</p>
<p className="text-muted-foreground text-xs">{t("Struck-through headers are not sent by the server.")}</p>
)}
</div>
<div className="space-y-2">
<span className="font-medium text-sm">Body</span>
<span className="font-medium text-sm">{t("Body")}</span>
{form.binary ? (
<p className="rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-amber-700 text-xs dark:text-amber-400">
The recorded body is binary (it contains NUL bytes). Replaying a binary body is not supported.
{t("The recorded body is binary (it contains NUL bytes). Replaying a binary body is not supported.")}
</p>
) : (
<>
<Textarea
aria-label="Body"
aria-label={t("Body")}
className="font-mono text-xs"
value={form.body}
onChange={(e) => update({ body: e.target.value })}
/>
{form.bodyPreviewOnly && (
<p className="text-amber-700 text-xs dark:text-amber-400">
The recorded body was too large to keep inline; only its preview is loaded, so replay is disabled for
this exchange.
{t(
"The recorded body was too large to keep inline; only its preview is loaded, so replay is disabled for this exchange.",
)}
</p>
)}
</>
@@ -229,7 +232,7 @@ export function ReplayPanel({
<Button onClick={send} disabled={!canSend}>
{sending ? <Loader2Icon className="animate-spin" /> : <SendIcon />}
Send
{t("Send")}
</Button>
{error && (
@@ -246,19 +249,19 @@ export function ReplayPanel({
{result.status}
</Badge>
<span className="text-muted-foreground tabular-nums">{result.duration_ms} ms</span>
{result.truncated && <Badge variant="outline">truncated</Badge>}
{result.truncated && <Badge variant="outline">{t("truncated")}</Badge>}
</div>
{!result.recorded && (
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-amber-700 text-xs dark:text-amber-400">
Passthrough host: the response is shown here but was not recorded.
{t("Passthrough host: the response is shown here but was not recorded.")}
</div>
)}
{sortedHeaders.length > 0 && (
<Table>
<TableHeader>
<TableRow>
<TableHead>Header</TableHead>
<TableHead>Value</TableHead>
<TableHead>{t("Header")}</TableHead>
<TableHead>{t("Value")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -8,6 +8,7 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { api } from "@/lib/api";
import type { TrafficStreamMessage } from "@/lib/types";
import { intlLocale, t } from "@/i18n";
const PAGE_SIZE = 50;
// Binary payloads loaded in full are shown as hex of their first 64 KiB.
@@ -22,8 +23,8 @@ function fmtBytes(n: number) {
}
function fmtDirection(direction: string) {
if (direction === "c2s") return "client -> server";
if (direction === "s2c") return "server -> client";
if (direction === "c2s") return t("client -> server");
if (direction === "s2c") return t("server -> client");
return direction;
}
@@ -53,7 +54,7 @@ function StreamMessageRow({ message }: { message: TrafficStreamMessage }) {
.trafficBlob(message.blob)
.then((bytes) => {
const text = binary
? `${hexDump(bytes.subarray(0, HEX_PREVIEW_BYTES))}\n(${bytes.length} bytes total)`
? `${hexDump(bytes.subarray(0, HEX_PREVIEW_BYTES))}\n${t("({count} bytes total)", { count: bytes.length })}`
: new TextDecoder().decode(bytes);
setFull({ loading: false, text });
})
@@ -64,7 +65,7 @@ function StreamMessageRow({ message }: { message: TrafficStreamMessage }) {
return (
<div className="mx-5 my-3 space-y-1 rounded-md border border-amber-500/40 bg-amber-500/10 p-3">
<div className="font-medium text-amber-700 text-xs dark:text-amber-400">
#{message.seq} Recording limit reached: later messages were not stored
{t("#{seq} Recording limit reached: later messages were not stored", { seq: message.seq })}
</div>
<pre className={payloadClass}>{message.payload}</pre>
</div>
@@ -76,14 +77,14 @@ function StreamMessageRow({ message }: { message: TrafficStreamMessage }) {
<div className="flex flex-wrap items-center gap-2 text-xs">
<span className="font-mono text-muted-foreground tabular-nums">#{message.seq}</span>
<Badge variant="outline">{fmtDirection(message.direction)}</Badge>
<Badge variant="secondary">{message.type}</Badge>
<Badge variant="secondary">{t(message.type)}</Badge>
{binary && message.encoding === "base64" && <Badge variant="outline">base64</Badge>}
{message.truncated && <Badge variant="destructive">truncated</Badge>}
{message.truncated && <Badge variant="destructive">{t("truncated")}</Badge>}
{message.event && <span className="font-mono">event: {message.event}</span>}
{message.event_id && <span className="font-mono">id: {message.event_id}</span>}
{message.retry ? <span className="font-mono">retry: {message.retry}</span> : null}
<span className="ml-auto text-muted-foreground tabular-nums">
{fmtBytes(message.size)} · {new Date(message.ts * 1000).toLocaleTimeString()}
{fmtBytes(message.size)} · {new Date(message.ts * 1000).toLocaleTimeString(intlLocale)}
</span>
</div>
<pre className={payloadClass}>{full?.text ?? message.payload}</pre>
@@ -93,7 +94,7 @@ function StreamMessageRow({ message }: { message: TrafficStreamMessage }) {
{!full?.text && (
<Button variant="outline" size="xs" disabled={full?.loading} onClick={loadFull}>
{full?.loading && <Loader2Icon className="animate-spin" />}
Load full payload
{t("Load full payload")}
</Button>
)}
{full?.error && <span className="text-destructive">{full.error}</span>}
@@ -153,11 +154,15 @@ export function StreamMessagesPanel({ exchangeId, kind }: { exchangeId: string;
<div className="flex flex-col">
<div className="flex items-center gap-2 px-5 py-3 text-muted-foreground text-xs">
<span>
{kind === "websocket" ? "WebSocket" : "Server-Sent Events"} · {items.length} of {total} messages
{t("{kind} · {count} of {total} messages", {
kind: kind === "websocket" ? "WebSocket" : "Server-Sent Events",
count: items.length,
total,
})}
</span>
<Button variant="outline" size="xs" className="ml-auto" disabled={loading} onClick={() => load(0)}>
<RefreshCwIcon className={loading ? "animate-spin" : undefined} />
Refresh
{t("Refresh")}
</Button>
</div>
{renderBody()}
@@ -169,15 +174,15 @@ export function StreamMessagesPanel({ exchangeId, kind }: { exchangeId: string;
return (
<div className="flex items-center gap-2 p-5 text-muted-foreground text-xs">
<Loader2Icon className="size-3.5 animate-spin" />
Loading messages…
{t("Loading messages…")}
</div>
);
}
if (error) {
return <div className="p-5 text-destructive text-xs">Failed to load messages: {error}</div>;
return <div className="p-5 text-destructive text-xs">{t("Failed to load messages: {error}", { error })}</div>;
}
if (items.length === 0) {
return <div className="p-5 text-muted-foreground text-xs">No messages recorded for this stream.</div>;
return <div className="p-5 text-muted-foreground text-xs">{t("No messages recorded for this stream.")}</div>;
}
return (
<>
@@ -190,7 +195,7 @@ export function StreamMessagesPanel({ exchangeId, kind }: { exchangeId: string;
<div className="flex justify-center p-4">
<Button variant="outline" size="sm" disabled={loadingMore} onClick={() => load(items.length)}>
{loadingMore && <Loader2Icon className="animate-spin" />}
Load more
{t("Load more")}
</Button>
</div>
)}
+99 -71
View File
@@ -46,12 +46,13 @@ import { setVisibleInterval } from "@/lib/polling";
import { useStoredSortPreference } from "@/lib/sort-preference";
import type { TrafficDetail, TrafficExchange, TrafficHost, TrafficResp } from "@/lib/types";
import { cn } from "@/lib/utils";
import { intlLocale, t } from "@/i18n";
import { ReplayPanel } from "./_components/replay-panel";
import { StreamMessagesPanel } from "./_components/stream-messages";
function fmtTime(ts: string) {
return new Date(ts).toLocaleString("zh-CN", {
return new Date(ts).toLocaleString(intlLocale, {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
@@ -258,12 +259,12 @@ export default function TrafficPage() {
// "Purge" for the unfiltered purge, "Delete" for the host-scoped ones — the dialog's
// title and its confirm button both follow from which is in play.
const deleteVerb = deleteMode === "all" ? "Purge" : "Delete";
const purging = deleteMode === "all";
const deleteTitle = deleteMode
? {
all: "Purge all traffic records?",
selected: `Delete all traffic for the ${selectedHosts.length} selected targets?`,
filter: "Delete all traffic for this target?",
all: t("Purge all traffic records?"),
selected: t("Delete all traffic for the {count} selected targets?", { count: selectedHosts.length }),
filter: t("Delete all traffic for this target?"),
}[deleteMode]
: "";
@@ -291,15 +292,21 @@ export default function TrafficPage() {
if (mode === "all") {
// Reclaimed space is the whole point of compacting an emptied index, so say so.
const reclaimed = r.reclaimed ?? 0;
const freed = reclaimed > 0 ? `, freeing ${fmtBytes(reclaimed)} of storage` : "";
toast.success(`Purged ${r.deleted} traffic records${freed}`);
toast.success(
reclaimed > 0
? t("Purged {count} traffic records, freeing {size} of storage", {
count: r.deleted,
size: fmtBytes(reclaimed),
})
: t("Purged {count} traffic records", { count: r.deleted }),
);
}
setPage(0);
setReloadTick((t) => t + 1);
})
.catch((e) => {
// Keep the confirmation open so the user can retry a failed deletion.
if (mode === "all") toast.error(`Purge failed: ${(e as Error).message}`);
if (mode === "all") toast.error(t("Purge failed: {error}", { error: (e as Error).message }));
})
.finally(() => setDeleting(false));
};
@@ -323,7 +330,7 @@ export default function TrafficPage() {
if (d.stream_kind === "websocket" || d.stream_kind === "sse") setDetailTab("stream");
})
.catch(() => {
if (alive) setDetail({ req: "(failed to load the messages)", resp: "" });
if (alive) setDetail({ req: t("(failed to load the messages)"), resp: "" });
})
.finally(() => {
if (alive) setDetailLoading(false);
@@ -352,8 +359,8 @@ export default function TrafficPage() {
<div className="flex min-h-0 flex-1 flex-col gap-4">
<div className="flex items-center justify-between gap-4">
<div>
<h1 className="text-xl font-semibold tracking-tight">Traffic</h1>
<p className="text-muted-foreground text-sm">Global recording proxy · all HTTP traffic</p>
<h1 className="text-xl font-semibold tracking-tight">{t("Traffic")}</h1>
<p className="text-muted-foreground text-sm">{t("Global recording proxy · all HTTP traffic")}</p>
</div>
<div className="flex items-center gap-4 text-sm">
<span
@@ -365,11 +372,11 @@ export default function TrafficPage() {
)}
>
<RadioTowerIcon className="size-3.5" />
{traffic?.enabled ? "Recording" : "Disabled"}
{traffic?.enabled ? t("Recording") : t("Disabled")}
</span>
{traffic?.proxy && <span className="font-mono text-xs text-muted-foreground">{traffic.proxy}</span>}
<span className="text-xs text-muted-foreground">
<span className="tabular-nums">{traffic?.count ?? 0}</span> records
<span className="text-xs text-muted-foreground tabular-nums">
{t("{count} records", { count: traffic?.count ?? 0 })}
</span>
</div>
</div>
@@ -380,7 +387,9 @@ export default function TrafficPage() {
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="h-8">
<ListChecksIcon className="size-3.5" />
{selectedHosts.length > 0 ? `Select targets (${selectedHosts.length})` : "Select targets…"}
{selectedHosts.length > 0
? t("Select targets ({count})", { count: selectedHosts.length })
: t("Select targets…")}
</Button>
</PopoverTrigger>
<PopoverContent
@@ -389,7 +398,7 @@ export default function TrafficPage() {
collisionPadding={16}
>
<div className="flex items-center justify-between border-b px-3 py-2">
<span className="text-xs font-medium text-muted-foreground">Batch delete by target</span>
<span className="text-xs font-medium text-muted-foreground">{t("Batch delete by target")}</span>
<div className="flex items-center gap-1">
{hosts.length > 0 && (
<Tooltip>
@@ -400,14 +409,18 @@ export default function TrafficPage() {
onClick={() => setHostCountSortDirection((current) => (current === "desc" ? "asc" : "desc"))}
aria-label={
hostCountSortDirection === "desc"
? "Packet count is currently descending; click to switch to ascending"
: "Packet count is currently ascending; click to switch to descending"
? t("Packet count is currently descending; click to switch to ascending")
: t("Packet count is currently ascending; click to switch to descending")
}
>
{hostCountSortDirection === "desc" ? <ArrowDownWideNarrowIcon /> : <ArrowUpNarrowWideIcon />}
</Button>
</TooltipTrigger>
<TooltipContent>By packet count, {hostCountSortDirection === "desc" ? "descending" : "ascending"}</TooltipContent>
<TooltipContent>
{hostCountSortDirection === "desc"
? t("By packet count, descending")
: t("By packet count, ascending")}
</TooltipContent>
</Tooltip>
)}
{hosts.length > 0 && (
@@ -417,14 +430,14 @@ export default function TrafficPage() {
className="h-6 px-2 text-xs"
onClick={() => setSelectedHosts(allSelected ? [] : hosts.map((h) => h.host))}
>
{allSelected ? "Clear all" : "Select all"}
{allSelected ? t("Clear all") : t("Select all")}
</Button>
)}
</div>
</div>
<div className="max-h-64 overflow-y-auto">
{hosts.length === 0 ? (
<div className="px-3 py-6 text-center text-xs text-muted-foreground">No traffic records</div>
<div className="px-3 py-6 text-center text-xs text-muted-foreground">{t("No traffic records")}</div>
) : (
sortedHosts.map((h, index) => (
<label
@@ -458,7 +471,7 @@ export default function TrafficPage() {
setPickerOpen(false);
}}
>
Delete selected ({selectedHosts.length})
{t("Delete selected ({count})", { count: selectedHosts.length })}
</Button>
</div>
</PopoverContent>
@@ -471,11 +484,11 @@ export default function TrafficPage() {
size="sm"
className="h-8"
disabled={!hostQ || deleting}
title={hostQ ? undefined : "Select a target on the left or enter a host first"}
title={hostQ ? undefined : t("Select a target on the left or enter a host first")}
onClick={() => setDeleteMode("filter")}
>
<Trash2Icon className="size-3.5" />
Delete this target
{t("Delete this target")}
</Button>
{/* Outline rather than a second destructive button: this one ignores every
filter, so it must not look one mis-click away from "Delete this target". */}
@@ -484,16 +497,16 @@ export default function TrafficPage() {
size="sm"
className="h-8 text-destructive hover:bg-destructive/10 hover:text-destructive"
disabled={!traffic?.count || deleting}
title={traffic?.count ? "Delete all traffic and compact storage" : "No traffic records yet"}
title={traffic?.count ? t("Delete all traffic and compact storage") : t("No traffic records yet")}
onClick={() => setDeleteMode("all")}
>
<EraserIcon className="size-3.5" />
Purge all
{t("Purge all")}
</Button>
<div className="relative max-w-sm flex-1">
<SearchIcon className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search everything (URL / method / type / status…)"
placeholder={t("Search everything (URL / method / type / status…)")}
value={query}
onChange={(e) => setQuery(e.target.value)}
className="h-8 pl-8"
@@ -501,10 +514,10 @@ export default function TrafficPage() {
</div>
<Select value={method} onValueChange={setMethod}>
<SelectTrigger size="sm" className="w-32">
<SelectValue placeholder="Method" />
<SelectValue placeholder={t("Method")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All methods</SelectItem>
<SelectItem value="all">{t("All methods")}</SelectItem>
{METHODS.map((m) => (
<SelectItem key={m} value={m}>
{m}
@@ -519,7 +532,7 @@ export default function TrafficPage() {
<SelectContent>
{PAGE_SIZES.map((n) => (
<SelectItem key={n} value={String(n)}>
{n} / page
{t("{count} / page", { count: n })}
</SelectItem>
))}
</SelectContent>
@@ -555,10 +568,10 @@ export default function TrafficPage() {
{/* Advanced filters (issue #177): narrow 660k+ exchanges down to the one packet. */}
<div className="flex flex-wrap items-center gap-2 rounded-md border bg-muted/30 px-2 py-1.5">
<span className="pl-1 text-xs font-medium text-muted-foreground">Advanced filters</span>
<span className="pl-1 text-xs font-medium text-muted-foreground">{t("Advanced filters")}</span>
<div className="relative w-56">
<Input
placeholder="Response content (body keyword, ≥3 chars)"
placeholder={t("Response content (body keyword, ≥3 chars)")}
value={body}
onChange={(e) => setBody(e.target.value)}
className="h-8"
@@ -566,7 +579,7 @@ export default function TrafficPage() {
</div>
<div className="relative w-52">
<Input
placeholder="Path (e.g. /api/user/…)"
placeholder={t("Path (e.g. /api/user/…)")}
value={path}
onChange={(e) => setPath(e.target.value)}
className="h-8"
@@ -574,10 +587,10 @@ export default function TrafficPage() {
</div>
<Select value={statusFilter} onValueChange={setStatusFilter}>
<SelectTrigger size="sm" className="w-28">
<SelectValue placeholder="Status" />
<SelectValue placeholder={t("Status")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All statuses</SelectItem>
<SelectItem value="all">{t("All statuses")}</SelectItem>
{STATUS_BUCKETS.map((s) => (
<SelectItem key={s} value={s}>
{s}
@@ -586,11 +599,11 @@ export default function TrafficPage() {
</SelectContent>
</Select>
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<span>Response size</span>
<span>{t("Response size")}</span>
<Input
type="number"
min={0}
placeholder="Min (B)"
placeholder={t("Min (B)")}
value={respMin}
onChange={(e) => setRespMin(e.target.value)}
className="h-8 w-24"
@@ -599,7 +612,7 @@ export default function TrafficPage() {
<Input
type="number"
min={0}
placeholder="Max (B)"
placeholder={t("Max (B)")}
value={respMax}
onChange={(e) => setRespMax(e.target.value)}
className="h-8 w-24"
@@ -608,19 +621,21 @@ export default function TrafficPage() {
{hasAdvancedFilter ? (
<Button variant="ghost" size="sm" className="h-8" onClick={resetAdvancedFilters}>
<FilterXIcon className="size-3.5" />
Clear filters
{t("Clear filters")}
</Button>
) : null}
</div>
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm text-muted-foreground">{selectedFlows.size} flows selected</span>
<span className="text-sm text-muted-foreground">
{t("{count} flows selected", { count: selectedFlows.size })}
</span>
<Button variant="outline" size="sm" disabled={selectedFlows.size === 0} onClick={() => setLinking(true)}>
Link to finding
{t("Link to finding")}
</Button>
{selectedFlows.size > 0 ? (
<Button variant="ghost" size="sm" onClick={() => setSelectedFlows(new Set())}>
Clear selection
{t("Clear selection")}
</Button>
) : null}
</div>
@@ -633,7 +648,7 @@ export default function TrafficPage() {
<TableRow>
<TableHead className="w-10">
<Checkbox
aria-label="Select this page's traffic"
aria-label={t("Select this page's traffic")}
checked={exchanges.length > 0 && exchanges.every((e) => selectedFlows.has(e.id))}
onCheckedChange={(checked) =>
setSelectedFlows((previous) => {
@@ -649,18 +664,18 @@ export default function TrafficPage() {
</TableHead>
<SortableHead
field="ts"
label="Time"
label={t("Time")}
activeField={sort.field}
direction={sort.direction}
onSort={toggleSort}
className="w-36"
/>
<TableHead className="w-44">host</TableHead>
<TableHead className="w-20">Method</TableHead>
<TableHead className="w-20">{t("Method")}</TableHead>
<TableHead>URL</TableHead>
<SortableHead
field="status"
label="Status"
label={t("Status")}
activeField={sort.field}
direction={sort.direction}
onSort={toggleSort}
@@ -669,7 +684,7 @@ export default function TrafficPage() {
<TableHead className="w-36">content-type</TableHead>
<SortableHead
field="resp_len"
label="Response size"
label={t("Response size")}
activeField={sort.field}
direction={sort.direction}
onSort={toggleSort}
@@ -687,7 +702,7 @@ export default function TrafficPage() {
>
<TableCell>
<Checkbox
aria-label={`Select traffic ${e.id}`}
aria-label={t("Select traffic {id}", { id: e.id })}
checked={selectedFlows.has(e.id)}
onClick={(event) => event.stopPropagation()}
onCheckedChange={(checked) =>
@@ -720,7 +735,7 @@ export default function TrafficPage() {
{exchanges.length === 0 && (
<TableRow>
<TableCell colSpan={8} className="py-12 text-center text-sm text-muted-foreground">
{traffic === null ? "Loading…" : "No matching traffic."}
{traffic === null ? t("Loading…") : t("No matching traffic.")}
</TableCell>
</TableRow>
)}
@@ -754,31 +769,31 @@ export default function TrafficPage() {
</SheetHeader>
<Tabs value={detailTab} onValueChange={setDetailTab} className="min-h-0 flex-1 gap-0">
<TabsList className={cn("mx-5 mt-4 grid w-auto", hasStream ? "grid-cols-4" : "grid-cols-3")}>
<TabsTrigger value="request">Request</TabsTrigger>
<TabsTrigger value="response">Response</TabsTrigger>
<TabsTrigger value="request">{t("Request")}</TabsTrigger>
<TabsTrigger value="response">{t("Response")}</TabsTrigger>
{hasStream && (
<TabsTrigger value="stream">
Stream
{t("Stream")}
{(detail?.stream_count ?? 0) > 0 && (
<span className="text-muted-foreground text-xs tabular-nums">{detail?.stream_count}</span>
)}
</TabsTrigger>
)}
{hasStream ? (
<span title="stream replay is not supported" className="flex">
<span title={t("stream replay is not supported")} className="flex">
<TabsTrigger value="replay" disabled>
Replay
{t("Replay")}
</TabsTrigger>
</span>
) : (
<TabsTrigger value="replay">Replay</TabsTrigger>
<TabsTrigger value="replay">{t("Replay")}</TabsTrigger>
)}
</TabsList>
<TabsContent value="request" className="min-h-0 overflow-auto">
{detailLoading ? (
<div className="flex items-center gap-2 p-5 text-xs text-muted-foreground">
<Loader2Icon className="size-3.5 animate-spin" />
Loading messages…
{t("Loading messages…")}
</div>
) : (
<HttpCodeBlock raw={requestWithHost(detail?.req ?? "", selected)} />
@@ -788,7 +803,7 @@ export default function TrafficPage() {
{detailLoading ? (
<div className="flex items-center gap-2 p-5 text-xs text-muted-foreground">
<Loader2Icon className="size-3.5 animate-spin" />
Loading messages…
{t("Loading messages…")}
</div>
) : (
<HttpCodeBlock raw={detail?.resp ?? ""} />
@@ -805,7 +820,7 @@ export default function TrafficPage() {
{detailLoading || !detail ? (
<div className="flex items-center gap-2 p-5 text-muted-foreground text-xs">
<Loader2Icon className="size-3.5 animate-spin" />
Loading…
{t("Loading…")}
</div>
) : (
<ReplayPanel
@@ -835,34 +850,41 @@ export default function TrafficPage() {
<AlertDialogDescription>
{deleteMode === "all" && (
<>
This will permanently delete all <span className="font-semibold tabular-nums">{traffic?.count ?? 0}</span>{" "}
traffic records (including raw requests/responses), ignoring the current filters. This action cannot be undone. Traffic evidence already bound to findings lives in a separate evidence store and is unaffected.
{t(
"This will permanently delete all {count} traffic records (including raw requests/responses), ignoring the current filters. This action cannot be undone. Traffic evidence already bound to findings lives in a separate evidence store and is unaffected.",
{ count: traffic?.count ?? 0 },
)}
<br />
<span className="text-muted-foreground">
Purging also compacts storage, returning the index's disk space to the system; traffic recording pauses briefly during this time.
{t(
"Purging also compacts storage, returning the index's disk space to the system; traffic recording pauses briefly during this time.",
)}
</span>
</>
)}
{deleteMode === "selected" && (
<>
This will permanently delete all traffic records for <span className="font-semibold tabular-nums">{selectedHosts.length}</span> targets (
<span className="font-mono">
{selectedHosts.slice(0, 3).join(", ")}
{selectedHosts.length > 3 ? "…" : ""}
</span>
), including raw requests/responses. This action cannot be undone.
{t(
"This will permanently delete all traffic records for {count} targets ({hosts}), including raw requests/responses. This action cannot be undone.",
{
count: selectedHosts.length,
hosts: `${selectedHosts.slice(0, 3).join(", ")}${selectedHosts.length > 3 ? "…" : ""}`,
},
)}
</>
)}
{deleteMode === "filter" && (
<>
This will permanently delete all traffic records for hosts containing <span className="font-mono font-semibold">{hostQ}</span>{" "}
(including raw requests/responses). This action cannot be undone.
{t(
"This will permanently delete all traffic records for hosts containing {host} (including raw requests/responses). This action cannot be undone.",
{ host: hostQ },
)}
</>
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
<AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault();
@@ -871,7 +893,13 @@ export default function TrafficPage() {
disabled={deleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{deleting ? `${deleteVerb}…` : `Confirm ${deleteVerb}`}
{deleting
? purging
? t("Purging…")
: t("Deleting…")
: purging
? t("Confirm purge")
: t("Confirm delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
+47 -33
View File
@@ -43,6 +43,7 @@ import {
import { cn } from "@/lib/utils";
import { api } from "@/lib/api";
import type { WorkspaceEntry, WorkspaceFile } from "@/lib/types";
import { intlLocale, t } from "@/i18n";
function fmtSize(n: number): string {
if (n < 1024) return `${n} B`;
@@ -51,7 +52,7 @@ function fmtSize(n: number): string {
return `${(n / 1024 / 1024 / 1024).toFixed(1)} GB`;
}
function fmtTime(ms: number): string {
return new Date(ms).toLocaleString("zh-CN", {
return new Date(ms).toLocaleString(intlLocale, {
year: "2-digit",
month: "2-digit",
day: "2-digit",
@@ -85,7 +86,7 @@ export default function WorkspacePage() {
setEntries(r.entries);
setPath(r.path);
})
.catch((e) => toast.error(`Failed to read directory: ${(e as Error).message}`))
.catch((e) => toast.error(t("Failed to read directory: {error}", { error: (e as Error).message })))
.finally(() => setLoading(false));
},
[],
@@ -97,7 +98,7 @@ export default function WorkspacePage() {
const crumbs = React.useMemo(() => {
const parts = path ? path.split("/") : [];
const acc: { name: string; path: string }[] = [{ name: "Workspace", path: "" }];
const acc: { name: string; path: string }[] = [{ name: t("Workspace"), path: "" }];
let cur = "";
for (const part of parts) {
cur = cur ? `${cur}/${part}` : part;
@@ -110,7 +111,7 @@ export default function WorkspacePage() {
api
.workspaceRead(e.path)
.then((f) => setEdit({ file: f, content: f.content ?? "", dirty: false, saving: false }))
.catch((err) => toast.error(`Failed to open file: ${(err as Error).message}`));
.catch((err) => toast.error(t("Failed to open file: {error}", { error: (err as Error).message })));
};
const saveFile = () => {
@@ -119,25 +120,28 @@ export default function WorkspacePage() {
api
.workspaceWrite(edit.file.path, edit.content)
.then(() => {
toast.success("Saved");
toast.success(t("Saved"));
setEdit((cur) => (cur ? { ...cur, dirty: false, saving: false } : cur));
load(path);
})
.catch((err) => {
toast.error(`Save failed: ${(err as Error).message}`);
toast.error(t("Save failed: {error}", { error: (err as Error).message }));
setEdit((cur) => (cur ? { ...cur, saving: false } : cur));
});
};
const del = (e: WorkspaceEntry) => {
if (!window.confirm(`Confirm deleting ${e.dir ? "directory" : "file"} "${e.name}"?${e.dir ? " (including everything inside)" : ""}`)) return;
const question = e.dir
? t('Confirm deleting directory "{name}"? (including everything inside)', { name: e.name })
: t('Confirm deleting file "{name}"?', { name: e.name });
if (!window.confirm(question)) return;
api
.workspaceDelete(e.path)
.then(() => {
toast.success("Deleted");
toast.success(t("Deleted"));
load(path);
})
.catch((err) => toast.error(`Delete failed: ${(err as Error).message}`));
.catch((err) => toast.error(t("Delete failed: {error}", { error: (err as Error).message })));
};
const doUpload = (files: FileList | null) => {
@@ -145,10 +149,10 @@ export default function WorkspacePage() {
api
.workspaceUpload(path, Array.from(files))
.then((r) => {
toast.success(`Uploaded ${r.uploaded} files`);
toast.success(t("Uploaded {count} files", { count: r.uploaded }));
load(path);
})
.catch((err) => toast.error(`Upload failed: ${(err as Error).message}`))
.catch((err) => toast.error(t("Upload failed: {error}", { error: (err as Error).message })))
.finally(() => {
if (uploadRef.current) uploadRef.current.value = "";
});
@@ -161,12 +165,12 @@ export default function WorkspacePage() {
api
.workspaceMkdir(target)
.then(() => {
toast.success("Directory created");
toast.success(t("Directory created"));
setMkdirOpen(false);
setMkdirName("");
load(path);
})
.catch((err) => toast.error(`Create failed: ${(err as Error).message}`));
.catch((err) => toast.error(t("Create failed: {error}", { error: (err as Error).message })));
};
return (
@@ -193,12 +197,12 @@ export default function WorkspacePage() {
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={() => setMkdirOpen(true)}>
<FolderPlusIcon /> New folder
<FolderPlusIcon /> {t("New folder")}
</Button>
<Button variant="outline" size="sm" onClick={() => uploadRef.current?.click()}>
<UploadIcon /> Upload
<UploadIcon /> {t("Upload")}
</Button>
<Button variant="ghost" size="icon" className="size-8" onClick={() => load(path)} title="Refresh">
<Button variant="ghost" size="icon" className="size-8" onClick={() => load(path)} title={t("Refresh")}>
<RefreshCwIcon className={cn("size-4", loading && "animate-spin")} />
</Button>
<input
@@ -216,17 +220,17 @@ export default function WorkspacePage() {
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead className="w-28 text-right">Size</TableHead>
<TableHead className="w-40">Modified</TableHead>
<TableHead className="w-24 text-right">Actions</TableHead>
<TableHead>{t("Name")}</TableHead>
<TableHead className="w-28 text-right">{t("Size")}</TableHead>
<TableHead className="w-40">{t("Modified")}</TableHead>
<TableHead className="w-24 text-right">{t("Actions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{entries.length === 0 && (
<TableRow>
<TableCell colSpan={4} className="text-muted-foreground py-10 text-center text-sm">
{loading ? "Loading…" : "Empty directory"}
{loading ? t("Loading…") : t("Empty directory")}
</TableCell>
</TableRow>
)}
@@ -257,8 +261,14 @@ export default function WorkspacePage() {
variant="ghost"
size="icon"
className="size-7"
title="Download"
onClick={() => api.workspaceDownload(e.path).catch((err) => toast.error(`Download failed: ${(err as Error).message}`))}
title={t("Download")}
onClick={() =>
api
.workspaceDownload(e.path)
.catch((err) =>
toast.error(t("Download failed: {error}", { error: (err as Error).message })),
)
}
>
<DownloadIcon className="size-3.5" />
</Button>
@@ -267,7 +277,7 @@ export default function WorkspacePage() {
variant="ghost"
size="icon"
className="text-destructive size-7"
title="Delete"
title={t("Delete")}
onClick={() => del(e)}
>
<Trash2Icon className="size-3.5" />
@@ -299,10 +309,12 @@ export default function WorkspacePage() {
{edit.file.binary || edit.file.too_large ? (
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-8 text-center">
<p className="text-muted-foreground text-sm">
{edit.file.too_large ? "File too large for online preview/editing." : "Binary file; online preview/editing is not supported."}
{edit.file.too_large
? t("File too large for online preview/editing.")
: t("Binary file; online preview/editing is not supported.")}
</p>
<Button variant="outline" onClick={() => api.workspaceDownload(edit.file.path)}>
<DownloadIcon /> Download file
<DownloadIcon /> {t("Download file")}
</Button>
</div>
) : (
@@ -316,16 +328,18 @@ export default function WorkspacePage() {
/>
</div>
<SheetFooter className="flex-row items-center justify-between border-t p-3">
<span className="text-muted-foreground text-xs">{edit.dirty ? "Unsaved changes" : "In sync"}</span>
<span className="text-muted-foreground text-xs">
{edit.dirty ? t("Unsaved changes") : t("In sync")}
</span>
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => api.workspaceDownload(edit.file.path)}
>
<DownloadIcon /> Download
<DownloadIcon /> {t("Download")}
</Button>
<Button onClick={saveFile} disabled={!edit.dirty || edit.saving}>
<SaveIcon /> {edit.saving ? "Saving…" : "Save"}
<SaveIcon /> {edit.saving ? t("Saving…") : t("Save")}
</Button>
</div>
</SheetFooter>
@@ -340,21 +354,21 @@ export default function WorkspacePage() {
<Dialog open={mkdirOpen} onOpenChange={setMkdirOpen}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>New folder</DialogTitle>
<DialogTitle>{t("New folder")}</DialogTitle>
</DialogHeader>
<Input
autoFocus
value={mkdirName}
onChange={(e) => setMkdirName(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && doMkdir()}
placeholder="Folder name"
placeholder={t("Folder name")}
/>
<DialogFooter>
<Button variant="outline" onClick={() => setMkdirOpen(false)}>
Cancel
{t("Cancel")}
</Button>
<Button onClick={doMkdir} disabled={!mkdirName.trim()}>
Create
{t("Create")}
</Button>
</DialogFooter>
</DialogContent>
@@ -9,6 +9,7 @@ import { ArrowLeftIcon } from "lucide-react";
import { AgentEditor } from "@/components/agent-editor";
import { Button } from "@/components/ui/button";
import { t } from "@/i18n";
// Deep-link editor page for one agent. The primary flow is the drawer on
// /system/agents; this page reuses the same AgentEditor component full-width so a
@@ -21,12 +22,12 @@ function AgentDetailInner() {
<div className="flex flex-1 flex-col gap-4">
<div className="flex items-center gap-2">
<Button asChild variant="ghost" size="icon-sm">
<Link href="/system/agents">
<Link href="/system/agents" aria-label={t("Back")}>
<ArrowLeftIcon className="size-4" />
</Link>
</Button>
<div>
<h1 className="text-xl font-semibold tracking-tight">Agent</h1>
<h1 className="text-xl font-semibold tracking-tight">{t("Agent")}</h1>
<p className="text-muted-foreground font-mono text-xs">{key}</p>
</div>
</div>
+40 -32
View File
@@ -38,6 +38,7 @@ import {
} from "@/components/ui/alert-dialog";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { AgentEditor } from "@/components/agent-editor";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { Agent } from "@/lib/types";
@@ -55,10 +56,10 @@ function AgentGridCard({
async function del() {
try {
await api.deleteAgent(agent.key);
toast.success(`Agent "${agent.name}" deleted`);
toast.success(t('Agent "{name}" deleted', { name: agent.name }));
onDeleted();
} catch (e) {
toast.error("Delete failed: " + (e as Error).message);
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
}
}
return (
@@ -70,26 +71,26 @@ function AgentGridCard({
<span className="text-muted-foreground font-mono text-xs">{agent.key}</span>
{agent.builtin ? (
<Badge variant="secondary" className="px-1.5 py-0 text-[10px]">
Built-in
{t("Built-in")}
</Badge>
) : (
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
Custom
{t("Custom")}
</Badge>
)}
{!agent.enabled && (
<Badge variant="outline" className="text-destructive px-1.5 py-0 text-[10px]">
Disabled
{t("Disabled")}
</Badge>
)}
</div>
<p className="text-muted-foreground line-clamp-2 min-h-8 text-xs">
{agent.description || "(no description)"}
{agent.description || t("(no description)")}
</p>
<div className="text-muted-foreground flex flex-wrap gap-1.5 text-[10px]">
<span className="rounded border px-1.5 py-0.5">MCP {agent.mcp_count ?? 0}</span>
<span className="rounded border px-1.5 py-0.5">Skill {agent.skill_count ?? 0}</span>
<span className="rounded border px-1.5 py-0.5">Tools {agent.tool_count ?? 0}</span>
<span className="rounded border px-1.5 py-0.5">{t("Skill {count}", { count: agent.skill_count ?? 0 })}</span>
<span className="rounded border px-1.5 py-0.5">{t("Tools {count}", { count: agent.tool_count ?? 0 })}</span>
</div>
</button>
{!agent.builtin && (
@@ -99,20 +100,21 @@ function AgentGridCard({
variant="ghost"
size="icon-sm"
className="text-muted-foreground hover:text-destructive absolute top-2 right-2 opacity-0 transition-opacity group-hover:opacity-100"
aria-label={t("Delete agent")}
>
<Trash2Icon className="size-3.5" />
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete agent "{agent.name}"?</AlertDialogTitle>
<AlertDialogTitle>{t('Delete agent "{name}"?', { name: agent.name })}</AlertDialogTitle>
<AlertDialogDescription>
This also deletes its prompt, variables, visibility and tool bindings. This action cannot be undone.
{t("This also deletes its prompt, variables, visibility and tool bindings. This action cannot be undone.")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={del}>Delete</AlertDialogAction>
<AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={del}>{t("Delete")}</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
@@ -132,14 +134,14 @@ function CreateAgentDialog({ onCreated }: { onCreated: (key: string) => void })
setBusy(true);
try {
const a = await api.createAgent(key.trim(), name.trim(), description.trim());
toast.success(`Agent "${a.name}" created`);
toast.success(t('Agent "{name}" created', { name: a.name }));
setOpen(false);
setKey("");
setName("");
setDescription("");
onCreated(a.key);
} catch (e) {
toast.error("Create failed: " + (e as Error).message);
toast.error(t("Create failed: {error}", { error: (e as Error).message }));
} finally {
setBusy(false);
}
@@ -152,44 +154,48 @@ function CreateAgentDialog({ onCreated }: { onCreated: (key: string) => void })
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button size="sm">
<PlusIcon /> Create agent
<PlusIcon /> {t("Create agent")}
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Create custom agent</DialogTitle>
<DialogTitle>{t("Create custom agent")}</DialogTitle>
<DialogDescription>
Create a conversational assistant. The key is the internal identifier and cannot change after creation; the name and description are for identification.
{t(
"Create a conversational assistant. The key is the internal identifier and cannot change after creation; the name and description are for identification.",
)}
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-2">
<div className="grid gap-1.5">
<Label htmlFor="agent-key">Key</Label>
<Label htmlFor="agent-key">{t("Key")}</Label>
<Input
id="agent-key"
placeholder="e.g. research_helper"
placeholder={t("e.g. research_helper")}
value={key}
onChange={(e) => setKey(e.target.value)}
className="font-mono"
/>
{key.length > 0 && !keyOk && (
<span className="text-destructive text-xs">Must start with a lowercase letter; only lowercase letters/digits/underscores</span>
<span className="text-destructive text-xs">
{t("Must start with a lowercase letter; only lowercase letters/digits/underscores")}
</span>
)}
</div>
<div className="grid gap-1.5">
<Label htmlFor="agent-name">Name</Label>
<Label htmlFor="agent-name">{t("Name")}</Label>
<Input
id="agent-name"
placeholder="e.g. Research assistant"
placeholder={t("e.g. Research assistant")}
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="grid gap-1.5">
<Label htmlFor="agent-desc">Description</Label>
<Label htmlFor="agent-desc">{t("Description")}</Label>
<Textarea
id="agent-desc"
placeholder="One line on what this agent does"
placeholder={t("One line on what this agent does")}
rows={2}
value={description}
onChange={(e) => setDescription(e.target.value)}
@@ -198,7 +204,7 @@ function CreateAgentDialog({ onCreated }: { onCreated: (key: string) => void })
</div>
<DialogFooter>
<Button onClick={create} disabled={!canCreate}>
Create
{t("Create")}
</Button>
</DialogFooter>
</DialogContent>
@@ -223,9 +229,9 @@ export default function AgentsPage() {
<div className="flex flex-1 flex-col gap-4 md:gap-6">
<div className="flex items-start justify-between gap-3">
<div>
<h1 className="text-xl font-semibold tracking-tight">Agent</h1>
<h1 className="text-xl font-semibold tracking-tight">{t("Agent")}</h1>
<p className="text-muted-foreground text-sm">
Prompts/configs for built-in agents, plus creating and managing custom conversational agents
{t("Prompts/configs for built-in agents, plus creating and managing custom conversational agents")}
</p>
</div>
<CreateAgentDialog
@@ -238,12 +244,12 @@ export default function AgentsPage() {
<Card>
<CardHeader>
<CardTitle>Agent list</CardTitle>
<CardDescription>{agents.length} total</CardDescription>
<CardTitle>{t("Agent list")}</CardTitle>
<CardDescription>{t("{count} total", { count: agents.length })}</CardDescription>
</CardHeader>
<CardContent>
{agents.length === 0 ? (
<p className="text-muted-foreground py-6 text-center text-sm">(no agents)</p>
<p className="text-muted-foreground py-6 text-center text-sm">{t("(no agents)")}</p>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{agents.map((a) => (
@@ -267,11 +273,13 @@ export default function AgentsPage() {
<span className="text-muted-foreground font-mono text-xs">{editing.key}</span>
{!editing.builtin && (
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
Custom
{t("Custom")}
</Badge>
)}
</SheetTitle>
<SheetDescription>{editing.description || "Prompt, config, visible resources and tool bindings"}</SheetDescription>
<SheetDescription>
{editing.description || t("Prompt, config, visible resources and tool bindings")}
</SheetDescription>
</SheetHeader>
<AgentEditor agentKey={editing.key} onSaved={reload} />
</>
@@ -16,19 +16,20 @@ import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetT
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { AssetInterceptKind, AssetInterceptRule } from "@/lib/types";
// ---- kind metadata ----
const KIND_OPTIONS: { value: AssetInterceptKind; label: string; group: string; placeholder: string }[] = [
{ value: "exact_domain", label: "Domain (exact)", group: "Exact match", placeholder: "example.gov.cn" },
{ value: "exact_ip", label: "IP (exact)", group: "Exact match", placeholder: "203.0.113.10" },
{ value: "exact_url", label: "URL (exact)", group: "Exact match", placeholder: "https://example.gov.cn/login" },
{ value: "fuzzy_domain", label: "Domain (fuzzy)", group: "Fuzzy match", placeholder: ".gov.cn" },
{ value: "fuzzy_ip", label: "IP (fuzzy)", group: "Fuzzy match", placeholder: "203.0.113." },
{ value: "fuzzy_url", label: "URL (fuzzy)", group: "Fuzzy match", placeholder: "/admin" },
{ value: "cidr", label: "CIDR network", group: "CIDR", placeholder: "192.168.0.0/16" },
{ value: "exact_domain", label: t("Domain (exact)"), group: "Exact match", placeholder: "example.gov.cn" },
{ value: "exact_ip", label: t("IP (exact)"), group: "Exact match", placeholder: "203.0.113.10" },
{ value: "exact_url", label: t("URL (exact)"), group: "Exact match", placeholder: "https://example.gov.cn/login" },
{ value: "fuzzy_domain", label: t("Domain (fuzzy)"), group: "Fuzzy match", placeholder: ".gov.cn" },
{ value: "fuzzy_ip", label: t("IP (fuzzy)"), group: "Fuzzy match", placeholder: "203.0.113." },
{ value: "fuzzy_url", label: t("URL (fuzzy)"), group: "Fuzzy match", placeholder: "/admin" },
{ value: "cidr", label: t("CIDR network"), group: "CIDR", placeholder: "192.168.0.0/16" },
];
const KIND_LABEL: Record<AssetInterceptKind, string> = Object.fromEntries(
@@ -80,9 +81,9 @@ const defaultForm = (): RuleForm => ({ enabled: true, kind: "fuzzy_domain", patt
// Light frontend validation (matching the backend: only exact_ip / cidr get format checks, the rest is left to the backend).
function frontValidate(form: RuleForm): string | null {
const p = form.pattern.trim();
if (!p) return "Match content cannot be empty";
if (!p) return t("Match content cannot be empty");
if (form.kind === "cidr" && !/^[0-9a-fA-F:.]+\/\d{1,3}$/.test(p)) {
return "Invalid CIDR format, e.g. 192.168.0.0/16";
return t("Invalid CIDR format, e.g. 192.168.0.0/16");
}
return null;
}
@@ -101,7 +102,7 @@ export default function AssetInterceptPage() {
try {
setRules(await api.assetInterceptRules());
} catch {
toast.error("Failed to load asset interception rules");
toast.error(t("Failed to load asset interception rules"));
} finally {
setLoading(false);
}
@@ -138,10 +139,10 @@ export default function AssetInterceptPage() {
try {
if (editing) {
await api.updateAssetInterceptRule(editing.id, payload);
toast.success("Rule updated");
toast.success(t("Rule updated"));
} else {
await api.createAssetInterceptRule(payload);
toast.success("Rule created");
toast.success(t("Rule created"));
}
setOpen(false);
load();
@@ -153,10 +154,10 @@ export default function AssetInterceptPage() {
}
async function handleDelete(rule: AssetInterceptRule) {
if (!window.confirm(`Are you sure you want to delete asset interception rule "${rule.pattern}"?`)) return;
if (!window.confirm(t("Are you sure you want to delete asset interception rule \"{pattern}\"?", { pattern: rule.pattern }))) return;
try {
await api.deleteAssetInterceptRule(rule.id);
toast.success("Rule deleted");
toast.success(t("Rule deleted"));
load();
} catch (e) {
toast.error((e as Error).message);
@@ -180,45 +181,44 @@ export default function AssetInterceptPage() {
<div className="flex items-center gap-2.5">
<BanIcon className="h-5 w-5 shrink-0" />
<div>
<h1 className="text-lg font-semibold leading-tight">Asset interception</h1>
<h1 className="text-lg font-semibold leading-tight">{t("Asset interception")}</h1>
<p className="text-sm text-muted-foreground mt-0.5">
Global asset blocklist: matching domains / IPs / URLs / networks are intercepted; no operations run against them
{t("Global asset blocklist: matching domains / IPs / URLs / networks are intercepted; no operations run against them")}
</p>
</div>
</div>
<div className="flex items-center justify-between gap-3">
<p className="text-xs text-muted-foreground">
Supports exact and fuzzy matching for domains / IPs / URLs, plus CIDR networks; ships with built-in fuzzy blocks for government (.gov / .gov.cn) and education (.edu /
.edu.cn) sites
{t("Supports exact and fuzzy matching for domains / IPs / URLs, plus CIDR networks; ships with built-in fuzzy blocks for government (.gov / .gov.cn) and education (.edu / .edu.cn) sites")}
</p>
<Button onClick={openNew} size="sm" className="shrink-0">
<PlusIcon className="h-4 w-4" />
Create rule
{t("Create rule")}
</Button>
</div>
<Card>
<CardContent className="p-0">
{loading ? (
<p className="p-6 text-sm text-muted-foreground">Loading…</p>
<p className="p-6 text-sm text-muted-foreground">{t("Loading…")}</p>
) : rules.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 py-16 text-center">
<BanIcon className="h-8 w-8 text-muted-foreground/40" />
<p className="text-sm text-muted-foreground">No asset interception rules yet</p>
<p className="text-sm text-muted-foreground">{t("No asset interception rules yet")}</p>
<Button size="sm" variant="outline" onClick={openNew}>
<PlusIcon className="h-4 w-4" />
Create the first rule
{t("Create the first rule")}
</Button>
</div>
) : (
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent">
<TableHead className="w-[130px]">Type</TableHead>
<TableHead>Match content</TableHead>
<TableHead>Note</TableHead>
<TableHead className="w-[64px] text-center">Enabled</TableHead>
<TableHead className="w-[130px]">{t("Type")}</TableHead>
<TableHead>{t("Match content")}</TableHead>
<TableHead>{t("Note")}</TableHead>
<TableHead className="w-[64px] text-center">{t("Enabled")}</TableHead>
<TableHead className="w-[80px]" />
</TableRow>
</TableHeader>
@@ -237,7 +237,7 @@ export default function AssetInterceptPage() {
<div className="flex items-center gap-1.5">
{rule.builtin && (
<Badge variant="secondary" className="shrink-0 px-1 py-0 text-[10px]">
Built-in
{t("Built-in")}
</Badge>
)}
<span className="truncate">{rule.note}</span>
@@ -273,12 +273,12 @@ export default function AssetInterceptPage() {
<Sheet open={open} onOpenChange={setOpen}>
<SheetContent side="right" className="flex flex-col gap-0 p-0 sm:max-w-md">
<SheetHeader className="border-b px-6 py-4">
<SheetTitle>{editing ? "Edit asset interception rule" : "Create asset interception rule"}</SheetTitle>
<SheetDescription className="text-xs">Target assets matching this rule are intercepted globally</SheetDescription>
<SheetTitle>{editing ? t("Edit asset interception rule") : t("Create asset interception rule")}</SheetTitle>
<SheetDescription className="text-xs">{t("Target assets matching this rule are intercepted globally")}</SheetDescription>
</SheetHeader>
<div className="flex-1 min-h-0 overflow-y-auto px-6 py-5 space-y-5">
<Field label="Match type">
<Field label={t("Match type")}>
<Select value={form.kind} onValueChange={(v) => set({ kind: v as AssetInterceptKind })}>
<SelectTrigger>
<SelectValue />
@@ -287,7 +287,7 @@ export default function AssetInterceptPage() {
{KIND_GROUPS.map((g) => (
<React.Fragment key={g}>
<div className="px-2 py-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
{g}
{t(g)}
</div>
{KIND_OPTIONS.filter((o) => o.group === g).map((o) => (
<SelectItem key={o.value} value={o.value}>
@@ -301,13 +301,13 @@ export default function AssetInterceptPage() {
</Field>
<Field
label="Match content"
label={t("Match content")}
hint={
form.kind === "cidr"
? "CIDR network, e.g. 192.168.0.0/16"
? t("CIDR network, e.g. 192.168.0.0/16")
: form.kind.startsWith("fuzzy_")
? "Fuzzy match: hits when the target contains this content"
: "Exact match: the target must equal this content exactly"
? t("Fuzzy match: hits when the target contains this content")
: t("Exact match: the target must equal this content exactly")
}
>
<Input
@@ -317,9 +317,9 @@ export default function AssetInterceptPage() {
/>
</Field>
<Field label="Note (optional)">
<Field label={t("Note (optional)")}>
<Textarea
placeholder="Describe what this rule is for"
placeholder={t("Describe what this rule is for")}
value={form.note}
onChange={(e) => set({ note: e.target.value })}
rows={2}
@@ -332,17 +332,17 @@ export default function AssetInterceptPage() {
<div className="flex items-center gap-3">
<Switch id="asset-rule-enabled" checked={form.enabled} onCheckedChange={(v) => set({ enabled: v })} />
<Label htmlFor="asset-rule-enabled" className="cursor-pointer">
Enable this rule
{t("Enable this rule")}
</Label>
</div>
</div>
<SheetFooter className="border-t px-6 py-4 flex-row justify-end gap-2">
<Button variant="outline" onClick={() => setOpen(false)}>
Cancel
{t("Cancel")}
</Button>
<Button onClick={handleSave} disabled={saving}>
{saving ? "Saving…" : "Save"}
{saving ? t("Saving…") : t("Save")}
</Button>
</SheetFooter>
</SheetContent>
+167 -143
View File
@@ -50,6 +50,7 @@ import {
} from "@/components/ui/table";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { intlLocale, t } from "@/i18n";
import { api } from "@/lib/api";
import type {
InterceptAction,
@@ -68,6 +69,17 @@ function fmtTokens(n: number): string {
return String(n);
}
// tRich translates a sentence whose {placeholders} are rendered as React nodes (e.g. emphasised spans or code).
function tRich(key: string, nodes: Record<string, React.ReactNode>): React.ReactNode[] {
return t(key)
.split(/(\{\w+\})/)
.map((part, i) => {
const name = /^\{(\w+)\}$/.exec(part)?.[1];
// biome-ignore lint/suspicious/noArrayIndexKey: static sentence fragments
return name && name in nodes ? <React.Fragment key={i}>{nodes[name]}</React.Fragment> : part;
});
}
// JudgeStat is one stat tile (label + value).
function JudgeStat({ label, value }: { label: string; value: string }) {
return (
@@ -89,7 +101,7 @@ function JudgeSparkbars({ daily }: { daily: JudgeDayUsage[] }) {
return (
<div
key={d.date}
title={`${d.date} · ${d.calls} calls · ${fmtTokens(total)} tokens`}
title={t("{date} · {calls} calls · {tokens} tokens", { date: d.date, calls: d.calls, tokens: fmtTokens(total) })}
className="min-w-[2px] flex-1 rounded-sm bg-violet-500/60 hover:bg-violet-500"
style={{ height: `${h}%` }}
/>
@@ -109,36 +121,36 @@ function sdkTool(key: string, description: string): Tool {
}
const SDK_EXEC: Tool[] = [
sdkTool("Bash", "Execute commands in a shell"),
sdkTool("WebFetch", "Make HTTP/HTTPS requests (with proxy support)"),
sdkTool("web_search", "Web search"),
sdkTool("shell_open", "Open a persistent PTY interactive session"),
sdkTool("shell_send", "Send input to an interactive session"),
sdkTool("shell_read", "Read output from an interactive session"),
sdkTool("shell_close", "Close an interactive session"),
sdkTool("shell_list", "List all interactive sessions"),
sdkTool("Bash", t("Execute commands in a shell")),
sdkTool("WebFetch", t("Make HTTP/HTTPS requests (with proxy support)")),
sdkTool("web_search", t("Web search")),
sdkTool("shell_open", t("Open a persistent PTY interactive session")),
sdkTool("shell_send", t("Send input to an interactive session")),
sdkTool("shell_read", t("Read output from an interactive session")),
sdkTool("shell_close", t("Close an interactive session")),
sdkTool("shell_list", t("List all interactive sessions")),
];
const SDK_WRITE: Tool[] = [
sdkTool("Write", "Write files"),
sdkTool("Edit", "Edit files (exact replacement)"),
sdkTool("MultiEdit", "Edit files in batch"),
sdkTool("Write", t("Write files")),
sdkTool("Edit", t("Edit files (exact replacement)")),
sdkTool("MultiEdit", t("Edit files in batch")),
];
const SDK_KEYS = new Set([...SDK_EXEC, ...SDK_WRITE].map((t) => t.key));
const SDK_KEYS = new Set([...SDK_EXEC, ...SDK_WRITE].map((tool) => tool.key));
function groupTools(dbTools: Tool[]) {
const sys: Tool[] = [], custom: Tool[] = [];
for (const t of dbTools) {
if (SDK_KEYS.has(t.key)) continue; // already covered by hardcoded groups
if (t.system) sys.push(t);
else custom.push(t);
for (const tool of dbTools) {
if (SDK_KEYS.has(tool.key)) continue; // already covered by hardcoded groups
if (tool.system) sys.push(tool);
else custom.push(tool);
}
return [
{ label: "Execution", tools: SDK_EXEC },
{ label: "Write/Edit", tools: SDK_WRITE },
{ label: "System tools", tools: sys },
{ label: "Custom tools", tools: custom },
{ label: t("Execution"), tools: SDK_EXEC },
{ label: t("Write/Edit"), tools: SDK_WRITE },
{ label: t("System tools"), tools: sys },
{ label: t("Custom tools"), tools: custom },
].filter((g) => g.tools.length > 0);
}
@@ -186,9 +198,9 @@ function argvLabel(pattern: string): string {
// ---- small components ----
function ActionBadge({ action }: { action: InterceptAction }) {
if (action === "allow") return <Badge variant="secondary">Allow</Badge>;
if (action === "deny") return <Badge variant="destructive">Block</Badge>;
return <Badge variant="outline" className="border-amber-400 text-amber-600">Ask</Badge>;
if (action === "allow") return <Badge variant="secondary">{t("Allow")}</Badge>;
if (action === "deny") return <Badge variant="destructive">{t("Block")}</Badge>;
return <Badge variant="outline" className="border-amber-400 text-amber-600">{t("Ask")}</Badge>;
}
function Field({ label, children }: { label: string; children: React.ReactNode }) {
@@ -240,7 +252,7 @@ function JudgeCard() {
setCfg(j);
setProfiles(ps);
} catch (e) {
toast.error("Failed to load model fallback config: " + (e as Error).message);
toast.error(t("Failed to load model fallback config: {error}", { error: (e as Error).message }));
} finally {
setLoading(false);
}
@@ -263,10 +275,10 @@ function JudgeCard() {
setSaving(true);
try {
await api.interceptSetJudgeConfig(cfg);
toast.success("Model fallback config saved");
toast.success(t("Model fallback config saved"));
await load(); // read back: if the prompt was cleared, the built-in template is refilled
} catch (e) {
toast.error("Save failed: " + (e as Error).message);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
}
@@ -279,9 +291,9 @@ function JudgeCard() {
await api.interceptSetJudgeConfig({ ...cfg, prompt: "" });
const j = await api.interceptGetJudgeConfig();
setCfg(j);
toast.success("Built-in default template restored");
toast.success(t("Built-in default template restored"));
} catch (e) {
toast.error("Restore failed: " + (e as Error).message);
toast.error(t("Restore failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
}
@@ -298,14 +310,17 @@ function JudgeCard() {
<div className="flex items-center gap-2.5">
<BotIcon className={`h-5 w-5 shrink-0 ${cfg.enabled ? "text-violet-600" : "text-muted-foreground"}`} />
<div>
<p className="text-sm font-semibold leading-tight">Model fallback approval</p>
<p className="text-sm font-semibold leading-tight">{t("Model fallback approval")}</p>
<p className="text-xs text-muted-foreground mt-0.5">
Only commands inside the <span className="font-medium text-foreground">interception scope</span> that <span className="font-medium text-foreground">match no interception rule</span> are semantically judged by the model (allow / escalate to human / block)
{tRich("Only commands inside the {scope} that {norule} are semantically judged by the model (allow / escalate to human / block)", {
scope: <span className="font-medium text-foreground">{t("interception scope")}</span>,
norule: <span className="font-medium text-foreground">{t("match no interception rule")}</span>,
})}
</p>
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
<span className="text-xs text-muted-foreground">{cfg.enabled ? "Enabled" : "Disabled"}</span>
<span className="text-xs text-muted-foreground">{cfg.enabled ? t("Enabled") : t("Disabled")}</span>
<Switch checked={cfg.enabled} disabled={loading} onCheckedChange={(v) => patch({ enabled: v })} />
</div>
</div>
@@ -316,26 +331,26 @@ function JudgeCard() {
<CardContent className="p-4">
<div className="mb-3 flex items-center justify-between">
<div>
<p className="text-sm font-medium">Approval token consumption</p>
<p className="text-sm font-medium">{t("Approval token consumption")}</p>
<p className="text-xs text-muted-foreground">
Cumulative model fallback approval usage, metered separately (worker=judge), not mixed with per-model config stats
{t("Cumulative model fallback approval usage, metered separately (worker=judge), not mixed with per-model config stats")}
</p>
</div>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={loadUsage}>
Refresh
{t("Refresh")}
</Button>
</div>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-5">
<JudgeStat label="Approval calls" value={usage.calls.toLocaleString()} />
<JudgeStat label="Input tokens" value={fmtTokens(usage.input_tokens)} />
<JudgeStat label="Output tokens" value={fmtTokens(usage.output_tokens)} />
<JudgeStat label="Cache read" value={fmtTokens(usage.cache_read_tokens)} />
<JudgeStat label="Cache write" value={fmtTokens(usage.cache_write_tokens)} />
<JudgeStat label={t("Approval calls")} value={usage.calls.toLocaleString(intlLocale)} />
<JudgeStat label={t("Input tokens")} value={fmtTokens(usage.input_tokens)} />
<JudgeStat label={t("Output tokens")} value={fmtTokens(usage.output_tokens)} />
<JudgeStat label={t("Cache read")} value={fmtTokens(usage.cache_read_tokens)} />
<JudgeStat label={t("Cache write")} value={fmtTokens(usage.cache_write_tokens)} />
</div>
{usage.daily.length > 0 && (
<div className="mt-4">
<p className="mb-2 text-[10px] uppercase tracking-wider text-muted-foreground">
Daily consumption over the last 30 days (input + output)
{t("Daily consumption over the last 30 days (input + output)")}
</p>
<JudgeSparkbars daily={usage.daily} />
</div>
@@ -351,21 +366,21 @@ function JudgeCard() {
<CardContent className="flex h-full flex-col gap-2 p-4">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">Approval prompt</p>
<p className="text-xs text-muted-foreground">The model decides ALLOW / ASK / DENY based on this; directly editable</p>
<p className="text-sm font-medium">{t("Approval prompt")}</p>
<p className="text-xs text-muted-foreground">{t("The model decides ALLOW / ASK / DENY based on this; directly editable")}</p>
</div>
<Button variant="ghost" size="sm" className="h-7 text-xs" onClick={restorePrompt} disabled={saving}>
Restore default template
{t("Restore default template")}
</Button>
</div>
<Textarea
className="min-h-[22rem] flex-1 resize-none font-mono text-xs leading-relaxed"
value={cfg.prompt}
onChange={(e) => patch({ prompt: e.target.value })}
placeholder="Leave empty to use the built-in template"
placeholder={t("Leave empty to use the built-in template")}
spellCheck={false}
/>
<p className="text-right text-[11px] text-muted-foreground">{cfg.prompt.length} chars</p>
<p className="text-right text-[11px] text-muted-foreground">{t("{count} chars", { count: cfg.prompt.length })}</p>
</CardContent>
</Card>
@@ -373,12 +388,12 @@ function JudgeCard() {
<Card className="lg:col-span-2">
<CardContent className="space-y-5 p-4">
<div className="space-y-4">
<p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">Judge model and policy</p>
<Field label="Approval model">
<p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">{t("Judge model and policy")}</p>
<Field label={t("Approval model")}>
<Select value={String(cfg.profile_id || 0)} onValueChange={(v) => patch({ profile_id: Number(v) })}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={FOLLOW_ACTIVE}>Follow active profile</SelectItem>
<SelectItem value={FOLLOW_ACTIVE}>{t("Follow active profile")}</SelectItem>
{profiles.map((p) => (
<SelectItem key={p.id} value={p.id}>
{p.name} ({p.model})
@@ -387,16 +402,16 @@ function JudgeCard() {
</SelectContent>
</Select>
</Field>
<Field label="Judge mode">
<Field label={t("Judge mode")}>
<Select value={cfg.mode ?? "closed"} onValueChange={(v) => patch({ mode: v as JudgeConfig["mode"] })}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="closed">Closed questions (code decides; prompt is the operator policy; failure asks)</SelectItem>
<SelectItem value="freeform">Free-form prompt (model decides)</SelectItem>
<SelectItem value="closed">{t("Closed questions (code decides; prompt is the operator policy; failure asks)")}</SelectItem>
<SelectItem value="freeform">{t("Free-form prompt (model decides)")}</SelectItem>
</SelectContent>
</Select>
</Field>
<Field label="Model judge timeout (seconds)">
<Field label={t("Model judge timeout (seconds)")}>
<Input
type="number"
min={1}
@@ -407,13 +422,13 @@ function JudgeCard() {
}}
/>
</Field>
<Field label="When the model fails (error / timeout / unparsable)">
<Field label={t("When the model fails (error / timeout / unparsable)")}>
<Select value={cfg.fail_action} onValueChange={(v) => patch({ fail_action: v as JudgeConfig["fail_action"] })}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="ask">Escalate to human approval</SelectItem>
<SelectItem value="deny">Block</SelectItem>
<SelectItem value="allow">{t("Allow")}</SelectItem>
<SelectItem value="ask">{t("Escalate to human approval")}</SelectItem>
<SelectItem value="deny">{t("Block")}</SelectItem>
</SelectContent>
</Select>
</Field>
@@ -422,8 +437,8 @@ function JudgeCard() {
<Separator />
<div className="space-y-4">
<p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">Human approval (when the model decides "ask")</p>
<Field label="Approval wait timeout (seconds)">
<p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">{t("Human approval (when the model decides \"ask\")")}</p>
<Field label={t("Approval wait timeout (seconds)")}>
<Input
type="number"
min={5}
@@ -434,12 +449,12 @@ function JudgeCard() {
}}
/>
</Field>
<Field label="Default action after timeout">
<Field label={t("Default action after timeout")}>
<Select value={cfg.ask_timeout_action} onValueChange={(v) => patch({ ask_timeout_action: v as JudgeConfig["ask_timeout_action"] })}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="deny">Block</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">{t("Block")}</SelectItem>
<SelectItem value="allow">{t("Allow")}</SelectItem>
</SelectContent>
</Select>
</Field>
@@ -451,7 +466,7 @@ function JudgeCard() {
<div className="flex justify-end">
<Button size="sm" onClick={save} disabled={saving || loading}>
{saving ? "Saving…" : "Save config"}
{saving ? t("Saving…") : t("Save config")}
</Button>
</div>
</div>
@@ -494,7 +509,7 @@ export default function InterceptPage() {
const r = await api.interceptRules();
setRules(r);
} catch {
toast.error("Failed to load interception rules");
toast.error(t("Failed to load interception rules"));
} finally {
setLoading(false);
}
@@ -541,17 +556,17 @@ export default function InterceptPage() {
}
async function handleSave() {
if (!form.name.trim()) { toast.error("Name cannot be empty"); return; }
if (!form.pattern.trim()) { toast.error("Pattern cannot be empty"); return; }
if (regexErr) { toast.error("Invalid regex syntax"); return; }
if (!form.name.trim()) { toast.error(t("Name cannot be empty")); return; }
if (!form.pattern.trim()) { toast.error(t("Pattern cannot be empty")); return; }
if (regexErr) { toast.error(t("Invalid regex syntax")); return; }
setSaving(true);
try {
if (editing) {
await api.updateInterceptRule(editing.id, form);
toast.success("Rule updated");
toast.success(t("Rule updated"));
} else {
await api.createInterceptRule(form);
toast.success("Rule created");
toast.success(t("Rule created"));
}
setOpen(false);
load();
@@ -565,7 +580,7 @@ export default function InterceptPage() {
async function handleDelete(id: number) {
try {
await api.deleteInterceptRule(id);
toast.success("Rule deleted");
toast.success(t("Rule deleted"));
load();
} catch (e) {
toast.error((e as Error).message);
@@ -591,7 +606,7 @@ export default function InterceptPage() {
setAllTools(tools);
setEnabledTools(new Set(cfg.enabled_tools));
} catch (e) {
toast.error("Load failed: " + (e as Error).message);
toast.error(t("Load failed: {error}", { error: (e as Error).message }));
} finally {
setScopeLoading(false);
}
@@ -609,11 +624,11 @@ export default function InterceptPage() {
setScopeSaving(true);
try {
await api.interceptSetToolConfig([...enabledTools]);
toast.success("Interception scope saved");
toast.success(t("Interception scope saved"));
setScopeTools([...enabledTools]);
setScopeOpen(false);
} catch (e) {
toast.error("Save failed: " + (e as Error).message);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setScopeSaving(false);
}
@@ -630,9 +645,9 @@ export default function InterceptPage() {
<div className="flex items-center gap-2.5">
<ShieldAlertIcon className="h-5 w-5 shrink-0" />
<div>
<h1 className="text-lg font-semibold leading-tight">Command interception</h1>
<h1 className="text-lg font-semibold leading-tight">{t("Command interception")}</h1>
<p className="text-sm text-muted-foreground mt-0.5">
Tools are matched against interception rules before execution; unmatched commands can be judged by the model fallback
{t("Tools are matched against interception rules before execution; unmatched commands can be judged by the model fallback")}
</p>
</div>
</div>
@@ -647,14 +662,14 @@ export default function InterceptPage() {
>
<div className="flex min-w-0 items-center gap-2 text-sm">
<ListFilterIcon className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="shrink-0 font-medium">Interception scope</span>
<span className="shrink-0 font-medium">{t("Interception scope")}</span>
{scopeTools.length === 0 ? (
<span className="text-amber-700 dark:text-amber-500">
No tools enabled — neither interception rules nor the model fallback take effect
{t("No tools enabled — neither interception rules nor the model fallback take effect")}
</span>
) : (
<>
<Badge variant="secondary" className="shrink-0">{scopeTools.length} tools</Badge>
<Badge variant="secondary" className="shrink-0">{t("{count} tools", { count: scopeTools.length })}</Badge>
<span className="truncate text-muted-foreground" title={scopeTools.join(", ")}>
{scopeTools.join(", ")}
</span>
@@ -668,52 +683,52 @@ export default function InterceptPage() {
onClick={openScope}
>
<ListFilterIcon className="h-4 w-4" />
Adjust scope
{t("Adjust scope")}
</Button>
</div>
<Tabs defaultValue="rules" className="flex-1">
<TabsList>
<TabsTrigger value="rules">Interception rules</TabsTrigger>
<TabsTrigger value="judge">Model config</TabsTrigger>
<TabsTrigger value="rules">{t("Interception rules")}</TabsTrigger>
<TabsTrigger value="judge">{t("Model config")}</TabsTrigger>
</TabsList>
{/* ---- tab: interception rules ---- */}
<TabsContent value="rules" className="mt-4 flex flex-col gap-4">
<div className="flex items-center justify-between gap-3">
<p className="text-xs text-muted-foreground">
Rules are matched one by one in priority order (higher numbers first); the first match wins
{t("Rules are matched one by one in priority order (higher numbers first); the first match wins")}
</p>
<Button onClick={openNew} size="sm" className="shrink-0">
<PlusIcon className="h-4 w-4" />
Create rule
{t("Create rule")}
</Button>
</div>
<Card>
<CardContent className="p-0">
{loading ? (
<p className="p-6 text-sm text-muted-foreground">Loading…</p>
<p className="p-6 text-sm text-muted-foreground">{t("Loading…")}</p>
) : rules.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 py-16 text-center">
<ShieldAlertIcon className="h-8 w-8 text-muted-foreground/40" />
<p className="text-sm text-muted-foreground">No rules yet</p>
<p className="text-sm text-muted-foreground">{t("No rules yet")}</p>
<Button size="sm" variant="outline" onClick={openNew}>
<PlusIcon className="h-4 w-4" />
Create the first rule
{t("Create the first rule")}
</Button>
</div>
) : (
<Table>
<TableHeader>
<TableRow className="hover:bg-transparent">
<TableHead className="w-[72px]">Priority</TableHead>
<TableHead>Name</TableHead>
<TableHead className="w-[90px]">Target</TableHead>
<TableHead className="w-[80px]">Type</TableHead>
<TableHead>Pattern</TableHead>
<TableHead className="w-[72px]">Policy</TableHead>
<TableHead className="w-[64px] text-center">Enabled</TableHead>
<TableHead className="w-[72px]">{t("Priority")}</TableHead>
<TableHead>{t("Name")}</TableHead>
<TableHead className="w-[90px]">{t("Target")}</TableHead>
<TableHead className="w-[80px]">{t("Type")}</TableHead>
<TableHead>{t("Pattern")}</TableHead>
<TableHead className="w-[72px]">{t("Policy")}</TableHead>
<TableHead className="w-[64px] text-center">{t("Enabled")}</TableHead>
<TableHead className="w-[80px]" />
</TableRow>
</TableHeader>
@@ -726,12 +741,12 @@ export default function InterceptPage() {
<TableCell className="font-medium text-sm">{rule.name}</TableCell>
<TableCell>
<span className="text-xs text-muted-foreground">
{rule.match_target === "tool_name" ? "Tool name" : "Input content"}
{rule.match_target === "tool_name" ? t("Tool name") : t("Input content")}
</span>
</TableCell>
<TableCell>
<span className="text-xs text-muted-foreground">
{rule.match_type === "regex" ? "Regex" : rule.match_type === "argv" ? "Argv prefix" : "String"}
{rule.match_type === "regex" ? t("Regex") : rule.match_type === "argv" ? t("Argv prefix") : t("String")}
</span>
</TableCell>
<TableCell className="max-w-[220px]">
@@ -784,22 +799,22 @@ export default function InterceptPage() {
<Sheet open={open} onOpenChange={setOpen}>
<SheetContent side="right" className="flex flex-col gap-0 p-0 sm:max-w-md">
<SheetHeader className="border-b px-6 py-4">
<SheetTitle>{editing ? "Edit rule" : "Create rule"}</SheetTitle>
<SheetTitle>{editing ? t("Edit rule") : t("Create rule")}</SheetTitle>
<SheetDescription className="text-xs">
Higher priority matches first; the first matching rule wins and the rest are skipped
{t("Higher priority matches first; the first matching rule wins and the rest are skipped")}
</SheetDescription>
</SheetHeader>
<div className="flex-1 min-h-0 overflow-y-auto px-6 py-5 space-y-5">
<Field label="Name">
<Field label={t("Name")}>
<Input
placeholder="Give the rule a name"
placeholder={t("Give the rule a name")}
value={form.name}
onChange={(e) => set({ name: e.target.value })}
/>
</Field>
<Field label="Priority (higher numbers match first)">
<Field label={t("Priority (higher numbers match first)")}>
<Input
type="number"
value={form.priority}
@@ -809,20 +824,20 @@ export default function InterceptPage() {
<Separator />
<Field label="Match target">
<Field label={t("Match target")}>
<Select
value={form.match_target}
onValueChange={(v) => set({ match_target: v as RuleForm["match_target"] })}
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="tool_name">Tool name (tool_name)</SelectItem>
<SelectItem value="tool_input">Input content (tool_input JSON)</SelectItem>
<SelectItem value="tool_name">{t("Tool name (tool_name)")}</SelectItem>
<SelectItem value="tool_input">{t("Input content (tool_input JSON)")}</SelectItem>
</SelectContent>
</Select>
</Field>
<Field label="Match type">
<Field label={t("Match type")}>
<Select
value={form.match_type}
onValueChange={(v) => {
@@ -833,14 +848,14 @@ export default function InterceptPage() {
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="string">String contains</SelectItem>
<SelectItem value="regex">Regular expression</SelectItem>
<SelectItem value="argv">Argv prefix (Bash only)</SelectItem>
<SelectItem value="string">{t("String contains")}</SelectItem>
<SelectItem value="regex">{t("Regular expression")}</SelectItem>
<SelectItem value="argv">{t("Argv prefix (Bash only)")}</SelectItem>
</SelectContent>
</Select>
</Field>
<Field label="Pattern">
<Field label={t("Pattern")}>
<Input
placeholder={form.match_type === "regex" ? "^Bash$" : form.match_type === "argv" ? '["git","push"]' : "rm -rf"}
value={form.pattern}
@@ -851,37 +866,46 @@ export default function InterceptPage() {
<p className="text-xs text-destructive mt-1">{regexErr}</p>
)}
{regexWarn && (
<p className="text-xs text-amber-600 mt-1">Contains Go RE2 extended syntax (e.g. <code className="font-mono">(?i)</code>); the browser cannot preview it, and the server validates on submission</p>
<p className="text-xs text-amber-600 mt-1">
{tRich("Contains Go RE2 extended syntax (e.g. {example}); the browser cannot preview it, and the server validates on submission", {
example: <code className="font-mono">(?i)</code>,
})}
</p>
)}
{form.match_type === "argv" && (
<p className="text-xs text-amber-600 mt-1">
JSON array of 1 to 8 tokens: the program and its subcommands, no flags. Matches a single simple Bash command
whose prefix is exactly <code className="font-mono">{argvLabel(form.pattern)}</code>. Flags are not constrained:
<code className="font-mono"> [&quot;git&quot;,&quot;push&quot;]</code> also covers <code className="font-mono">git push --force</code>.
{t("JSON array of 1 to 8 tokens: the program and its subcommands, no flags.")}{" "}
{tRich("Matches a single simple Bash command whose prefix is exactly {prefix}.", {
prefix: <code className="font-mono">{argvLabel(form.pattern)}</code>,
})}{" "}
{tRich("Flags are not constrained: {pattern} also covers {command}.", {
pattern: <code className="font-mono">[&quot;git&quot;,&quot;push&quot;]</code>,
command: <code className="font-mono">git push --force</code>,
})}
</p>
)}
</Field>
<Separator />
<Field label="Interception policy">
<Field label={t("Interception policy")}>
<Select
value={form.action}
onValueChange={(v) => set({ action: v as InterceptAction })}
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="allow">Allow — pass through directly, skipping the remaining rules</SelectItem>
<SelectItem value="deny">Block — cut it off and return a denial message to the model</SelectItem>
<SelectItem value="ask">Ask the user — wait for approval</SelectItem>
<SelectItem value="allow">{t("Allow — pass through directly, skipping the remaining rules")}</SelectItem>
<SelectItem value="deny">{t("Block — cut it off and return a denial message to the model")}</SelectItem>
<SelectItem value="ask">{t("Ask the user — wait for approval")}</SelectItem>
</SelectContent>
</Select>
</Field>
{form.action !== "allow" && (
<Field label={form.action === "deny" ? "Denial message (returned to the model)" : "Approval note (optional)"}>
<Field label={form.action === "deny" ? t("Denial message (returned to the model)") : t("Approval note (optional)")}>
<Textarea
placeholder={form.action === "deny" ? "Blocked by the security policy" : ""}
placeholder={form.action === "deny" ? t("Blocked by the security policy") : ""}
value={form.message}
onChange={(e) => set({ message: e.target.value })}
rows={2}
@@ -895,8 +919,8 @@ export default function InterceptPage() {
<Separator />
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">Enable approval timeout</p>
<p className="text-xs text-muted-foreground">Handle automatically after the timeout instead of waiting</p>
<p className="text-sm font-medium">{t("Enable approval timeout")}</p>
<p className="text-xs text-muted-foreground">{t("Handle automatically after the timeout instead of waiting")}</p>
</div>
<Switch
checked={form.timeout_enabled}
@@ -905,7 +929,7 @@ export default function InterceptPage() {
</div>
{form.timeout_enabled && (
<div className="flex items-end gap-3">
<Field label="Timeout (seconds)">
<Field label={t("Timeout (seconds)")}>
<Input
type="number"
min={5}
@@ -917,15 +941,15 @@ export default function InterceptPage() {
}}
/>
</Field>
<Field label="Timeout action">
<Field label={t("Timeout action")}>
<Select
value={form.timeout_action}
onValueChange={(v) => set({ timeout_action: v as "deny" | "allow" })}
>
<SelectTrigger className="w-32"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="deny">Auto-deny</SelectItem>
<SelectItem value="allow">Auto-allow</SelectItem>
<SelectItem value="deny">{t("Auto-deny")}</SelectItem>
<SelectItem value="allow">{t("Auto-allow")}</SelectItem>
</SelectContent>
</Select>
</Field>
@@ -942,14 +966,14 @@ export default function InterceptPage() {
checked={form.enabled}
onCheckedChange={(v) => set({ enabled: v })}
/>
<Label htmlFor="rule-enabled" className="cursor-pointer">Enable this rule</Label>
<Label htmlFor="rule-enabled" className="cursor-pointer">{t("Enable this rule")}</Label>
</div>
</div>
<SheetFooter className="border-t px-6 py-4 flex-row justify-end gap-2">
<Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
<Button variant="outline" onClick={() => setOpen(false)}>{t("Cancel")}</Button>
<Button onClick={handleSave} disabled={saving || !!regexErr}>
{saving ? "Saving…" : "Save"}
{saving ? t("Saving…") : t("Save")}
</Button>
</SheetFooter>
</SheetContent>
@@ -961,16 +985,16 @@ export default function InterceptPage() {
<DialogHeader className="shrink-0 border-b px-6 py-4">
<DialogTitle className="flex items-center gap-2">
<ListFilterIcon className="h-4 w-4" />
Interception scope
{t("Interception scope")}
</DialogTitle>
<DialogDescription className="text-xs">
Only tools with interception enabled go through rule matching; all other tools pass through directly
{t("Only tools with interception enabled go through rule matching; all other tools pass through directly")}
</DialogDescription>
</DialogHeader>
<div className="flex-1 min-h-0 overflow-y-auto px-6 py-4 space-y-5">
{scopeLoading ? (
<p className="text-sm text-muted-foreground py-4">Loading…</p>
<p className="text-sm text-muted-foreground py-4">{t("Loading…")}</p>
) : (
toolGroups.map((group, gi) => (
<div key={group.label}>
@@ -979,22 +1003,22 @@ export default function InterceptPage() {
{group.label}
</p>
<div className="space-y-0.5">
{group.tools.map((t) => (
<div key={t.key} className="flex items-center gap-3 rounded-md px-2 py-1.5 hover:bg-muted/50">
{group.tools.map((tool) => (
<div key={tool.key} className="flex items-center gap-3 rounded-md px-2 py-1.5 hover:bg-muted/50">
<Switch
id={`scope-${t.key}`}
checked={enabledTools.has(t.key)}
onCheckedChange={(v) => toggleTool(t.key, v)}
id={`scope-${tool.key}`}
checked={enabledTools.has(tool.key)}
onCheckedChange={(v) => toggleTool(tool.key, v)}
/>
<label htmlFor={`scope-${t.key}`} className="flex-1 min-w-0 cursor-pointer">
<label htmlFor={`scope-${tool.key}`} className="flex-1 min-w-0 cursor-pointer">
<div className="flex items-center gap-1.5">
<span className="font-mono text-sm">{t.key}</span>
{(t.kind && t.kind !== "builtin") && (
<Badge variant="outline" className="px-1 py-0 text-[10px]">{t.kind}</Badge>
<span className="font-mono text-sm">{tool.key}</span>
{(tool.kind && tool.kind !== "builtin") && (
<Badge variant="outline" className="px-1 py-0 text-[10px]">{tool.kind}</Badge>
)}
</div>
{t.description && (
<p className="text-[11px] text-muted-foreground line-clamp-1">{t.description}</p>
{tool.description && (
<p className="text-[11px] text-muted-foreground line-clamp-1">{tool.description}</p>
)}
</label>
</div>
@@ -1006,9 +1030,9 @@ export default function InterceptPage() {
</div>
<div className="shrink-0 border-t px-6 py-3 flex justify-end gap-2">
<Button variant="outline" size="sm" onClick={() => setScopeOpen(false)}>Cancel</Button>
<Button variant="outline" size="sm" onClick={() => setScopeOpen(false)}>{t("Cancel")}</Button>
<Button size="sm" onClick={saveScope} disabled={scopeSaving || scopeLoading}>
{scopeSaving ? "Saving…" : "Save"}
{scopeSaving ? t("Saving…") : t("Save")}
</Button>
</div>
</DialogContent>
@@ -17,6 +17,7 @@ import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { LLMRetryOverride, LLMRetryPolicy, LLMRetryRule } from "@/lib/types";
@@ -52,65 +53,59 @@ type LayerMeta = {
export const RETRY_LAYERS = {
connect: {
title: "Connect retry",
where: "SDK · before a 200 arrives",
trigger:
"Cannot connect or no 200 yet: network-layer errors such as connection reset / read-write timeout / DNS failure, plus HTTP 408, 429, 500, 502, 503, 504.",
skips: "The remaining status codes (400 / 401 / 403 / 404 / 413 / 422 etc.) are deterministic rejections — resending fails the same way, so they bubble up directly.",
desc: "Resends the same request verbatim. Once the stream has started (a 200 was received), a mid-stream drop is no longer this layer's business.",
attemptsLabel: "Retry attempts",
title: t("Connect retry"),
where: t("SDK · before a 200 arrives"),
trigger: t("Cannot connect or no 200 yet: network-layer errors such as connection reset / read-write timeout / DNS failure, plus HTTP 408, 429, 500, 502, 503, 504."),
skips: t("The remaining status codes (400 / 401 / 403 / 404 / 413 / 422 etc.) are deterministic rejections — resending fails the same way, so they bubble up directly."),
desc: t("Resends the same request verbatim. Once the stream has started (a 200 was received), a mid-stream drop is no longer this layer's business."),
attemptsLabel: t("Retry attempts"),
defAttempts: 3,
defInterval: "0.5s→1s→2s exponential (capped at 8s)",
offHint: "-1 = no retries at all; the failure bubbles up immediately",
defInterval: t("0.5s→1s→2s exponential (capped at 8s)"),
offHint: t("-1 = no retries at all; the failure bubbles up immediately"),
},
empty: {
title: "Empty-response retry",
where: "SDK · openai format only",
trigger:
"HTTP 200 with a normal stop finish_reason, yet not a single content block in the response — gateway empty frames, dropped thinking-field frames and sampling hiccups all look like this.",
skips: "Empty because of max_tokens truncation does not count (fix that by raising the output cap; resending just hits it again).",
desc: "Resends the entire prompt, so it is relatively expensive on long contexts; keep the count small.",
attemptsLabel: "Retry attempts",
title: t("Empty-response retry"),
where: t("SDK · openai format only"),
trigger: t("HTTP 200 with a normal stop finish_reason, yet not a single content block in the response — gateway empty frames, dropped thinking-field frames and sampling hiccups all look like this."),
skips: t("Empty because of max_tokens truncation does not count (fix that by raising the output cap; resending just hits it again)."),
desc: t("Resends the entire prompt, so it is relatively expensive on long contexts; keep the count small."),
attemptsLabel: t("Retry attempts"),
defAttempts: 2,
defInterval: "0.5s→1s→2s exponential (capped at 8s)",
offHint: "-1 = hand the empty response through as-is",
defInterval: t("0.5s→1s→2s exponential (capped at 8s)"),
offHint: t("-1 = hand the empty response through as-is"),
},
stream: {
title: "Same-provider safe-window retry",
where: "This project · before any output is delivered",
trigger:
"Trouble only after the stream is established (a 200 received): mid-stream disconnects, provider overloaded, in-stream 429 / 5xx error events — while not a single token has been handed to the caller yet.",
skips:
"Quota exhausted (402 / insufficient_quota, handed to the pool to switch configs), context too long (413 / context length, handed to compression), and deterministic rejections (400 / 401 / 403 / 404 / 422) are never retried.",
desc: "Replays the same request on the same config. Since no output has been delivered yet, the replay cannot duplicate model output or tool executions.",
attemptsLabel: "Retry attempts",
title: t("Same-provider safe-window retry"),
where: t("This project · before any output is delivered"),
trigger: t("Trouble only after the stream is established (a 200 received): mid-stream disconnects, provider overloaded, in-stream 429 / 5xx error events — while not a single token has been handed to the caller yet."),
skips: t("Quota exhausted (402 / insufficient_quota, handed to the pool to switch configs), context too long (413 / context length, handed to compression), and deterministic rejections (400 / 401 / 403 / 404 / 422) are never retried."),
desc: t("Replays the same request on the same config. Since no output has been delivered yet, the replay cannot duplicate model output or tool executions."),
attemptsLabel: t("Retry attempts"),
defAttempts: 2,
defInterval: "0.5s→1s exponential (capped at 4s)",
offHint: "-1 = a broken stream goes straight to the outer intent rerun",
defInterval: t("0.5s→1s exponential (capped at 4s)"),
offHint: t("-1 = a broken stream goes straight to the outer intent rerun"),
},
breaker: {
title: "Pool breaker",
where: "This project · process-level, one global copy",
trigger:
"Trips when transient failures (429, 5xx, network errors) accumulate consecutively to the threshold; deterministic failures — insufficient balance (402), dead key (401 / 403), missing model (404) — ignore the threshold and trip on the first occurrence.",
skips: "One success resets the counter, so an occasionally flaky config is not slowly ground into tripping.",
desc: "After tripping it enters cooldown, and while cooling the pool skips the config outright. State is persisted, surviving restarts.",
attemptsLabel: "Consecutive failures to trip",
title: t("Pool breaker"),
where: t("This project · process-level, one global copy"),
trigger: t("Trips when transient failures (429, 5xx, network errors) accumulate consecutively to the threshold; deterministic failures — insufficient balance (402), dead key (401 / 403), missing model (404) — ignore the threshold and trip on the first occurrence."),
skips: t("One success resets the counter, so an occasionally flaky config is not slowly ground into tripping."),
desc: t("After tripping it enters cooldown, and while cooling the pool skips the config outright. State is persisted, surviving restarts."),
attemptsLabel: t("Consecutive failures to trip"),
defAttempts: 3,
defInterval: "1min→5min→30min gradient",
offHint: "-1 = transient failures never trip (deterministic failures still do)",
defInterval: t("1min→5min→30min gradient"),
offHint: t("-1 = transient failures never trip (deterministic failures still do)"),
},
intent: {
title: "Intent rerun",
where: "This project · process-level, one global copy",
trigger:
"The earlier layers could not save it: the worker ends with model_error — inner retries all exhausted, or the stream broke only after output delivery had started (when replay is unsafe and only a full rerun works).",
skips: "Quota exhaustion is already handled by the pool switching configs and is not rerun here; when the task is paused / aborted / wrapping up it yields immediately, spending no backoff time.",
desc: "Reruns the whole intent from scratch. It is the outermost layer, so one rerun multiplies the inner layers' attempt counts once more.",
attemptsLabel: "Rerun attempts",
title: t("Intent rerun"),
where: t("This project · process-level, one global copy"),
trigger: t("The earlier layers could not save it: the worker ends with model_error — inner retries all exhausted, or the stream broke only after output delivery had started (when replay is unsafe and only a full rerun works)."),
skips: t("Quota exhaustion is already handled by the pool switching configs and is not rerun here; when the task is paused / aborted / wrapping up it yields immediately, spending no backoff time."),
desc: t("Reruns the whole intent from scratch. It is the outermost layer, so one rerun multiplies the inner layers' attempt counts once more."),
attemptsLabel: t("Rerun attempts"),
defAttempts: 2,
defInterval: "Fixed 3s",
offHint: "-1 = no rerun; the intent is marked blocked outright",
defInterval: t("Fixed 3s"),
offHint: t("-1 = no rerun; the intent is marked blocked outright"),
},
} satisfies Record<string, LayerMeta>;
@@ -119,9 +114,9 @@ type LayerKey = keyof typeof RETRY_LAYERS;
/** Milliseconds in human terms, only echoed next to the input so nobody counts zeros. */
function humanMs(ms: number) {
if (!Number.isFinite(ms) || ms <= 0) return "";
if (ms < 1000) return `${ms}ms`;
if (ms < 60_000) return `${Number((ms / 1000).toFixed(2))}s`;
return `${Number((ms / 60_000).toFixed(2))}min`;
if (ms < 1000) return t("{n}ms", { n: ms });
if (ms < 60_000) return t("{n}s", { n: Number((ms / 1000).toFixed(2)) });
return t("{n}min", { n: Number((ms / 60_000).toFixed(2)) });
}
/** Controlled numeric input: empty string ↔ 0; intermediate states ("-", "1e") stay local and never bother the parent. */
@@ -188,11 +183,11 @@ export function RetryRuleFields({
</div>
{/* Which errors reach this layer, down to status codes — if the knobs seem to have no effect, the error most likely does not land on this layer at all. */}
<p className="text-muted-foreground text-xs">
<span className="font-medium text-foreground">Triggers</span>: {meta.trigger}
<span className="font-medium text-foreground">{t("Triggers")}</span>: {meta.trigger}
</p>
{!compact && meta.skips && (
<p className="text-muted-foreground text-xs">
<span className="font-medium text-foreground">Skipped here</span>: {meta.skips}
<span className="font-medium text-foreground">{t("Skipped here")}</span>: {meta.skips}
</p>
)}
{!compact && <p className="text-muted-foreground text-xs">{meta.desc}</p>}
@@ -206,25 +201,29 @@ export function RetryRuleFields({
id={`${idPrefix}-${layer}-n`}
min={-1}
value={value.attempts}
placeholder={`Default ${meta.defAttempts}`}
placeholder={t("Default {count}", { count: meta.defAttempts })}
onChange={(n) => onChange({ ...value, attempts: n })}
/>
</div>
<div className="flex items-center gap-2">
<Label htmlFor={`${idPrefix}-${layer}-ms`} className="text-muted-foreground text-xs">
Interval ms
{t("Interval ms")}
</Label>
<NumField
id={`${idPrefix}-${layer}-ms`}
min={0}
value={value.interval_ms}
placeholder="Default backoff"
placeholder={t("Default backoff")}
onChange={(n) => onChange({ ...value, interval_ms: n })}
/>
<span className="text-muted-foreground text-xs">{human ? `Fixed ${human}` : meta.defInterval}</span>
<span className="text-muted-foreground text-xs">
{human ? t("Fixed {value}", { value: human }) : meta.defInterval}
</span>
</div>
</div>
{!compact && <p className="text-muted-foreground text-xs">Empty = use the default; {meta.offHint}.</p>}
{!compact && (
<p className="text-muted-foreground text-xs">{t("Empty = use the default; {hint}.", { hint: meta.offHint })}</p>
)}
</div>
);
}
@@ -240,10 +239,11 @@ export function ProfileRetryFields({
return (
<div className="grid gap-3 rounded-lg border p-3">
<div className="grid gap-0.5">
<Label className="text-sm">Retry overrides</Label>
<Label className="text-sm">{t("Retry overrides")}</Label>
<p className="text-muted-foreground text-xs">
Applies only to this profile, overriding the global defaults from "Retry & backoff". Each field left empty = follow the global; attempts -1 = disable this layer;
a filled interval replaces the exponential backoff with a fixed one. The breaker and intent rerun are process-level and can only be tuned on the global page.
{t(
'Applies only to this profile, overriding the global defaults from "Retry & backoff". Each field left empty = follow the global; attempts -1 = disable this layer; a filled interval replaces the exponential backoff with a fixed one. The breaker and intent rerun are process-level and can only be tuned on the global page.',
)}
</p>
</div>
{(["connect", "empty", "stream"] as const).map((k) => (
@@ -273,7 +273,7 @@ export function RetryPolicyPanel() {
const p = await api.llmRetryPolicy();
setPolicy({ ...ZERO_POLICY, ...p });
} catch (e) {
toast.error(`Failed to load retry policy: ${(e as Error).message}`);
toast.error(t("Failed to load retry policy: {error}", { error: (e as Error).message }));
} finally {
setLoading(false);
}
@@ -290,9 +290,9 @@ export function RetryPolicyPanel() {
// The backend clamps out-of-range values back into the interval and returns them; refresh straight from the reply so what you see is what is stored.
const saved = await api.saveLLMRetryPolicy(policy);
setPolicy({ ...ZERO_POLICY, ...saved });
toast.success("Saved; takes effect immediately (calls already in flight still use the old parameters)");
toast.success(t("Saved; takes effect immediately (calls already in flight still use the old parameters)"));
} catch (e) {
toast.error(`Save failed: ${(e as Error).message}`);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
}
@@ -303,7 +303,7 @@ export function RetryPolicyPanel() {
if (loading) {
return (
<div className="flex items-center gap-2 rounded-lg border border-dashed p-10 text-muted-foreground text-sm">
<Loader2Icon className="size-4 animate-spin" /> Loading retry policy…
<Loader2Icon className="size-4 animate-spin" /> {t("Loading retry policy…")}
</div>
);
}
@@ -311,12 +311,20 @@ export function RetryPolicyPanel() {
return (
<div className="grid gap-4">
<div className="rounded-lg border bg-muted/30 p-3 text-muted-foreground text-xs leading-relaxed">
A failed model call passes through five retry layers in turn, innermost to outermost:
<span className="text-foreground"> connect → empty response → same-provider safe window → pool breaker → intent rerun</span>
. An outer layer only gets what the inner ones exhausted, so the attempt counts
<span className="text-foreground">multiply</span>
— max out every layer and a single hiccup can burn dozens of requests.
Leaving everything empty keeps the current defaults, identical to the behavior before this page existed. The first three layers can be overridden per model profile.
{t(
"A failed model call passes through five retry layers in turn, innermost to outermost: <b>connect → empty response → same-provider safe window → pool breaker → intent rerun</b>. An outer layer only gets what the inner ones exhausted, so the attempt counts <b>multiply</b> — max out every layer and a single hiccup can burn dozens of requests. Leaving everything empty keeps the current defaults, identical to the behavior before this page existed. The first three layers can be overridden per model profile.",
)
.split(/<b>(.*?)<\/b>/)
.map((part, i) =>
i % 2 === 1 ? (
// biome-ignore lint/suspicious/noArrayIndexKey: static split of one translated sentence
<span key={i} className="text-foreground">
{part}
</span>
) : (
part
),
)}
</div>
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
@@ -328,10 +336,10 @@ export function RetryPolicyPanel() {
<div className="flex gap-2">
<Button onClick={save} disabled={saving}>
{saving ? <Loader2Icon className="animate-spin" /> : <SaveIcon />}
Save
{t("Save")}
</Button>
<Button variant="outline" onClick={() => setPolicy(ZERO_POLICY)} disabled={saving}>
Reset all to defaults
{t("Reset all to defaults")}
</Button>
</div>
</div>
+177 -135
View File
@@ -26,6 +26,7 @@ import { Separator } from "@/components/ui/separator";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { LLMPoolMember, LLMPoolStatus, LLMProfile, LLMRetryOverride } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -33,6 +34,11 @@ import { cn } from "@/lib/utils";
import { ProfileRetryFields, RetryPolicyPanel, ZERO_OVERRIDE } from "./_components/retry";
import { setVisibleInterval } from "@/lib/polling";
// Renders a translated string, turning <b>…</b> spans into bold elements, so a sentence with emphasis stays one key.
function rich(s: string): React.ReactNode[] {
return s.split(/<b>(.*?)<\/b>/).map((part, i) => (i % 2 === 1 ? <b key={i}>{part}</b> : part));
}
// The thinking switch (thinking.type) and the thinking effort (reasoning_effort) are two [independent] fields,
// each set on its own — some APIs have no thinking field and activate thinking via the effort parameter alone, hence the decoupling.
// An empty string in storage = the field is [not sent]; Radix Select rejects an empty value, so the UI uses "none"
@@ -41,29 +47,30 @@ const NONE = "none";
const fromStore = (v?: string) => (v ? v : NONE);
const toStore = (v: string) => (v === NONE ? "" : v);
const THINKING_TYPES: { value: string; label: string }[] = [
{ value: NONE, label: "Not sent (default)" },
{ value: "disabled", label: "Disabled" },
{ value: "enabled", label: "Enabled" },
{ value: NONE, label: t("Not sent (default)") },
{ value: "disabled", label: t("Disabled") },
{ value: "enabled", label: t("Enabled") },
];
// Which request field name carries the output cap (only meaningful for the openai format). NONE ↔ "" shares the same sentinel conversion.
const MAX_TOKENS_FIELDS: { value: string; label: string }[] = [
{ value: NONE, label: "max_tokens (default)" },
{ value: NONE, label: t("max_tokens (default)") },
{ value: "max_completion_tokens", label: "max_completion_tokens" },
];
// The other formats hard-code their field names, so the option is meaningless for them; the hint texts spell this out.
const MAX_TOKENS_FIELD_HINTS: Record<string, string> = {
openai:
openai: t(
"Which key carries the cap. max_tokens is the default and the vast majority of compatible gateways only accept it; OpenAI's official reasoning models (the o series / GPT-5) conversely only accept max_completion_tokens and fail outright with unsupported_parameter when they receive max_tokens.",
anthropic: "Only selectable for the openai format. Anthropic's field name is fixed as max_tokens.",
"openai-responses": "Only selectable for the openai format. The Responses API's field name is fixed as max_output_tokens.",
ollama: "Only selectable for the openai format. Ollama's field name is fixed as max_tokens.",
),
anthropic: t("Only selectable for the openai format. Anthropic's field name is fixed as max_tokens."),
"openai-responses": t("Only selectable for the openai format. The Responses API's field name is fixed as max_output_tokens."),
ollama: t("Only selectable for the openai format. Ollama's field name is fixed as max_tokens."),
};
// LLM profile formats. The default in the create form is "anthropic"; "ollama" is the
// keyless local-server format (base URL defaults to http://127.0.0.1:11434/v1).
type ProfileFormat = "anthropic" | "openai" | "openai-responses" | "ollama";
const OLLAMA_DEFAULT_BASE_URL = "http://127.0.0.1:11434/v1";
const EFFORT_LEVELS: { value: string; label: string }[] = [
{ value: NONE, label: "Not sent (default)" },
{ value: NONE, label: t("Not sent (default)") },
{ value: "low", label: "low" },
{ value: "medium", label: "medium" },
{ value: "high", label: "high" },
@@ -73,8 +80,8 @@ const EFFORT_LEVELS: { value: string; label: string }[] = [
function cooldownText(secs: number) {
if (secs <= 0) return "";
if (secs < 60) return `${secs}s`;
return `${Math.ceil(secs / 60)}min`;
if (secs < 60) return t("{n}s", { n: secs });
return t("{n}min", { n: Math.ceil(secs / 60) });
}
// The "healthy or not" badge a profile shows on its card. A profile without a Key cannot send any request at all — say that before the breaker;
@@ -84,26 +91,26 @@ type Health = { label: string; cls: string; hint?: string };
function healthOf(p: LLMProfile, m?: LLMPoolMember): Health {
if (!p.api_key_hint && p.format !== "ollama") {
return {
label: "No Key configured",
label: t("No Key configured"),
cls: "border-muted-foreground/40 text-muted-foreground",
hint: "No API Key set; cannot be called",
hint: t("No API Key set; cannot be called"),
};
}
if (m?.state === "tripped") {
return {
label: m.cooldown_secs > 0 ? `Tripped · ${cooldownText(m.cooldown_secs)}` : "Tripped",
label: m.cooldown_secs > 0 ? t("Tripped · {cooldown}", { cooldown: cooldownText(m.cooldown_secs) }) : t("Tripped"),
cls: "border-destructive/50 text-destructive",
hint: m.last_error,
};
}
if (m?.state === "degraded") {
return {
label: `Degraded · failed ${m.fails} times`,
label: t("Degraded · failed {count} times", { count: m.fails }),
cls: "border-amber-500/50 text-amber-600 dark:text-amber-400",
hint: m.last_error,
};
}
return { label: "Healthy", cls: "border-emerald-500/50 text-emerald-600 dark:text-emerald-400" };
return { label: t("Healthy"), cls: "border-emerald-500/50 text-emerald-600 dark:text-emerald-400" };
}
// ─────────────────────────────────────────────────────────────────────────────
@@ -137,12 +144,12 @@ function PoolSheet({
await api.setSettings(patch);
await onReload();
if (patch.llm_pool_enabled !== undefined) {
toast.success(patch.llm_pool_enabled ? "LLM pool enabled" : "LLM pool disabled");
toast.success(patch.llm_pool_enabled ? t("LLM pool enabled") : t("LLM pool disabled"));
} else {
toast.success("Fallback settings updated");
toast.success(t("Fallback settings updated"));
}
} catch (e) {
toast.error(`Failed to apply settings: ${(e as Error).message}`);
toast.error(t("Failed to apply settings: {error}", { error: (e as Error).message }));
} finally {
setBusy(false);
}
@@ -152,9 +159,9 @@ function PoolSheet({
try {
await api.resetLLMPool(id);
await onReload();
toast.success(id ? "Profile recovered" : "All profiles recovered");
toast.success(id ? t("Profile recovered") : t("All profiles recovered"));
} catch (e) {
toast.error(`Recovery failed: ${(e as Error).message}`);
toast.error(t("Recovery failed: {error}", { error: (e as Error).message }));
}
}
@@ -169,25 +176,28 @@ function PoolSheet({
<SheetContent side="right" className="flex flex-col gap-0 p-0 data-[side=right]:sm:max-w-lg">
<SheetHeader className="px-4">
<SheetTitle className="flex items-center gap-2">
<ZapIcon className="size-4" /> LLM Pool · Failover
<ZapIcon className="size-4" /> {t("LLM Pool · Failover")}
</SheetTitle>
<SheetDescription>
When enabled, an Agent <b>without a pinned model</b> automatically fails over to the next config when the current one is unusable (insufficient balance / dead Key / rate limiting /
service error).
{rich(
t(
"When enabled, an Agent <b>without a pinned model</b> automatically fails over to the next config when the current one is unusable (insufficient balance / dead Key / rate limiting / service error).",
),
)}
</SheetDescription>
</SheetHeader>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 pb-6">
<div className="flex items-center justify-between gap-4 rounded-lg border p-3">
<div className="grid gap-0.5">
<Label className="text-sm">Enable pool</Label>
<p className="text-muted-foreground text-xs">Off by default. When off, only the active profile is ever used and a failure stays a failure.</p>
<Label className="text-sm">{t("Enable pool")}</Label>
<p className="text-muted-foreground text-xs">{t("Off by default. When off, only the active profile is ever used and a failure stays a failure.")}</p>
</div>
<Switch
checked={enabled}
disabled={busy}
onCheckedChange={(v) => void toggle({ llm_pool_enabled: v })}
aria-label="LLM pool toggle"
aria-label={t("LLM pool toggle")}
/>
</div>
@@ -195,17 +205,18 @@ function PoolSheet({
<>
<div className="flex items-center justify-between gap-4 rounded-lg border p-3">
<div className="grid gap-0.5">
<Label className="text-sm">Also fall back when a pinned config fails</Label>
<Label className="text-sm">{t("Also fall back when a pinned config fails")}</Label>
<p className="text-muted-foreground text-xs">
Off by default: when an Agent or task pins a config, only that config is used and a failure stays a failure (no silent switch to another model).
When enabled, a failing pinned config also falls back to the pool chain below.
{t(
"Off by default: when an Agent or task pins a config, only that config is used and a failure stays a failure (no silent switch to another model). When enabled, a failing pinned config also falls back to the pool chain below.",
)}
</p>
</div>
<Switch
checked={pool?.bind_fallback ?? false}
disabled={busy}
onCheckedChange={(v) => void toggle({ llm_pool_bind_fallback: v })}
aria-label="Bound-config failure fallback toggle"
aria-label={t("Bound-config failure fallback toggle")}
/>
</div>
@@ -213,17 +224,19 @@ function PoolSheet({
<div className="grid gap-2">
<div className="flex items-center justify-between">
<Label className="text-sm">Pool order</Label>
<Label className="text-sm">{t("Pool order")}</Label>
{tripped.length > 0 && (
<Button size="sm" variant="ghost" onClick={() => void recover()}>
<RotateCcwIcon /> Recover all
<RotateCcwIcon /> {t("Recover all")}
</Button>
)}
</div>
{inChain.length < 2 && (
<p className="text-muted-foreground text-xs">
Only {inChain.length} usable profile(s) right now, so the pool has no effect — at least 2 usable profiles (API Key set, or Ollama) with pool participation are
required.
{t(
"Only {count} usable profile(s) right now, so the pool has no effect — at least 2 usable profiles (API Key set, or Ollama) with pool participation are required.",
{ count: inChain.length },
)}
</p>
)}
{chain.map((m) => {
@@ -245,24 +258,28 @@ function PoolSheet({
<span className="font-medium">{m.name}</span>
{m.active && (
<Badge variant="outline" className="border-amber-400/50 text-amber-500">
Active
{t("Active")}
</Badge>
)}
{excluded && <Badge variant="outline">Excluded from pool</Badge>}
{excluded && <Badge variant="outline">{t("Excluded from pool")}</Badge>}
<div className="ml-auto flex items-center gap-2">
{m.state === "tripped" && m.cooldown_secs > 0 && (
<span className="text-muted-foreground text-xs">Cooldown {cooldownText(m.cooldown_secs)}</span>
<span className="text-muted-foreground text-xs">
{t("Cooldown {time}", { time: cooldownText(m.cooldown_secs) })}
</span>
)}
{m.state === "degraded" && (
<span className="text-muted-foreground text-xs">{m.fails} consecutive failures</span>
<span className="text-muted-foreground text-xs">
{t("{count} consecutive failures", { count: m.fails })}
</span>
)}
{m.state !== "ok" && (
<Button
size="icon"
variant="ghost"
className="size-7"
aria-label="Recover now"
title="Recover now: clears the breaker so the next call retries this profile"
aria-label={t("Recover now")}
title={t("Recover now: clears the breaker so the next call retries this profile")}
onClick={() => void recover(m.profile_id)}
>
<RotateCcwIcon className="size-3.5" />
@@ -272,7 +289,7 @@ function PoolSheet({
</div>
<div className="flex flex-wrap items-center gap-x-3 pl-7 text-muted-foreground text-xs">
<code className="truncate font-mono">{m.model}</code>
{!m.active && <span>Priority {m.priority}</span>}
{!m.active && <span>{t("Priority {priority}", { priority: m.priority })}</span>}
</div>
{m.last_error && (
<p className="truncate pl-7 font-mono text-muted-foreground text-xs" title={m.last_error}>
@@ -284,15 +301,15 @@ function PoolSheet({
})}
{chain.length === 0 && (
<div className="rounded-lg border border-dashed p-4 text-center text-muted-foreground text-sm">
No profiles yet
{t("No profiles yet")}
</div>
)}
</div>
<div className="rounded-lg border border-dashed p-3 text-muted-foreground text-xs leading-relaxed">
The active profile is always first; the rest follow priority from high to low (set per profile). After a failure a profile enters a cooldown (60s → 5min →
30min), is skipped while cooling down, and switches back automatically once recovered. Profiles whose context window cannot fit the current request are skipped. Agents
and tasks with a pinned model do not join the pool by default.
{t(
"The active profile is always first; the rest follow priority from high to low (set per profile). After a failure a profile enters a cooldown (60s → 5min → 30min), is skipped while cooling down, and switches back automatically once recovered. Profiles whose context window cannot fit the current request are skipped. Agents and tasks with a pinned model do not join the pool by default.",
)}
</div>
</>
)}
@@ -398,12 +415,12 @@ function ProfileSheet({
if (r.ok && r.models && r.models.length > 0) {
setModels(r.models);
setModelsOpen(true);
toast.success(`Loaded ${r.models.length} models`);
toast.success(t("Loaded {count} models", { count: r.models.length }));
} else {
toast.error(`Failed to load models: ${r.error ?? "no models returned"}`);
toast.error(t("Failed to load models: {error}", { error: r.error ?? t("no models returned") }));
}
} catch (e) {
toast.error(`Error loading models: ${(e as Error).message}`);
toast.error(t("Error loading models: {error}", { error: (e as Error).message }));
} finally {
setLoadingModels(false);
}
@@ -430,12 +447,12 @@ function ProfileSheet({
);
// Show the reply too: only when the model demonstrably spoke is this the same as working inside a session.
if (r.ok)
toast.success(`Connected · ${r.latency_ms ?? "?"}ms · ${r.model ?? model}`, {
description: r.reply ? `Reply: ${r.reply}` : undefined,
toast.success(t("Connected · {latency}ms · {model}", { latency: r.latency_ms ?? "?", model: r.model ?? model }), {
description: r.reply ? t("Reply: {reply}", { reply: r.reply }) : undefined,
});
else toast.error(`Connection failed: ${r.error ?? "unknown"}`);
else toast.error(t("Connection failed: {error}", { error: r.error ?? t("unknown") }));
} catch (e) {
toast.error(`Test error: ${(e as Error).message}`);
toast.error(t("Test error: {error}", { error: (e as Error).message }));
} finally {
setTesting(false);
}
@@ -443,7 +460,7 @@ function ProfileSheet({
async function save() {
if (!name.trim() || !model.trim()) {
toast.error("Please fill in a name and a model");
toast.error(t("Please fill in a name and a model"));
return;
}
if (saving) return;
@@ -473,12 +490,15 @@ function ProfileSheet({
user_agent: userAgent.trim(),
retry,
});
if (isNew) toast.success(`Created: ${name.trim()} (use "Set as active" on its card to enable it)`);
else toast.success(profile?.is_default ? "Saved; the active profile takes effect immediately, no restart needed" : "Saved");
if (isNew) toast.success(t('Created: {name} (use "Set as active" on its card to enable it)', { name: name.trim() }));
else
toast.success(
profile?.is_default ? t("Saved; the active profile takes effect immediately, no restart needed") : t("Saved"),
);
onSaved(String(id));
onOpenChange(false);
} catch (e) {
toast.error(`Save failed: ${(e as Error).message}`);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
}
@@ -486,9 +506,9 @@ function ProfileSheet({
let keyPlaceholder = "sk-…";
if (format === "ollama") {
keyPlaceholder = "optional — a local Ollama server runs keyless";
keyPlaceholder = t("optional — a local Ollama server runs keyless");
} else if (keyHint) {
keyPlaceholder = `Set (${keyHint}); leave empty to keep it`;
keyPlaceholder = t("Set ({hint}); leave empty to keep it", { hint: keyHint });
}
return (
@@ -499,49 +519,49 @@ function ProfileSheet({
>
<SheetHeader className="px-4">
<SheetTitle className="flex items-center gap-2">
{isNew ? "New model profile" : `Edit: ${profile?.name}`}
{isNew ? t("New model profile") : t("Edit: {name}", { name: profile?.name ?? "" })}
{profile?.is_default && (
<Badge variant="outline" className="border-amber-400/50 text-amber-500">
Active
{t("Active")}
</Badge>
)}
</SheetTitle>
<SheetDescription>
{isNew
? "New profiles are not activated automatically; use 'Set as active' on its card to enable it."
: "Click save after editing; saving the active profile takes effect immediately for all agents."}
? t("New profiles are not activated automatically; use 'Set as active' on its card to enable it.")
: t("Click save after editing; saving the active profile takes effect immediately for all agents.")}
</SheetDescription>
</SheetHeader>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="grid gap-2">
<Label htmlFor="p-name">Name</Label>
<Label htmlFor="p-name">{t("Name")}</Label>
<Input
id="p-name"
placeholder="e.g. OpenAI production"
placeholder={t("e.g. OpenAI production")}
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label>Format</Label>
<Label>{t("Format")}</Label>
<Select value={format} onValueChange={(v) => setFormat(v as ProfileFormat)}>
<SelectTrigger>
<SelectValue placeholder="Select a format" />
<SelectValue placeholder={t("Select a format")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="anthropic">Anthropic</SelectItem>
<SelectItem value="openai">OpenAI (Chat Completions)</SelectItem>
<SelectItem value="openai-responses">OpenAI (Responses API)</SelectItem>
<SelectItem value="ollama">Ollama (local, no key needed)</SelectItem>
<SelectItem value="ollama">{t("Ollama (local, no key needed)")}</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="p-model">Model</Label>
<Label htmlFor="p-model">{t("Model")}</Label>
<div className="flex gap-2">
<Input
id="p-model"
@@ -568,7 +588,7 @@ function ProfileSheet({
className="shrink-0"
disabled={loadingModels}
onClick={loadModels}
title="Load available models from the API"
title={t("Load available models from the API")}
>
{loadingModels ? <Loader2Icon className="animate-spin" /> : <RefreshCwIcon />}
</Button>
@@ -579,17 +599,17 @@ function ProfileSheet({
<Input
autoFocus
className="h-8 border-0 shadow-none focus-visible:ring-0 dark:bg-transparent"
placeholder={`Search ${models.length} models…`}
placeholder={t("Search {count} models…", { count: models.length })}
value={modelQuery}
onChange={(e) => setModelQuery(e.target.value)}
spellCheck={false}
aria-label="Search models"
aria-label={t("Search models")}
/>
</div>
<div className="max-h-64 overflow-y-auto overscroll-contain p-1">
{filteredModels.length === 0 ? (
<p className="px-2 py-6 text-center text-muted-foreground text-xs">
No model matches “{modelQuery.trim()}”
{t("No model matches “{query}”", { query: modelQuery.trim() })}
</p>
) : (
filteredModels.map((m) => (
@@ -614,7 +634,7 @@ function ProfileSheet({
</div>
<div className="grid gap-2">
<Label htmlFor="p-base-url">Base URL (optional)</Label>
<Label htmlFor="p-base-url">{t("Base URL (optional)")}</Label>
<Input
id="p-base-url"
className="font-mono"
@@ -625,7 +645,7 @@ function ProfileSheet({
</div>
<div className="grid gap-2">
<Label htmlFor="p-proxy">Proxy (optional)</Label>
<Label htmlFor="p-proxy">{t("Proxy (optional)")}</Label>
<Input
id="p-proxy"
className="font-mono"
@@ -634,45 +654,51 @@ function ProfileSheet({
onChange={(e) => setProxy(e.target.value)}
/>
<p className="text-muted-foreground text-xs">
Only outbound LLM requests go through this proxy; http/https/socks5 are supported, optionally with credentials (e.g.
socks5://user:pass@host:port — URL-encode the password if it contains special characters). Leave empty for no proxy (direct connection).
{t(
"Only outbound LLM requests go through this proxy; http/https/socks5 are supported, optionally with credentials (e.g. socks5://user:pass@host:port — URL-encode the password if it contains special characters). Leave empty for no proxy (direct connection).",
)}
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="p-session-header">Custom session header (optional)</Label>
<Label htmlFor="p-session-header">{t("Custom session header (optional)")}</Label>
<Input
id="p-session-header"
className="font-mono"
placeholder="e.g. x-session-id (empty = not sent)"
placeholder={t("e.g. x-session-id (empty = not sent)")}
value={sessionHeaderKey}
onChange={(e) => setSessionHeaderKey(e.target.value)}
/>
<p className="text-muted-foreground text-xs">
Once a header name is set, every request carries this HTTP header, with the value filled in automatically as the <b>current session's session id</b> (chat sessions like
conv-12, workers like exp3-worker-i87). Meant for gateways that do prompt caching /
sticky routing on a session-id header; stable across turns of one session, distinct across sessions. Leave empty to not send it.
{rich(
t(
"Once a header name is set, every request carries this HTTP header, with the value filled in automatically as the <b>current session's session id</b> (chat sessions like conv-12, workers like exp3-worker-i87). Meant for gateways that do prompt caching / sticky routing on a session-id header; stable across turns of one session, distinct across sessions. Leave empty to not send it.",
),
)}
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="p-user-agent">Custom User-Agent (optional)</Label>
<Label htmlFor="p-user-agent">{t("Custom User-Agent (optional)")}</Label>
<Input
id="p-user-agent"
className="font-mono"
placeholder="e.g. my-app/1.0 (empty = default UA)"
placeholder={t("e.g. my-app/1.0 (empty = default UA)")}
value={userAgent}
onChange={(e) => setUserAgent(e.target.value)}
/>
<p className="text-muted-foreground text-xs">
Overrides the <b>User-Agent</b> header on every outbound LLM request. Useful for gateways that route or allow-list by
User-Agent. Leave empty to keep the default User-Agent unchanged.
{rich(
t(
"Overrides the <b>User-Agent</b> header on every outbound LLM request. Useful for gateways that route or allow-list by User-Agent. Leave empty to keep the default User-Agent unchanged.",
),
)}
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="p-api-key">
{format === "ollama" ? "API Key (optional for Ollama)" : "API Key"}
{format === "ollama" ? t("API Key (optional for Ollama)") : "API Key"}
</Label>
<Input
id="p-api-key"
@@ -692,15 +718,15 @@ function ProfileSheet({
<div className="grid gap-4 sm:grid-cols-3">
<div className="grid gap-2">
<Label htmlFor="p-rps">Rate limit per second</Label>
<Label htmlFor="p-rps">{t("Rate limit per second")}</Label>
<Input id="p-rps" type="number" min={0} value={rps} onChange={(e) => setRps(e.target.value)} />
</div>
<div className="grid gap-2">
<Label htmlFor="p-rpm">Rate limit per minute</Label>
<Label htmlFor="p-rpm">{t("Rate limit per minute")}</Label>
<Input id="p-rpm" type="number" min={0} value={rpm} onChange={(e) => setRpm(e.target.value)} />
</div>
<div className="grid gap-2">
<Label htmlFor="p-cw">Context window (K)</Label>
<Label htmlFor="p-cw">{t("Context window (K)")}</Label>
<Input
id="p-cw"
type="number"
@@ -713,18 +739,21 @@ function ProfileSheet({
</div>
</div>
<p className="-mt-2 text-muted-foreground text-xs">
Rate limits of 0 mean unlimited, shared across all agents. The context window is in K (thousand tokens); 0 = the 200K default, capped at 1000 (i.e.
1M). Setting it too high keeps compression from ever triggering.
{t(
"Rate limits of 0 mean unlimited, shared across all agents. The context window is in K (thousand tokens); 0 = the 200K default, capped at 1000 (i.e. 1M). Setting it too high keeps compression from ever triggering.",
)}
</p>
<div className="grid gap-3 rounded-lg border p-3">
<div className="flex items-center justify-between gap-4">
<div className="grid gap-0.5">
<Label htmlFor="p-priority" className="text-sm">
Pool priority
{t("Pool priority")}
</Label>
<p className="text-muted-foreground text-xs">
Higher numbers are picked first; the active profile is always first regardless of this value. Profiles with equal priority take turns leading, spreading quota naturally.
{t(
"Higher numbers are picked first; the active profile is always first regardless of this value. Profiles with equal priority take turns leading, spreading quota naturally.",
)}
</p>
</div>
<Input
@@ -737,24 +766,25 @@ function ProfileSheet({
</div>
<div className="flex items-center justify-between gap-4 border-t pt-3">
<div className="grid gap-0.5">
<Label className="text-sm">Excluded from pool</Label>
<Label className="text-sm">{t("Excluded from pool")}</Label>
<p className="text-muted-foreground text-xs">
When enabled, this profile is never used as a failover target (Agents / tasks can still pin it explicitly). Suited to expensive profiles reserved for one specific Agent
that should not be burned through by other agents' failures.
{t(
"When enabled, this profile is never used as a failover target (Agents / tasks can still pin it explicitly). Suited to expensive profiles reserved for one specific Agent that should not be burned through by other agents' failures.",
)}
</p>
</div>
<Switch checked={poolExclude} onCheckedChange={setPoolExclude} aria-label="Excluded from pool" />
<Switch checked={poolExclude} onCheckedChange={setPoolExclude} aria-label={t("Excluded from pool")} />
</div>
<div className="flex items-center justify-between gap-4 border-t pt-3">
<div className="grid gap-0.5">
<Label className="text-sm">Streaming output</Label>
<Label className="text-sm">{t("Streaming output")}</Label>
<p className="text-muted-foreground text-xs">
On (default) streams over SSE, with live in-flight progress and real-time token counting. Off uses true non-streaming (stream:false,
returning the full response in one shot) — a way around gateways with broken SSE implementations (empty frames / dropped thinking-field frames),
at the cost of losing live in-flight progress.
{t(
"On (default) streams over SSE, with live in-flight progress and real-time token counting. Off uses true non-streaming (stream:false, returning the full response in one shot) — a way around gateways with broken SSE implementations (empty frames / dropped thinking-field frames), at the cost of losing live in-flight progress.",
)}
</p>
</div>
<Switch checked={streaming} onCheckedChange={setStreaming} aria-label="Streaming output" />
<Switch checked={streaming} onCheckedChange={setStreaming} aria-label={t("Streaming output")} />
</div>
</div>
@@ -762,12 +792,12 @@ function ProfileSheet({
<div className="flex items-center justify-between gap-4">
<div className="grid gap-0.5">
<Label htmlFor="p-max-tokens" className="text-sm">
Output cap · max tokens
{t("Output cap · max tokens")}
</Label>
<p className="text-muted-foreground text-xs">
How many tokens a single reply may generate at most; sent with every request. 0 (default) = the field is not sent, leaving it to the server default.
This is not the same thing as the "context window" above: that is the model's total capacity, used only locally to compute the compression threshold.
Set it too low and a reasoning model gets truncated mid-thinking, unable to emit even a one-word answer.
{t(
'How many tokens a single reply may generate at most; sent with every request. 0 (default) = the field is not sent, leaving it to the server default. This is not the same thing as the "context window" above: that is the model\'s total capacity, used only locally to compute the compression threshold. Set it too low and a reasoning model gets truncated mid-thinking, unable to emit even a one-word answer.',
)}
</p>
</div>
<Input
@@ -782,7 +812,7 @@ function ProfileSheet({
</div>
<div className="flex items-center justify-between gap-4 border-t pt-3">
<div className="grid gap-0.5">
<Label className="text-sm">Cap field name</Label>
<Label className="text-sm">{t("Cap field name")}</Label>
<p className="text-muted-foreground text-xs">{MAX_TOKENS_FIELD_HINTS[format]}</p>
</div>
<Select
@@ -807,10 +837,11 @@ function ProfileSheet({
<div className="grid gap-3 rounded-lg border p-3">
<div className="flex items-center justify-between gap-4">
<div className="grid gap-0.5">
<Label className="text-sm">Thinking switch · thinking.type</Label>
<Label className="text-sm">{t("Thinking switch · thinking.type")}</Label>
<p className="text-muted-foreground text-xs">
Controls whether the thinking field is sent. Not sent = the field is omitted (compatible with models like MiniMax that lack support); Disabled = send
disabled; Enabled = send enabled. Independent of the effort below.
{t(
"Controls whether the thinking field is sent. Not sent = the field is omitted (compatible with models like MiniMax that lack support); Disabled = send disabled; Enabled = send enabled. Independent of the effort below.",
)}
</p>
</div>
<Select value={thinkingType} onValueChange={setThinkingType}>
@@ -828,10 +859,11 @@ function ProfileSheet({
</div>
<div className="flex items-center justify-between gap-4 border-t pt-3">
<div className="grid gap-0.5">
<Label className="text-sm">Thinking effort · reasoning_effort</Label>
<Label className="text-sm">{t("Thinking effort · reasoning_effort")}</Label>
<p className="text-muted-foreground text-xs">
A separate effort knob (OpenAI reasoning_effort / Anthropic output_config.effort). Some APIs have no thinking
field and activate thinking via effort alone, so it can be set on its own without sending the thinking switch.
{t(
"A separate effort knob (OpenAI reasoning_effort / Anthropic output_config.effort). Some APIs have no thinking field and activate thinking via effort alone, so it can be set on its own without sending the thinking switch.",
)}
</p>
</div>
<Select value={effort} onValueChange={setEffort}>
@@ -855,12 +887,12 @@ function ProfileSheet({
<div className="flex gap-2 border-t px-4 py-3">
<Button variant="outline" onClick={testConnection} disabled={testing}>
{testing ? <Loader2Icon className="animate-spin" /> : <PlugZapIcon />}
{testing ? "Testing…" : "Test connection"}
{testing ? t("Testing…") : t("Test connection")}
</Button>
<Button onClick={save} disabled={saving} className="flex-1">
{saving && <Loader2Icon className="animate-spin" />}
{!saving && (isNew ? <PlusIcon /> : <SaveIcon />)}
{isNew ? "Create" : "Save"}
{isNew ? t("Create") : t("Save")}
</Button>
</div>
</SheetContent>
@@ -914,24 +946,24 @@ export default function LLMPage() {
async function activate(id: string, name: string) {
try {
await api.activateLLMProfile(id);
toast.success(`Activated: ${name}`);
toast.success(t("Activated: {name}", { name }));
await load();
} catch (e) {
toast.error(`Activation failed: ${(e as Error).message}`);
toast.error(t("Activation failed: {error}", { error: (e as Error).message }));
}
}
async function remove(p: LLMProfile) {
if (p.is_default) {
toast.error("Cannot delete the active profile");
toast.error(t("Cannot delete the active profile"));
return;
}
try {
await api.deleteLLMProfile(p.id);
toast.success(`Deleted: ${p.name}`);
toast.success(t("Deleted: {name}", { name: p.name }));
await load();
} catch (e) {
toast.error(`Delete failed: ${(e as Error).message}`);
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
}
}
@@ -943,28 +975,30 @@ export default function LLMPage() {
<div>
<h1 className="font-semibold text-xl tracking-tight">LLM</h1>
<p className="text-muted-foreground text-sm">
Format / model / rate-limit settings shared by all agents. Click a card to edit it; the starred card is the active profile.
{t(
"Format / model / rate-limit settings shared by all agents. Click a card to edit it; the starred card is the active profile.",
)}
</p>
</div>
<div className="flex items-center gap-2">
<Button size="sm" variant="outline" onClick={() => setPoolOpen(true)}>
<ZapIcon /> Pool settings
<ZapIcon /> {t("Pool settings")}
{poolOn && (
<Badge variant="outline" className="ml-1 border-emerald-500/50 text-emerald-600 dark:text-emerald-400">
On
{t("On")}
</Badge>
)}
</Button>
<Button size="sm" variant="outline" onClick={() => openEditor(null)}>
<PlusIcon /> Create
<PlusIcon /> {t("Create")}
</Button>
</div>
</div>
<Tabs defaultValue="profiles" className="flex-1">
<TabsList>
<TabsTrigger value="profiles">Model profiles</TabsTrigger>
<TabsTrigger value="retry">Retry & backoff</TabsTrigger>
<TabsTrigger value="profiles">{t("Model profiles")}</TabsTrigger>
<TabsTrigger value="retry">{t("Retry & backoff")}</TabsTrigger>
</TabsList>
<TabsContent value="profiles" className="mt-4">
@@ -1000,7 +1034,7 @@ export default function LLMPage() {
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-2">
<span className="truncate font-medium text-sm">{p.name}</span>
<Badge variant="outline" className="uppercase">
<Badge variant="outline" className="uppercase" lang="en">
{p.format}
</Badge>
<Badge variant="outline" className={cn("ml-auto", h.cls)} title={h.hint}>
@@ -1014,16 +1048,24 @@ export default function LLMPage() {
<div className="flex flex-wrap gap-x-3 gap-y-0.5 pl-6 text-muted-foreground text-xs">
{p.api_key_hint && <span>{p.api_key_hint}</span>}
<span>
{p.rate_per_second}/s · {p.rate_per_minute}/min
{t("{rps}/s · {rpm}/min", { rps: p.rate_per_second, rpm: p.rate_per_minute })}
</span>
{p.proxy && <span className="truncate">Proxy {p.proxy}</span>}
{p.proxy && <span className="truncate">{t("Proxy {proxy}", { proxy: p.proxy })}</span>}
{p.reasoning_effort && (
<span>Thinking {p.reasoning_effort === "off" ? "off" : p.reasoning_effort}</span>
<span>
{t("Thinking {effort}", {
effort: p.reasoning_effort === "off" ? t("off") : p.reasoning_effort,
})}
</span>
)}
{/* The two pool-related fields only matter when the pool is on; when it is off they take no space */}
{poolOn &&
!p.is_default &&
(p.pool_exclude ? <span>Excluded from pool</span> : <span>Priority {p.priority ?? 0}</span>)}
(p.pool_exclude ? (
<span>{t("Excluded from pool")}</span>
) : (
<span>{t("Priority {priority}", { priority: p.priority ?? 0 })}</span>
))}
</div>
<div className="mt-1 flex gap-2">
@@ -1037,12 +1079,12 @@ export default function LLMPage() {
void activate(p.id, p.name);
}}
>
{p.is_default ? "Active" : "Set as active"}
{p.is_default ? t("Active") : t("Set as active")}
</Button>
<Button
size="icon"
variant="outline"
aria-label="Delete profile"
aria-label={t("Delete profile")}
onClick={(e) => {
e.stopPropagation();
void remove(p);
@@ -1057,7 +1099,7 @@ export default function LLMPage() {
})}
{profiles.length === 0 && (
<div className="col-span-full rounded-lg border border-dashed p-10 text-center text-muted-foreground text-sm">
No model profiles yet — click "Create" in the top right to add the first one.
{t('No model profiles yet — click "Create" in the top right to add the first one.')}
</div>
)}
</div>
+12 -11
View File
@@ -7,6 +7,7 @@ import { sseUrl } from "@/lib/api";
import { MOCK } from "@/lib/mock/enabled";
import type { LogLine } from "@/lib/types";
import { cn } from "@/lib/utils";
import { t } from "@/i18n";
// Mock demo: no backend SSE, so stuff in a few sample log lines.
const MOCK_LOGS: LogLine[] = [
@@ -142,13 +143,13 @@ export default function LogsPage() {
return (
<div className="flex flex-1 flex-col gap-3">
<div>
<h1 className="text-xl font-semibold tracking-tight">System logs</h1>
<p className="text-muted-foreground text-sm">Live backend log stream (planner / worker / database / traffic …)</p>
<h1 className="text-xl font-semibold tracking-tight">{t("System logs")}</h1>
<p className="text-muted-foreground text-sm">{t("Live backend log stream (planner / worker / database / traffic …)")}</p>
</div>
<div className="flex flex-1 flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<Input
placeholder="Filter (text / tag)…"
placeholder={t("Filter (text / tag)…")}
value={q}
onChange={(e) => setQ(e.target.value)}
className="h-8 max-w-xs"
@@ -162,7 +163,7 @@ export default function LogsPage() {
className="h-8"
onClick={() => setLevel(lv)}
>
{lv === "all" ? "All" : lv}
{lv === "all" ? t("All") : t(lv)}
</Button>
))}
</div>
@@ -172,15 +173,15 @@ export default function LogsPage() {
className="h-8"
onClick={() => setPaused((p) => !p)}
>
{paused ? "Paused" : "Pause"}
{paused ? t("Paused") : t("Pause")}
</Button>
<Button size="sm" variant="outline" className="h-8" onClick={() => setLines([])}>
Clear
{t("Clear")}
</Button>
<span className="ml-auto text-xs text-muted-foreground">
{counts.total} lines ·{" "}
<span className="text-amber-600 dark:text-amber-400">{counts.warn} warnings</span> ·{" "}
<span className="text-red-600 dark:text-red-400">{counts.error} errors</span>
{t("{count} lines", { count: counts.total })} ·{" "}
<span className="text-amber-600 dark:text-amber-400">{t("{count} warnings", { count: counts.warn })}</span> ·{" "}
<span className="text-red-600 dark:text-red-400">{t("{count} errors", { count: counts.error })}</span>
</span>
</div>
@@ -200,12 +201,12 @@ export default function LogsPage() {
disabled={loadingHistory}
onClick={loadOlderHistory}
>
{loadingHistory ? "Loading…" : "Load older logs"}
{loadingHistory ? t("Loading…") : t("Load older logs")}
</Button>
</div>
)}
{filtered.length === 0 ? (
<p className="py-10 text-center text-muted-foreground">No logs yet.</p>
<p className="py-10 text-center text-muted-foreground">{t("No logs yet.")}</p>
) : (
filtered.map((l) => {
const body =
+57 -52
View File
@@ -20,6 +20,7 @@ import {
SheetDescription,
} from "@/components/ui/sheet";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { intlLocale, t } from "@/i18n";
import { api } from "@/lib/api";
import type { MCPServer, MCPTool, Agent } from "@/lib/types";
@@ -139,15 +140,15 @@ export default function MCPPage() {
async function saveForm() {
if (!form.name.trim()) {
toast.error("Please fill in the name");
toast.error(t("Please fill in the name"));
return;
}
if (form.transport === "stdio" && !form.command.trim()) {
toast.error("Please fill in the command");
toast.error(t("Please fill in the command"));
return;
}
if (form.transport !== "stdio" && !form.url.trim()) {
toast.error("Please fill in the remote URL");
toast.error(t("Please fill in the remote URL"));
return;
}
setSaving(true);
@@ -178,11 +179,11 @@ export default function MCPPage() {
enabled: editing ? editing.enabled : true,
...base,
});
toast.success(editing ? "Saved" : "MCP server added");
toast.success(editing ? t("Saved") : t("MCP server added"));
if (!editing) setOpen(false);
load();
} catch (e) {
toast.error("Save failed: " + (e as Error).message);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
}
@@ -192,12 +193,12 @@ export default function MCPPage() {
if (!editing) return;
setRefreshing(true);
try {
const t = await api.refreshMcpServer(editing.id);
setTools(t);
toast.success(`Found ${t.length} tools`);
const found = await api.refreshMcpServer(editing.id);
setTools(found);
toast.success(t("Found {count} tools", { count: found.length }));
load();
} catch (e) {
toast.error("Refresh failed: " + (e as Error).message);
toast.error(t("Refresh failed: {error}", { error: (e as Error).message }));
} finally {
setRefreshing(false);
}
@@ -206,11 +207,11 @@ export default function MCPPage() {
async function removeServer(s: MCPServer) {
try {
await api.deleteMcpServer(s.id);
toast.success(`Deleted: ${s.name}`);
toast.success(t("Deleted: {name}", { name: s.name }));
setOpen(false);
load();
} catch (e) {
toast.error("Delete failed: " + (e as Error).message);
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
}
}
@@ -219,7 +220,7 @@ export default function MCPPage() {
await api.saveMcpServer({ ...s, enabled: !s.enabled });
load();
} catch (e) {
toast.error("Operation failed: " + (e as Error).message);
toast.error(t("Operation failed: {error}", { error: (e as Error).message }));
}
}
@@ -227,10 +228,14 @@ export default function MCPPage() {
const on = (visibility[serverId] ?? []).includes(agentId);
try {
await api.toggleVisibility(agentId, "mcp", serverId, !on);
toast.success(`${on ? "Revoked" : "Granted"} visibility to "${agentName}"`);
toast.success(
on
? t("Revoked visibility from \"{agent}\"", { agent: agentName })
: t("Granted visibility to \"{agent}\"", { agent: agentName }),
);
load();
} catch (e) {
toast.error("Operation failed: " + (e as Error).message);
toast.error(t("Operation failed: {error}", { error: (e as Error).message }));
}
}
@@ -238,33 +243,33 @@ export default function MCPPage() {
return (
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label>Transport</Label>
<Label>{t("Transport")}</Label>
<div className="flex gap-2">
<Button
type="button"
variant={form.transport === "stdio" ? "default" : "outline"}
onClick={() => setF({ transport: "stdio" })}
>
stdio (local)
{t("stdio (local)")}
</Button>
<Button
type="button"
variant={form.transport === "http" ? "default" : "outline"}
onClick={() => setF({ transport: "http" })}
>
http (remote)
{t("http (remote)")}
</Button>
<Button
type="button"
variant={form.transport === "sse" ? "default" : "outline"}
onClick={() => setF({ transport: "sse" })}
>
sse (legacy)
{t("sse (legacy)")}
</Button>
</div>
</div>
<div className="grid gap-2">
<Label htmlFor="m-name">Name</Label>
<Label htmlFor="m-name">{t("Name")}</Label>
<Input
id="m-name"
placeholder="filesystem"
@@ -275,7 +280,7 @@ export default function MCPPage() {
{form.transport === "stdio" ? (
<>
<div className="grid gap-2">
<Label htmlFor="m-cmd">Command</Label>
<Label htmlFor="m-cmd">{t("Command")}</Label>
<Input
id="m-cmd"
className="font-mono"
@@ -285,7 +290,7 @@ export default function MCPPage() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="m-args">Arguments (space-separated)</Label>
<Label htmlFor="m-args">{t("Arguments (space-separated)")}</Label>
<Input
id="m-args"
className="font-mono"
@@ -297,7 +302,7 @@ export default function MCPPage() {
</>
) : (
<div className="grid gap-2">
<Label htmlFor="m-url">Remote URL</Label>
<Label htmlFor="m-url">{t("Remote URL")}</Label>
<Input
id="m-url"
className="font-mono"
@@ -310,9 +315,9 @@ export default function MCPPage() {
checked={form.insecure}
onCheckedChange={(v) => setF({ insecure: v === true })}
/>
Skip TLS certificate verification (self-signed certs)
{t("Skip TLS certificate verification (self-signed certs)")}
</label>
<Label htmlFor="m-timeout">Request timeout (seconds, default 120)</Label>
<Label htmlFor="m-timeout">{t("Request timeout (seconds, default 120)")}</Label>
<Input
id="m-timeout"
type="number"
@@ -326,8 +331,8 @@ export default function MCPPage() {
<div className="grid gap-2">
<Label htmlFor="m-env">
{form.transport !== "stdio"
? "Request headers (one KEY=VALUE per line, e.g. Authorization=Bearer xxx)"
: "Environment variables (one KEY=VALUE per line)"}
? t("Request headers (one KEY=VALUE per line, e.g. Authorization=Bearer xxx)")
: t("Environment variables (one KEY=VALUE per line)")}
</Label>
<Textarea
id="m-env"
@@ -347,23 +352,23 @@ export default function MCPPage() {
return (
<div className="flex flex-col gap-3 py-4">
<div className="flex items-center justify-between">
<span className="text-muted-foreground text-sm">{tools.length} tools</span>
<span className="text-muted-foreground text-sm">{t("{count} tools", { count: tools.length })}</span>
<Button size="sm" variant="outline" disabled={refreshing} onClick={refreshTools}>
<RefreshCwIcon className={refreshing ? "animate-spin" : ""} /> Refresh
<RefreshCwIcon className={refreshing ? "animate-spin" : ""} /> {t("Refresh")}
</Button>
</div>
{toolsLoading ? (
<p className="text-muted-foreground text-sm">Loading…</p>
<p className="text-muted-foreground text-sm">{t("Loading…")}</p>
) : tools.length === 0 ? (
<p className="text-muted-foreground text-sm">No tools discovered yet; click refresh to fetch again.</p>
<p className="text-muted-foreground text-sm">{t("No tools discovered yet; click refresh to fetch again.")}</p>
) : (
<div className="flex flex-col divide-y">
{tools.map((t) => (
<div key={t.name} className="py-2.5">
<code className="font-mono text-sm">{t.name}</code>
{t.description && (
{tools.map((tool) => (
<div key={tool.name} className="py-2.5">
<code className="font-mono text-sm">{tool.name}</code>
{tool.description && (
<p className="text-muted-foreground mt-0.5 text-xs leading-relaxed">
{t.description}
{tool.description}
</p>
)}
</div>
@@ -378,7 +383,7 @@ export default function MCPPage() {
<div className="flex flex-1 flex-col gap-4 md:gap-6">
<div>
<h1 className="text-xl font-semibold tracking-tight">MCP</h1>
<p className="text-muted-foreground text-sm">External MCP tool servers · visibility granted per agent</p>
<p className="text-muted-foreground text-sm">{t("External MCP tool servers · visibility granted per agent")}</p>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
@@ -388,7 +393,7 @@ export default function MCPPage() {
className="text-foreground/70 border-foreground/70 hover:bg-muted/60 hover:shadow-sm flex min-h-[116px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed transition"
>
<PlusIcon className="size-6" />
<span className="text-sm">Add MCP</span>
<span className="text-sm">{t("Add MCP")}</span>
</button>
{servers.map((s) => (
@@ -401,32 +406,32 @@ export default function MCPPage() {
<div className="flex items-center gap-2">
<ServerIcon className="text-muted-foreground size-4 shrink-0" />
<CardTitle className="truncate text-base">{s.name}</CardTitle>
<Badge variant="outline" className="uppercase">
<Badge variant="outline" className="uppercase" lang="en">
{s.transport}
</Badge>
{s.last_connect_ok === false ? (
<Badge variant="destructive" className="max-w-55 truncate font-normal" title={s.last_connect_err ?? "connect failed"}>
down: {s.last_connect_err ? s.last_connect_err.slice(0, 60) : "connect failed"}
<Badge variant="destructive" className="max-w-55 truncate font-normal" title={s.last_connect_err ?? t("connect failed")}>
{t("down: {error}", { error: s.last_connect_err ? s.last_connect_err.slice(0, 60) : t("connect failed") })}
</Badge>
) : s.last_connect_ok === true ? (
<Badge variant="secondary" className="font-normal">
ok {s.last_connect_at ? new Date(s.last_connect_at).toLocaleTimeString() : ""}
{t("ok {time}", { time: s.last_connect_at ? new Date(s.last_connect_at).toLocaleTimeString(intlLocale) : "" })}
</Badge>
) : (
<Badge variant="outline" className="text-muted-foreground font-normal">
not connected yet
{t("not connected yet")}
</Badge>
)}
<div className="ml-auto flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
<Switch
checked={s.enabled}
onCheckedChange={() => toggleEnabled(s)}
aria-label="Enable"
aria-label={t("Enable")}
/>
<Button
size="icon"
variant="outline"
aria-label="Delete"
aria-label={t("Delete")}
onClick={() => removeServer(s)}
>
<Trash2Icon className="text-destructive" />
@@ -436,10 +441,10 @@ export default function MCPPage() {
</CardHeader>
<CardContent className="grid gap-3">
<p className="text-muted-foreground text-sm">
{s.tools && s.tools.length > 0 ? `${s.tools.length} tools` : "No tools discovered yet"}
{s.tools && s.tools.length > 0 ? t("{count} tools", { count: s.tools.length }) : t("No tools discovered yet")}
</p>
<div className="grid gap-2" onClick={(e) => e.stopPropagation()}>
<span className="text-muted-foreground text-xs">Visibility (granted per agent)</span>
<span className="text-muted-foreground text-xs">{t("Visibility (granted per agent)")}</span>
<div className="flex flex-wrap gap-x-4 gap-y-2">
{agents.map((a) => (
<label key={a.key} className="flex items-center gap-2 text-sm">
@@ -463,9 +468,9 @@ export default function MCPPage() {
className="w-full data-[side=right]:sm:max-w-lg"
>
<SheetHeader>
<SheetTitle>{editing ? editing.name : "Add MCP server"}</SheetTitle>
<SheetTitle>{editing ? editing.name : t("Add MCP server")}</SheetTitle>
<SheetDescription>
stdio (local process) or http (remote Streamable HTTP)
{t("stdio (local process) or http (remote Streamable HTTP)")}
</SheetDescription>
</SheetHeader>
@@ -476,16 +481,16 @@ export default function MCPPage() {
className="flex min-h-0 flex-1 flex-col px-4"
>
<TabsList>
<TabsTrigger value="config">Config</TabsTrigger>
<TabsTrigger value="config">{t("Config")}</TabsTrigger>
<TabsTrigger value="tools">
Tools{tools.length ? ` (${tools.length})` : ""}
{tools.length ? t("Tools ({count})", { count: tools.length }) : t("Tools")}
</TabsTrigger>
</TabsList>
<TabsContent value="config" className="min-h-0 flex-1 overflow-y-auto">
{renderForm()}
<div className="flex gap-2 pt-2 pb-6">
<Button onClick={saveForm} disabled={saving}>
Save
{t("Save")}
</Button>
</div>
</TabsContent>
@@ -498,7 +503,7 @@ export default function MCPPage() {
{renderForm()}
<div className="pt-2 pb-6">
<Button onClick={saveForm} disabled={saving}>
<PlusIcon /> Add
<PlusIcon /> {t("Add")}
</Button>
</div>
</div>
@@ -1,3 +1,5 @@
import { t } from "@/i18n";
// Channel field table and config-value parsing helpers.
//
// This lives apart from the page because it is **data**, not a view: it describes which fields each channel has,
@@ -8,9 +10,9 @@ export const KIND_LABEL: Record<string, string> = {
dingtalk: "DingTalk",
feishu: "Feishu",
wecom: "WeCom",
webhook: "Generic Webhook",
webhook: t("Generic Webhook"),
telegram: "Telegram",
email: "Email",
email: t("Email"),
};
// Config field definitions per channel.
@@ -40,9 +42,9 @@ export const CHANNEL_FIELDS: Record<string, FieldDef[]> = {
},
{
key: "secret",
label: "Signing secret",
label: t("Signing secret"),
kind: "password",
help: "Fill in when the robot's security settings use 'Sign'; leave empty for 'Custom keywords' or when no security setting is enabled",
help: t("Fill in when the robot's security settings use 'Sign'; leave empty for 'Custom keywords' or when no security setting is enabled"),
},
],
feishu: [
@@ -52,7 +54,7 @@ export const CHANNEL_FIELDS: Record<string, FieldDef[]> = {
kind: "text",
placeholder: "https://open.feishu.cn/open-apis/bot/v2/hook/...",
},
{ key: "secret", label: "Signature verification secret", kind: "password", help: "Fill in when the robot enables 'Signature verification'; otherwise leave empty" },
{ key: "secret", label: t("Signature verification secret"), kind: "password", help: t("Fill in when the robot enables 'Signature verification'; otherwise leave empty") },
],
wecom: [
{
@@ -63,27 +65,26 @@ export const CHANNEL_FIELDS: Record<string, FieldDef[]> = {
},
],
webhook: [
{ key: "url", label: "Target URL", kind: "text", placeholder: "https://your-endpoint.example.com/hook" },
{ key: "url", label: t("Target URL"), kind: "text", placeholder: "https://your-endpoint.example.com/hook" },
{
key: "method",
label: "HTTP method",
label: t("HTTP method"),
kind: "select",
options: [
{ value: "POST", label: "POST (with body)" },
{ value: "PUT", label: "PUT (with body)" },
{ value: "PATCH", label: "PATCH (with body)" },
{ value: "GET", label: "GET (no body)" },
{ value: "POST", label: t("POST (with body)") },
{ value: "PUT", label: t("PUT (with body)") },
{ value: "PATCH", label: t("PATCH (with body)") },
{ value: "GET", label: t("GET (no body)") },
],
},
{ key: "headers", label: "Custom headers", kind: "kv", help: "One KEY=VALUE per line, e.g. Authorization=Bearer xxx" },
{ key: "headers", label: t("Custom headers"), kind: "kv", help: t("One KEY=VALUE per line, e.g. Authorization=Bearer xxx") },
{
key: "body_template",
label: "Body template",
label: t("Body template"),
kind: "textarea",
help:
"Leave empty to use the built-in default template. Variables: {{.Title}} {{.Batch}} {{.Count}} {{.HomeURL}} {{.SentAt}}, " +
"plus .Name/.VulnClass/.Severity/.Summary/.Assets/.DetailURL/.StatusLabel under range .Items. " +
"Use {{json .Xxx}} instead of {{.Xxx}} to insert strings, or quotes in titles will break the JSON.",
help: t(
"Leave empty to use the built-in default template. Variables: {{.Title}} {{.Batch}} {{.Count}} {{.HomeURL}} {{.SentAt}}, plus .Name/.VulnClass/.Severity/.Summary/.Assets/.DetailURL/.StatusLabel under range .Items. Use {{json .Xxx}} instead of {{.Xxx}} to insert strings, or quotes in titles will break the JSON.",
),
},
],
telegram: [
@@ -94,32 +95,32 @@ export const CHANNEL_FIELDS: Record<string, FieldDef[]> = {
label: "API URL",
kind: "text",
placeholder: "https://api.telegram.org",
help: "Leave empty for the official URL; fill in when proxying a self-hosted Bot API",
help: t("Leave empty for the official URL; fill in when proxying a self-hosted Bot API"),
},
],
email: [
{ key: "host", label: "SMTP server", kind: "text", placeholder: "smtp.example.com" },
{ key: "host", label: t("SMTP server"), kind: "text", placeholder: "smtp.example.com" },
{
key: "port",
label: "Port",
label: t("Port"),
kind: "number",
placeholder: "587",
help: "587 uses STARTTLS; for 465 turn 'Implicit TLS' on",
help: t("587 uses STARTTLS; for 465 turn 'Implicit TLS' on"),
},
{ key: "username", label: "Account", kind: "text" },
{ key: "password", label: "Password / auth code", kind: "password" },
{ key: "from", label: "From", kind: "text", placeholder: "artex@example.com" },
{ key: "to", label: "Recipients", kind: "list", help: "Separate multiple addresses with commas" },
{ key: "tls", label: "Implicit TLS", kind: "switch", help: "On for port 465; keep off for 587 (STARTTLS is automatic)" },
{ key: "username", label: t("Account"), kind: "text" },
{ key: "password", label: t("Password / auth code"), kind: "password" },
{ key: "from", label: t("From"), kind: "text", placeholder: "artex@example.com" },
{ key: "to", label: t("Recipients"), kind: "list", help: t("Separate multiple addresses with commas") },
{ key: "tls", label: t("Implicit TLS"), kind: "switch", help: t("On for port 465; keep off for 587 (STARTTLS is automatic)") },
],
};
export const SEVERITY_OPTIONS = [
{ value: "", label: "All severities" },
{ value: "low", label: "Low and above" },
{ value: "medium", label: "Medium and above" },
{ value: "high", label: "High and above" },
{ value: "critical", label: "Critical only" },
{ value: "", label: t("All severities") },
{ value: "low", label: t("Low and above") },
{ value: "medium", label: t("Medium and above") },
{ value: "high", label: t("High and above") },
{ value: "critical", label: t("Critical only") },
];
export type ChannelForm = {
@@ -156,10 +157,10 @@ export const emptyForm = (kind: string): ChannelForm => ({
export function parseKV(text: string): Record<string, string> {
const out: Record<string, string> = {};
for (const line of text.split("\n")) {
const t = line.trim();
if (!t) continue;
const i = t.indexOf("=");
if (i > 0) out[t.slice(0, i).trim()] = t.slice(i + 1).trim();
const ln = line.trim();
if (!ln) continue;
const i = ln.indexOf("=");
if (i > 0) out[ln.slice(0, i).trim()] = ln.slice(i + 1).trim();
}
return out;
}
@@ -7,6 +7,7 @@ import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { t } from "@/i18n";
import type { NotificationFilter } from "@/lib/types";
// asText / inputType are value helpers local to this file (tightly coupled to control rendering); they do not belong in channel-fields.
@@ -120,7 +121,9 @@ export function ConfigField({
const hint = masked ? (
<p className="text-muted-foreground flex items-center gap-1 text-xs">
<CheckIcon className="size-3" />
Saved{maskedTail ? ` (tail ${maskedTail})` : ""} · enter a new value to overwrite, clear to remove it
{maskedTail
? t("Saved (tail {tail}) · enter a new value to overwrite, clear to remove it", { tail: maskedTail })
: t("Saved · enter a new value to overwrite, clear to remove it")}
</p>
) : (
def.help && <p className="text-muted-foreground text-xs">{def.help}</p>
@@ -141,13 +144,13 @@ export function FilterSummary({ filter }: { filter: NotificationFilter }) {
if (filter.min_severity) {
parts.push(SEVERITY_OPTIONS.find((o) => o.value === filter.min_severity)?.label ?? filter.min_severity);
}
if (filter.vulnclass_include?.length) parts.push(`${filter.vulnclass_include.length} type keywords`);
if (filter.vulnclass_exclude?.length) parts.push(`excludes ${filter.vulnclass_exclude.length} keywords`);
if (filter.task_ids?.length) parts.push(`${filter.task_ids.length} tasks`);
if (filter.asset_ids?.length) parts.push(`${filter.asset_ids.length} assets`);
if (filter.on_status_change) parts.push("includes status changes");
if (filter.vulnclass_include?.length) parts.push(t("{count} type keywords", { count: filter.vulnclass_include.length }));
if (filter.vulnclass_exclude?.length) parts.push(t("excludes {count} keywords", { count: filter.vulnclass_exclude.length }));
if (filter.task_ids?.length) parts.push(t("{count} tasks", { count: filter.task_ids.length }));
if (filter.asset_ids?.length) parts.push(t("{count} assets", { count: filter.asset_ids.length }));
if (filter.on_status_change) parts.push(t("includes status changes"));
if (parts.length === 0) {
return <p className="text-muted-foreground text-sm">All vulnerabilities</p>;
return <p className="text-muted-foreground text-sm">{t("All vulnerabilities")}</p>;
}
return <p className="text-muted-foreground text-sm">{parts.join(" · ")}</p>;
}
@@ -10,6 +10,7 @@ import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { intlLocale, t } from "@/i18n";
import { api } from "@/lib/api";
import { statusMeta, toneClasses } from "@/lib/status";
import type { NotificationChannel, NotificationDelivery } from "@/lib/types";
@@ -32,7 +33,7 @@ export function DeliveryList({ channels }: { channels: NotificationChannel[] })
setRows(r.deliveries);
setTotal(r.total);
})
.catch((e) => toast.error("Failed to load delivery records: " + (e as Error).message))
.catch((e) => toast.error(t("Failed to load delivery records: {error}", { error: (e as Error).message })))
.finally(() => setLoading(false));
}, [channelID, state, page]);
React.useEffect(() => {
@@ -42,10 +43,10 @@ export function DeliveryList({ channels }: { channels: NotificationChannel[] })
async function retry(id: number) {
try {
await api.notifyRetryDelivery(id);
toast.success("Re-queued");
toast.success(t("Re-queued"));
load();
} catch (e) {
toast.error("Retry failed: " + (e as Error).message);
toast.error(t("Retry failed: {error}", { error: (e as Error).message }));
}
}
@@ -62,10 +63,10 @@ export function DeliveryList({ channels }: { channels: NotificationChannel[] })
}}
>
<SelectTrigger size="sm" className="w-44">
<SelectValue placeholder="All channels" />
<SelectValue placeholder={t("All channels")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All channels</SelectItem>
<SelectItem value="all">{t("All channels")}</SelectItem>
{channels.map((c) => (
<SelectItem key={c.id} value={String(c.id)}>
{c.name}
@@ -81,10 +82,10 @@ export function DeliveryList({ channels }: { channels: NotificationChannel[] })
}}
>
<SelectTrigger size="sm" className="w-32">
<SelectValue placeholder="All statuses" />
<SelectValue placeholder={t("All statuses")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All statuses</SelectItem>
<SelectItem value="all">{t("All statuses")}</SelectItem>
{["pending", "sending", "sent", "failed", "skipped"].map((s) => (
<SelectItem key={s} value={s}>
{statusMeta("delivery", s).label}
@@ -93,21 +94,21 @@ export function DeliveryList({ channels }: { channels: NotificationChannel[] })
</SelectContent>
</Select>
<Button size="sm" variant="outline" onClick={load} disabled={loading}>
<RefreshCwIcon className={loading ? "animate-spin" : ""} /> Refresh
<RefreshCwIcon className={loading ? "animate-spin" : ""} /> {t("Refresh")}
</Button>
<span className="text-muted-foreground ml-auto text-xs">{total} in total</span>
<span className="text-muted-foreground ml-auto text-xs">{t("{count} in total", { count: total })}</span>
</div>
<Card className="py-0">
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-40">Time</TableHead>
<TableHead>Vulnerability</TableHead>
<TableHead className="w-40">Channel</TableHead>
<TableHead className="w-24">Status</TableHead>
<TableHead className="w-16">Attempts</TableHead>
<TableHead>Error</TableHead>
<TableHead className="w-40">{t("Time")}</TableHead>
<TableHead>{t("Vulnerability")}</TableHead>
<TableHead className="w-40">{t("Channel")}</TableHead>
<TableHead className="w-24">{t("Status")}</TableHead>
<TableHead className="w-16">{t("Attempts")}</TableHead>
<TableHead>{t("Error")}</TableHead>
<TableHead className="w-20" />
</TableRow>
</TableHeader>
@@ -115,7 +116,7 @@ export function DeliveryList({ channels }: { channels: NotificationChannel[] })
{rows.length === 0 ? (
<TableRow>
<TableCell colSpan={7} className="text-muted-foreground py-8 text-center">
{loading ? "Loading…" : "No delivery records"}
{loading ? t("Loading…") : t("No delivery records")}
</TableCell>
</TableRow>
) : (
@@ -129,10 +130,10 @@ export function DeliveryList({ channels }: { channels: NotificationChannel[] })
<Badge variant="outline" className={toneClasses[statusMeta("severity", d.severity).tone]}>
{statusMeta("severity", d.severity).label}
</Badge>
<span className="truncate text-sm">{d.title || "(untitled)"}</span>
<span className="truncate text-sm">{d.title || t("(untitled)")}</span>
{d.event_kind === "finding_status_changed" && (
<Badge variant="outline" className="shrink-0">
Status change
{t("Status change")}
</Badge>
)}
</div>
@@ -149,7 +150,7 @@ export function DeliveryList({ channels }: { channels: NotificationChannel[] })
{/* Only failed/skipped items get a retry button: re-sending a delivered one would duplicate the push. */}
{(d.state === "failed" || d.state === "skipped") && (
<Button size="sm" variant="outline" onClick={() => retry(d.id)}>
<RotateCcwIcon /> Retry
<RotateCcwIcon /> {t("Retry")}
</Button>
)}
</TableCell>
@@ -163,13 +164,13 @@ export function DeliveryList({ channels }: { channels: NotificationChannel[] })
{maxPage > 1 && (
<div className="flex items-center justify-end gap-2">
<Button size="sm" variant="outline" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
Previous
{t("Previous")}
</Button>
<span className="text-muted-foreground text-sm">
{page} / {maxPage}
</span>
<Button size="sm" variant="outline" disabled={page >= maxPage} onClick={() => setPage((p) => p + 1)}>
Next
{t("Next")}
</Button>
</div>
)}
@@ -180,5 +181,5 @@ export function DeliveryList({ channels }: { channels: NotificationChannel[] })
function formatTime(iso: string): string {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return iso;
return d.toLocaleString("zh-CN", { hour12: false });
return d.toLocaleString(intlLocale, { hour12: false });
}
@@ -1,4 +1,5 @@
import { Card, CardContent } from "@/components/ui/card";
import { t } from "@/i18n";
export function StatTile({ label, value, hint, tone }: { label: string; value: string; hint?: string; tone?: string }) {
return (
@@ -15,7 +16,7 @@ export function StatTile({ label, value, hint, tone }: { label: string; value: s
// formatBacklog renders backlog milliseconds as a human-readable magnitude.
export function formatBacklog(ms: number): string {
if (!ms) return "—";
if (ms < 60_000) return `${Math.round(ms / 1000)}s`;
if (ms < 3_600_000) return `${Math.round(ms / 60_000)}min`;
return `${(ms / 3_600_000).toFixed(1)}h`;
if (ms < 60_000) return t("{n}s", { n: Math.round(ms / 1000) });
if (ms < 3_600_000) return t("{n}min", { n: Math.round(ms / 60_000) });
return t("{n}h", { n: (ms / 3_600_000).toFixed(1) });
}
+76 -74
View File
@@ -15,6 +15,7 @@ import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { NotificationChannel, NotificationFilter, NotificationMeta } from "@/lib/types";
@@ -73,7 +74,7 @@ export default function NotifyPage() {
setBaseURL(m.public_base_url);
setDigestMin(m.digest_interval_min);
})
.catch((e) => toast.error("Failed to load notification settings: " + (e as Error).message));
.catch((e) => toast.error(t("Failed to load notification settings: {error}", { error: (e as Error).message })));
// The two render limits are not part of /notify/meta; they are only exposed through /api/settings.
api
.settings()
@@ -81,13 +82,13 @@ export default function NotifyPage() {
setSummaryMax(String(s.notify_summary_max_runes ?? ""));
setAssetsMax(String(s.notify_assets_max_shown ?? ""));
})
.catch((e) => toast.error(`Failed to load message limits: ${(e as Error).message}`));
.catch((e) => toast.error(t("Failed to load message limits: {error}", { error: (e as Error).message })));
// Channel-list load failures must be reported: failing silently would render as "no channels at all",
// and users would think their config was lost — scarier than a straight-up error.
api
.notifyChannels()
.then(setChannels)
.catch((e) => toast.error("Failed to load channels: " + (e as Error).message));
.catch((e) => toast.error(t("Failed to load channels: {error}", { error: (e as Error).message })));
}, []);
React.useEffect(() => {
load();
@@ -187,7 +188,7 @@ export default function NotifyPage() {
async function saveForm() {
if (!form.name.trim()) {
toast.error("Please fill in a channel name");
toast.error(t("Please fill in a channel name"));
return;
}
setSaving(true);
@@ -203,16 +204,16 @@ export default function NotifyPage() {
};
if (editing) {
await api.notifyUpdateChannel(editing.id, payload);
toast.success("Saved");
toast.success(t("Saved"));
setOpen(false);
} else {
await api.notifyCreateChannel(payload);
toast.success("Channel added");
toast.success(t("Channel added"));
setOpen(false);
}
load();
} catch (e) {
toast.error("Save failed: " + (e as Error).message);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
}
@@ -223,10 +224,10 @@ export default function NotifyPage() {
setTesting(true);
try {
const r = await api.notifyTestChannel(editing.id);
toast.success(`Test message sent (${r.latency_ms} ms); check the group to confirm`);
toast.success(t("Test message sent ({ms} ms); check the group to confirm", { ms: r.latency_ms }));
} catch (e) {
// The backend relays the raw error returned by the channel verbatim — the only clue for debugging the config — so show it as-is.
toast.error("Test failed: " + (e as Error).message, { duration: 12000 });
toast.error(t("Test failed: {error}", { error: (e as Error).message }), { duration: 12000 });
} finally {
setTesting(false);
}
@@ -235,11 +236,11 @@ export default function NotifyPage() {
async function removeChannel(ch: NotificationChannel) {
try {
await api.notifyDeleteChannel(ch.id);
toast.success(`Deleted: ${ch.name}`);
toast.success(t("Deleted: {name}", { name: ch.name }));
setOpen(false);
load();
} catch (e) {
toast.error("Delete failed: " + (e as Error).message);
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
}
}
@@ -248,7 +249,7 @@ export default function NotifyPage() {
await api.notifyUpdateChannel(ch.id, { enabled: !ch.enabled });
load();
} catch (e) {
toast.error("Operation failed: " + (e as Error).message);
toast.error(t("Operation failed: {error}", { error: (e as Error).message }));
}
}
@@ -257,9 +258,9 @@ export default function NotifyPage() {
try {
await api.setSettings({ notify_enabled: on });
setMeta((m) => (m ? { ...m, enabled: on } : m));
toast.success(on ? "Push enabled" : "Push paused");
toast.success(on ? t("Push enabled") : t("Push paused"));
} catch (e) {
toast.error("Operation failed: " + (e as Error).message);
toast.error(t("Operation failed: {error}", { error: (e as Error).message }));
} finally {
setGlobalSaving(false);
}
@@ -269,11 +270,11 @@ export default function NotifyPage() {
// Checked before anything is sent: the backend applies the fields of one PUT in order,
// so a 400 on a limit would leave the URL and digest interval already saved.
if (limitInvalid(summaryMax, SUMMARY_LIMIT_MAX)) {
toast.error(`Summary length must be a whole number between 0 and ${SUMMARY_LIMIT_MAX}`);
toast.error(t("Summary length must be a whole number between 0 and {max}", { max: SUMMARY_LIMIT_MAX }));
return;
}
if (limitInvalid(assetsMax, ASSETS_LIMIT_MAX)) {
toast.error(`Assets listed must be a whole number between 0 and ${ASSETS_LIMIT_MAX}`);
toast.error(t("Assets listed must be a whole number between 0 and {max}", { max: ASSETS_LIMIT_MAX }));
return;
}
setGlobalSaving(true);
@@ -284,10 +285,10 @@ export default function NotifyPage() {
if (summaryMax.trim() !== "") patch.notify_summary_max_runes = Number(summaryMax);
if (assetsMax.trim() !== "") patch.notify_assets_max_shown = Number(assetsMax);
await api.setSettings(patch);
toast.success("Saved");
toast.success(t("Saved"));
load();
} catch (e) {
toast.error("Save failed: " + (e as Error).message);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setGlobalSaving(false);
}
@@ -301,21 +302,21 @@ export default function NotifyPage() {
<div className="flex flex-1 flex-col gap-4 md:gap-6">
<div className="flex items-start justify-between gap-4">
<div>
<h1 className="text-xl font-semibold tracking-tight">Notifications</h1>
<h1 className="text-xl font-semibold tracking-tight">{t("Notifications")}</h1>
<p className="text-muted-foreground text-sm">
Push findings to DingTalk / Feishu / WeCom and other channels · each channel has its own delivery timing and filter rules
{t("Push findings to DingTalk / Feishu / WeCom and other channels · each channel has its own delivery timing and filter rules")}
</p>
</div>
{meta && (
// A div, not a label: the Switch carries its own aria-label, and wrapping it in a label
// would associate it with no native control while making the text look like it should toggle.
<div className="flex shrink-0 items-center gap-2 text-sm">
<span className="text-muted-foreground">Master switch</span>
<span className="text-muted-foreground">{t("Master switch")}</span>
<Switch
checked={meta.enabled}
disabled={globalSaving}
onCheckedChange={toggleGlobal}
aria-label="Push master switch"
aria-label={t("Push master switch")}
/>
</div>
)}
@@ -323,15 +324,15 @@ export default function NotifyPage() {
{meta && (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
<StatTile label="Channels" value={`${meta.stats.channels_on} / ${meta.stats.channels}`} hint="On / total" />
<StatTile label="Sent today" value={String(meta.stats.sent_today)} />
<StatTile label="Pending" value={String(meta.stats.pending)} />
<StatTile label="Failed" value={String(meta.stats.failed)} tone={meta.stats.failed > 0 ? "red" : undefined} />
<StatTile label={t("Channels")} value={`${meta.stats.channels_on} / ${meta.stats.channels}`} hint={t("On / total")} />
<StatTile label={t("Sent today")} value={String(meta.stats.sent_today)} />
<StatTile label={t("Pending")} value={String(meta.stats.pending)} />
<StatTile label={t("Failed")} value={String(meta.stats.failed)} tone={meta.stats.failed > 0 ? "red" : undefined} />
<StatTile
label="Oldest backlog"
label={t("Oldest backlog")}
value={formatBacklog(meta.stats.backlog_age_ms)}
// Backlog age is far more useful than backlog count: 3 backlogged items could mean 3 seconds or 3 hours.
hint={meta.stats.backlog_age_ms > 5 * 60_000 ? "Push may be stuck" : undefined}
hint={meta.stats.backlog_age_ms > 5 * 60_000 ? t("Push may be stuck") : undefined}
tone={meta.stats.backlog_age_ms > 5 * 60_000 ? "red" : undefined}
/>
</div>
@@ -339,21 +340,21 @@ export default function NotifyPage() {
<Card className="gap-3">
<CardHeader>
<CardTitle className="text-base">Global settings</CardTitle>
<CardTitle className="text-base">{t("Global settings")}</CardTitle>
</CardHeader>
<CardContent className="grid gap-4 sm:grid-cols-2">
<div className="grid gap-2">
<Label htmlFor="n-base">Link-back URL</Label>
<Label htmlFor="n-base">{t("Link-back URL")}</Label>
<Input
id="n-base"
placeholder="https://artex.example.com"
value={baseURL}
onChange={(e) => setBaseURL(e.target.value)}
/>
<p className="text-muted-foreground text-xs">The address the "View details" button in messages points to. Leave empty to omit the button.</p>
<p className="text-muted-foreground text-xs">{t("The address the \"View details\" button in messages points to. Leave empty to omit the button.")}</p>
</div>
<div className="grid gap-2">
<Label htmlFor="n-digest">Digest interval (minutes)</Label>
<Label htmlFor="n-digest">{t("Digest interval (minutes)")}</Label>
<Input
id="n-digest"
type="number"
@@ -363,10 +364,10 @@ export default function NotifyPage() {
value={digestMin}
onChange={(e) => setDigestMin(e.target.value)}
/>
<p className="text-muted-foreground text-xs">Only applies to channels in "digest" mode.</p>
<p className="text-muted-foreground text-xs">{t("Only applies to channels in \"digest\" mode.")}</p>
</div>
<div className="grid gap-2">
<Label htmlFor="n-summary-max">Summary length (characters)</Label>
<Label htmlFor="n-summary-max">{t("Summary length (characters)")}</Label>
<Input
id="n-summary-max"
type="number"
@@ -379,11 +380,11 @@ export default function NotifyPage() {
aria-invalid={limitInvalid(summaryMax, SUMMARY_LIMIT_MAX)}
/>
<p className="text-muted-foreground text-xs">
Longest finding summary shown in a message, 0–{SUMMARY_LIMIT_MAX}. 0 = no truncation.
{t("Longest finding summary shown in a message, 0–{max}. 0 = no truncation.", { max: SUMMARY_LIMIT_MAX })}
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="n-assets-max">Assets listed per finding</Label>
<Label htmlFor="n-assets-max">{t("Assets listed per finding")}</Label>
<Input
id="n-assets-max"
type="number"
@@ -396,12 +397,12 @@ export default function NotifyPage() {
aria-invalid={limitInvalid(assetsMax, ASSETS_LIMIT_MAX)}
/>
<p className="text-muted-foreground text-xs">
Most asset names listed for a finding, 0–{ASSETS_LIMIT_MAX}. 0 = no truncation (all assets listed).
{t("Most asset names listed for a finding, 0–{max}. 0 = no truncation (all assets listed).", { max: ASSETS_LIMIT_MAX })}
</p>
</div>
<div className="sm:col-span-2">
<Button onClick={saveGlobal} disabled={globalSaving}>
Save global settings
{t("Save global settings")}
</Button>
</div>
</CardContent>
@@ -409,8 +410,8 @@ export default function NotifyPage() {
<Tabs value={tab} onValueChange={(v) => setTab(v as "channels" | "deliveries")} className="flex flex-col gap-4">
<TabsList>
<TabsTrigger value="channels">Channels</TabsTrigger>
<TabsTrigger value="deliveries">Delivery log</TabsTrigger>
<TabsTrigger value="channels">{t("Channels")}</TabsTrigger>
<TabsTrigger value="deliveries">{t("Delivery log")}</TabsTrigger>
</TabsList>
<TabsContent value="channels">
@@ -421,7 +422,7 @@ export default function NotifyPage() {
className="text-foreground/70 border-foreground/70 hover:bg-muted/60 hover:shadow-sm flex min-h-[130px] flex-col items-center justify-center gap-2 rounded-xl border border-dashed transition"
>
<PlusIcon className="size-6" />
<span className="text-sm">Add channel</span>
<span className="text-sm">{t("Add channel")}</span>
</button>
{channels.map((ch) => (
@@ -443,12 +444,12 @@ export default function NotifyPage() {
checked={ch.enabled}
onCheckedChange={() => toggleEnabled(ch)}
onClick={(e) => e.stopPropagation()}
aria-label="Enable"
aria-label={t("Enable")}
/>
<Button
size="icon"
variant="outline"
aria-label="Delete"
aria-label={t("Delete")}
onClick={(e) => {
e.stopPropagation();
// void explicitly discards the Promise: removeChannel catches and toasts on its own,
@@ -464,8 +465,8 @@ export default function NotifyPage() {
<CardContent className="grid gap-3">
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline">{KIND_LABEL[ch.kind] ?? ch.kind}</Badge>
<Badge variant="outline">{ch.mode === "digest" ? "Digest" : "Realtime"}</Badge>
{!ch.enabled && <Badge variant="outline">Disabled</Badge>}
<Badge variant="outline">{ch.mode === "digest" ? t("Digest") : t("Realtime")}</Badge>
{!ch.enabled && <Badge variant="outline">{t("Disabled")}</Badge>}
</div>
<FilterSummary filter={ch.filter} />
</CardContent>
@@ -482,17 +483,18 @@ export default function NotifyPage() {
<Sheet open={open} onOpenChange={setOpen}>
<SheetContent side="right" className="w-full data-[side=right]:sm:max-w-lg">
<SheetHeader>
<SheetTitle>{editing ? editing.name : "Add notification channel"}</SheetTitle>
<SheetTitle>{editing ? editing.name : t("Add notification channel")}</SheetTitle>
<SheetDescription>
{KIND_LABEL[form.kind] ?? form.kind}
{defaultRate > 0 ? ` · default rate limit ${defaultRate}/min` : " · no rate limit"}
{" · "}
{defaultRate > 0 ? t("default rate limit {rate}/min", { rate: defaultRate }) : t("no rate limit")}
</SheetDescription>
</SheetHeader>
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-4">
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label>Channel type</Label>
<Label>{t("Channel type")}</Label>
<Select
value={form.kind}
onValueChange={(v) => {
@@ -514,16 +516,16 @@ export default function NotifyPage() {
</Select>
{editing && (
<p className="text-muted-foreground text-xs">
The channel type cannot be changed — a different type means a different set of credentials; create a new channel instead.
{t("The channel type cannot be changed — a different type means a different set of credentials; create a new channel instead.")}
</p>
)}
</div>
<div className="grid gap-2">
<Label htmlFor="n-name">Channel name</Label>
<Label htmlFor="n-name">{t("Channel name")}</Label>
<Input
id="n-name"
placeholder="Incident response group / Daily broadcast group"
placeholder={t("Incident response group / Daily broadcast group")}
value={form.name}
onChange={(e) => setF({ name: e.target.value })}
/>
@@ -531,7 +533,7 @@ export default function NotifyPage() {
{fields.length === 0 ? (
<p className="text-muted-foreground text-sm">
The form for this channel type is not defined yet (the frontend is missing a CHANNEL_FIELDS entry); add it and retry.
{t("The form for this channel type is not defined yet (the frontend is missing a CHANNEL_FIELDS entry); add it and retry.")}
</p>
) : (
fields.map((d) => (
@@ -546,41 +548,41 @@ export default function NotifyPage() {
)}
<div className="grid gap-2">
<Label>Delivery timing</Label>
<Label>{t("Delivery timing")}</Label>
<Select value={form.mode} onValueChange={(v) => setF({ mode: v as "realtime" | "digest" })}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="realtime">Realtime · one message per finding</SelectItem>
<SelectItem value="digest">Digest · merged into one message per interval</SelectItem>
<SelectItem value="realtime">{t("Realtime · one message per finding")}</SelectItem>
<SelectItem value="digest">{t("Digest · merged into one message per interval")}</SelectItem>
</SelectContent>
</Select>
<p className="text-muted-foreground text-xs">
For "realtime for High, digest for the rest", create two channels: one realtime with a High threshold, one digest with no severity limit.
{t("For \"realtime for High, digest for the rest\", create two channels: one realtime with a High threshold, one digest with no severity limit.")}
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="n-rate">Rate limit (messages/min)</Label>
<Label htmlFor="n-rate">{t("Rate limit (messages/min)")}</Label>
<Input
id="n-rate"
type="number"
min={0}
placeholder={defaultRate > 0 ? String(defaultRate) : "0 = unlimited"}
placeholder={defaultRate > 0 ? String(defaultRate) : t("0 = unlimited")}
value={form.ratePerMin}
onChange={(e) => setF({ ratePerMin: e.target.value })}
/>
<p className="text-muted-foreground text-xs">
Leave empty to use the channel default; 0 means no limit. Going over the limit never drops messages, only delays them.
{t("Leave empty to use the channel default; 0 means no limit. Going over the limit never drops messages, only delays them.")}
</p>
</div>
<div className="border-t pt-4">
<p className="mb-3 text-sm font-medium">Filter rules (empty = no filtering)</p>
<p className="mb-3 text-sm font-medium">{t("Filter rules (empty = no filtering)")}</p>
<div className="grid gap-4">
<div className="grid gap-2">
<Label>Minimum severity</Label>
<Label>{t("Minimum severity")}</Label>
<Select
value={form.minSeverity || "all"}
onValueChange={(v) => setF({ minSeverity: v === "all" ? "" : v })}
@@ -598,7 +600,7 @@ export default function NotifyPage() {
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor="n-inc">Only these vulnerability types</Label>
<Label htmlFor="n-inc">{t("Only these vulnerability types")}</Label>
<Textarea
id="n-inc"
placeholder={"SQL injection\ncommand execution"}
@@ -606,21 +608,21 @@ export default function NotifyPage() {
onChange={(e) => setF({ includeText: e.target.value })}
/>
<p className="text-muted-foreground text-xs">
One keyword per line, matched case-insensitively as a substring. Leave empty for all types.
{t("One keyword per line, matched case-insensitively as a substring. Leave empty for all types.")}
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="n-exc">Exclude these vulnerability types</Label>
<Label htmlFor="n-exc">{t("Exclude these vulnerability types")}</Label>
<Textarea
id="n-exc"
placeholder={"Information disclosure"}
value={form.excludeText}
onChange={(e) => setF({ excludeText: e.target.value })}
/>
<p className="text-muted-foreground text-xs">Exclusion beats inclusion: an item matching both is excluded.</p>
<p className="text-muted-foreground text-xs">{t("Exclusion beats inclusion: an item matching both is excluded.")}</p>
</div>
<div className="grid gap-2">
<Label htmlFor="n-tasks">Restrict to task IDs</Label>
<Label htmlFor="n-tasks">{t("Restrict to task IDs")}</Label>
<Input
id="n-tasks"
placeholder="1, 2, 3"
@@ -629,39 +631,39 @@ export default function NotifyPage() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="n-assets">Restrict to asset IDs</Label>
<Label htmlFor="n-assets">{t("Restrict to asset IDs")}</Label>
<Input
id="n-assets"
placeholder="10, 11"
value={form.assetIDsText}
onChange={(e) => setF({ assetIDsText: e.target.value })}
/>
<p className="text-muted-foreground text-xs">Empty task/asset = no restriction; when filled, the finding must intersect them.</p>
<p className="text-muted-foreground text-xs">{t("Empty task/asset = no restriction; when filled, the finding must intersect them.")}</p>
</div>
<div className="flex items-center gap-2 text-sm">
<Switch
checked={form.onStatusChange}
onCheckedChange={(v) => setF({ onStatusChange: v })}
aria-label="Include status changes"
aria-label={t("Include status changes")}
/>
Also push when a finding's status changes (realtime mode only)
{t("Also push when a finding's status changes (realtime mode only)")}
</div>
</div>
</div>
<div className="flex items-center gap-2 text-sm">
<Switch checked={form.enabled} onCheckedChange={(v) => setF({ enabled: v })} aria-label="Enable" />
Enable this channel
<Switch checked={form.enabled} onCheckedChange={(v) => setF({ enabled: v })} aria-label={t("Enable")} />
{t("Enable this channel")}
</div>
</div>
<div className="flex gap-2 pt-2 pb-6">
<Button onClick={saveForm} disabled={saving}>
{editing ? "Save" : "Add"}
{editing ? t("Save") : t("Add")}
</Button>
{editing && (
<Button variant="outline" onClick={testChannel} disabled={testing}>
<SendIcon /> Send test message
<SendIcon /> {t("Send test message")}
</Button>
)}
</div>
@@ -10,30 +10,34 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { NoiseProfileName, NoiseStatus } from "@/lib/types";
// Mirrors egress.Profiles in egress/egress.go; the jitter of one send is
// min(Jitter/RPS, 250 ms).
const profiles: { value: NoiseProfileName; label: string; limits: string }[] = [
{ value: "off", label: "Off", limits: "Off: requests and their timing are unchanged, and nothing is counted." },
{ value: "off", label: t("Off"), limits: t("Off: requests and their timing are unchanged, and nothing is counted.") },
{
value: "quiet",
label: "Quiet",
limits:
label: t("Quiet"),
limits: t(
"2 req/s per host (burst 4), 1 in flight per host, 8 overall, jitter up to 250 ms, identical GETs of a task cached 60 s, up to 3 retries on 429/503.",
),
},
{
value: "balanced",
label: "Balanced",
limits:
label: t("Balanced"),
limits: t(
"5 req/s per host (burst 10), 2 in flight per host, 16 overall, jitter up to 40 ms, identical GETs of a task cached 30 s, up to 3 retries on 429/503.",
),
},
{
value: "aggressive",
label: "Aggressive",
limits:
label: t("Aggressive"),
limits: t(
"20 req/s per host (burst 40), 4 in flight per host, 32 overall, jitter up to 5 ms, identical GETs of a task cached 10 s, up to 2 retries on 429/503.",
),
},
];
@@ -49,7 +53,7 @@ export function NoiseProfileCard() {
api
.noiseStatus()
.then(setStatus)
.catch((e) => toast.error(`Failed to load the noise counters: ${(e as Error).message}`))
.catch((e) => toast.error(t("Failed to load the noise counters: {error}", { error: (e as Error).message })))
.finally(() => setLoading(false));
}, []);
React.useEffect(() => {
@@ -61,10 +65,12 @@ export function NoiseProfileCard() {
api
.setSettings({ noise_profile: value })
.then(() => {
toast.success(`Noise profile set to ${value}`);
toast.success(
t("Noise profile set to {profile}", { profile: profiles.find((p) => p.value === value)?.label ?? value }),
);
refresh();
})
.catch((e) => toast.error(`Save failed: ${(e as Error).message}`))
.catch((e) => toast.error(t("Save failed: {error}", { error: (e as Error).message })))
.finally(() => setSaving(false));
};
@@ -74,21 +80,18 @@ export function NoiseProfileCard() {
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<GaugeIcon className="size-4" />
Target noise
{t("Target noise")}
</CardTitle>
<CardDescription>
Paces the requests ARTEX itself sends to targets (WebFetch, http custom tools, the enrich probe) and sets the
low-and-slow guidance in agent prompts. With traffic capture on, Bash commands that use the proxy (curl,
wget, python-requests…) are paced too, by rate and jitter only: the in-flight, cache and retry limits apply
to ARTEX's own requests. Raw scanners such as nmap, and commands that bypass the proxy, are not paced; this
is best effort, not a security boundary. This setting takes precedence over ARTEX_NOISE_PROFILE and applies
to the next request.
{t(
"Paces the requests ARTEX itself sends to targets (WebFetch, http custom tools, the enrich probe) and sets the low-and-slow guidance in agent prompts. With traffic capture on, Bash commands that use the proxy (curl, wget, python-requests…) are paced too, by rate and jitter only: the in-flight, cache and retry limits apply to ARTEX's own requests. Raw scanners such as nmap, and commands that bypass the proxy, are not paced; this is best effort, not a security boundary. This setting takes precedence over ARTEX_NOISE_PROFILE and applies to the next request.",
)}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-4">
<Label htmlFor="noise-profile" className="text-sm font-normal text-muted-foreground">
Profile
{t("Profile")}
</Label>
<Select
value={status?.profile ?? ""}
@@ -96,7 +99,7 @@ export function NoiseProfileCard() {
onValueChange={(v) => save(v as NoiseProfileName)}
>
<SelectTrigger id="noise-profile" className="w-48 shrink-0">
<SelectValue placeholder="Loading…" />
<SelectValue placeholder={t("Loading…")} />
</SelectTrigger>
<SelectContent>
{profiles.map((p) => (
@@ -109,21 +112,21 @@ export function NoiseProfileCard() {
</div>
<p className="text-muted-foreground text-xs">{current.limits}</p>
<div className="flex items-center justify-between gap-4">
<span className="font-medium text-sm">Hosts, current minute</span>
<span className="font-medium text-sm">{t("Hosts, current minute")}</span>
<Button variant="outline" size="sm" onClick={refresh} disabled={loading}>
<RefreshCwIcon data-icon="inline-start" className={loading ? "animate-spin" : undefined} />
Refresh
{t("Refresh")}
</Button>
</div>
{status?.hosts.length ? (
<Table aria-label="Noise counters per host">
<Table aria-label={t("Noise counters per host")}>
<TableHeader>
<TableRow>
<TableHead>Host</TableHead>
<TableHead>{t("Host")}</TableHead>
<TableHead className="text-right">RPM</TableHead>
<TableHead className="text-right">Peak RPM</TableHead>
<TableHead className="text-right">In flight (peak)</TableHead>
<TableHead className="text-right">Duplicates</TableHead>
<TableHead className="text-right">{t("Peak RPM")}</TableHead>
<TableHead className="text-right">{t("In flight (peak)")}</TableHead>
<TableHead className="text-right">{t("Duplicates")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -144,7 +147,7 @@ export function NoiseProfileCard() {
</Table>
) : (
<p className="text-muted-foreground text-sm">
{status?.profile === "off" ? "Off counts no request." : "No paced request yet."}
{status?.profile === "off" ? t("Off counts no request.") : t("No paced request yet.")}
</p>
)}
</CardContent>
+200 -125
View File
@@ -11,12 +11,24 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import { CHAT_SEND_MODE_OPTIONS, type ChatSendMode, setChatSendMode, useChatSendMode } from "@/lib/chat-send-mode";
import type { Settings } from "@/lib/types";
import { NoiseProfileCard } from "./noise-profile-card";
// Renders a translated string, turning <b>…</b> and <code>…</code> spans into elements, so a sentence with emphasis stays one key.
function rich(s: string): React.ReactNode[] {
return s.split(/(<b>.*?<\/b>|<code>.*?<\/code>)/).map((part, i) => {
const b = /^<b>(.*)<\/b>$/.exec(part);
if (b) return <b key={i}>{b[1]}</b>;
const c = /^<code>(.*)<\/code>$/.exec(part);
if (c) return <code key={i}>{c[1]}</code>;
return part;
});
}
export default function SystemSettingsPage() {
const [trafficCapture, setTrafficCapture] = React.useState(false);
const [agentTrafficBinding, setAgentTrafficBinding] = React.useState(false);
@@ -69,7 +81,7 @@ export default function SystemSettingsPage() {
const saveWorkers = () => {
const n = Number(workers);
if (!Number.isInteger(n) || n <= 0) {
toast.error("Concurrency must be an integer greater than 0");
toast.error(t("Concurrency must be an integer greater than 0"));
return;
}
setSavingWorkers(true);
@@ -77,9 +89,9 @@ export default function SystemSettingsPage() {
.setSettings({ workers: n })
.then((s) => {
apply(s);
toast.success("Saved the concurrent worker agent count (applies to tasks started afterwards)");
toast.success(t("Saved the concurrent worker agent count (applies to tasks started afterwards)"));
})
.catch((e) => toast.error("Save failed: " + (e as Error).message))
.catch((e) => toast.error(t("Save failed: {error}", { error: (e as Error).message })))
.finally(() => setSavingWorkers(false));
};
@@ -89,9 +101,9 @@ export default function SystemSettingsPage() {
.setSettings({ python_interpreter: pyInterp.trim() })
.then((s) => {
apply(s);
toast.success("Saved Python interpreter config");
toast.success(t("Saved Python interpreter config"));
})
.catch((e) => toast.error("Save failed: " + (e as Error).message))
.catch((e) => toast.error(t("Save failed: {error}", { error: (e as Error).message })))
.finally(() => setSaving(false));
};
const detectPython = () => {
@@ -136,11 +148,11 @@ export default function SystemSettingsPage() {
.setSettings({ agent_traffic_binding: v })
.then((s) => {
apply(s);
toast.success(v ? "Enabled automatic agent traffic binding" : "Disabled automatic agent traffic binding");
toast.success(v ? t("Enabled automatic agent traffic binding") : t("Disabled automatic agent traffic binding"));
})
.catch((e) => {
setAgentTrafficBinding(!v);
toast.error(`Save failed: ${(e as Error).message}`);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
})
.finally(() => setSaving(false));
};
@@ -159,11 +171,15 @@ export default function SystemSettingsPage() {
.setSettings({ noa_compaction: v })
.then((s) => {
apply(s);
toast.success(v ? "Enabled noa context compaction (applies to runs started afterwards)" : "Disabled noa context compaction (built-in compaction restored)");
toast.success(
v
? t("Enabled noa context compaction (applies to runs started afterwards)")
: t("Disabled noa context compaction (built-in compaction restored)"),
);
})
.catch((e) => {
setNoaCompaction(!v); // revert on failure
toast.error(`Save failed: ${(e as Error).message}`);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
});
};
@@ -174,10 +190,10 @@ export default function SystemSettingsPage() {
.setSettings(patch)
.then((s) => {
apply(s);
toast.success("Saved web search config");
toast.success(t("Saved web search config"));
})
.catch((e) => {
toast.error("Save failed: " + (e as Error).message);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
api
.settings()
.then(apply)
@@ -193,9 +209,9 @@ export default function SystemSettingsPage() {
.then((s) => {
apply(s);
setBraveKeyInput("");
toast.success("Saved Brave API Key");
toast.success(t("Saved Brave API Key"));
})
.catch((e) => toast.error("Save failed: " + (e as Error).message))
.catch((e) => toast.error(t("Save failed: {error}", { error: (e as Error).message })))
.finally(() => setSavingKey(false));
};
@@ -206,9 +222,9 @@ export default function SystemSettingsPage() {
.then((s) => {
apply(s);
setTavilyKeyInput("");
toast.success("Saved Tavily API Key");
toast.success(t("Saved Tavily API Key"));
})
.catch((e) => toast.error("Save failed: " + (e as Error).message))
.catch((e) => toast.error(t("Save failed: {error}", { error: (e as Error).message })))
.finally(() => setSavingTavilyKey(false));
};
@@ -219,9 +235,9 @@ export default function SystemSettingsPage() {
.then((s) => {
apply(s);
setKeenableKeyInput("");
toast.success("Saved Keenable API Key");
toast.success(t("Saved Keenable API Key"));
})
.catch((e) => toast.error("Save failed: " + (e as Error).message))
.catch((e) => toast.error(t("Save failed: {error}", { error: (e as Error).message })))
.finally(() => setSavingKeenableKey(false));
};
@@ -231,9 +247,9 @@ export default function SystemSettingsPage() {
.setSettings({ web_search_proxy: proxyInput.trim() })
.then((s) => {
apply(s);
toast.success(proxyInput.trim() ? "Saved egress proxy" : "Cleared egress proxy (direct connection)");
toast.success(proxyInput.trim() ? t("Saved egress proxy") : t("Cleared egress proxy (direct connection)"));
})
.catch((e) => toast.error("Save failed: " + (e as Error).message))
.catch((e) => toast.error(t("Save failed: {error}", { error: (e as Error).message })))
.finally(() => setSavingProxy(false));
};
@@ -243,9 +259,9 @@ export default function SystemSettingsPage() {
.setSettings({ global_proxy: globalProxyInput.trim() })
.then((s) => {
apply(s);
toast.success(globalProxyInput.trim() ? "Saved global proxy" : "Cleared global proxy (direct connection)");
toast.success(globalProxyInput.trim() ? t("Saved global proxy") : t("Cleared global proxy (direct connection)"));
})
.catch((e) => toast.error("Save failed: " + (e as Error).message))
.catch((e) => toast.error(t("Save failed: {error}", { error: (e as Error).message })))
.finally(() => setSavingGlobalProxy(false));
};
@@ -262,10 +278,11 @@ export default function SystemSettingsPage() {
keenable_search_api_key: keenableKeyInput,
})
.then((r) => {
if (r.ok) toast.success(`Search test succeeded · ${r.backend} returned ${r.count} results`);
else toast.error("Search test failed: " + (r.error || "unknown error"));
if (r.ok)
toast.success(t("Search test succeeded · {backend} returned {count} results", { backend: r.backend ?? "", count: r.count ?? 0 }));
else toast.error(t("Search test failed: {error}", { error: r.error || t("unknown error") }));
})
.catch((e) => toast.error("Search test failed: " + (e as Error).message))
.catch((e) => toast.error(t("Search test failed: {error}", { error: (e as Error).message })))
.finally(() => setTesting(false));
};
@@ -275,8 +292,8 @@ export default function SystemSettingsPage() {
return (
<div className="flex flex-1 flex-col gap-4 md:gap-6">
<div>
<h1 className="text-xl font-semibold tracking-tight">System settings</h1>
<p className="text-muted-foreground text-sm">Global runtime switches</p>
<h1 className="text-xl font-semibold tracking-tight">{t("System settings")}</h1>
<p className="text-muted-foreground text-sm">{t("Global runtime switches")}</p>
</div>
{/* Multi-column instead of grid: the web search card is several times taller than the others and
@@ -289,19 +306,23 @@ export default function SystemSettingsPage() {
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<RadioTowerIcon className="size-4" />
Traffic capture
{t("Traffic capture")}
</CardTitle>
<CardDescription>
When enabled, every agent's HTTP traffic is stored in full through the recording proxy, and agents are injected with the traffic_search / traffic_get
tools and proxy configuration (the prompt includes proxy notes).
{t(
"When enabled, every agent's HTTP traffic is stored in full through the recording proxy, and agents are injected with the traffic_search / traffic_get tools and proxy configuration (the prompt includes proxy notes).",
)}
<br />
When off (default) no traffic is recorded: the agent
does <b>not</b> receive proxy configuration or traffic tools, and the prompt contains <b>no</b> proxy-related content. Agents are rebuilt immediately after switching.
{rich(
t(
"When off (default) no traffic is recorded: the agent does <b>not</b> receive proxy configuration or traffic tools, and the prompt contains <b>no</b> proxy-related content. Agents are rebuilt immediately after switching.",
),
)}
</CardDescription>
</CardHeader>
<CardContent className="flex items-center justify-between gap-4">
<Label htmlFor="traffic-capture" className="text-sm font-normal text-muted-foreground">
{trafficCapture ? "On · recording traffic and injecting proxy" : "Off · no recording, no proxy injection"}
{trafficCapture ? t("On · recording traffic and injecting proxy") : t("Off · no recording, no proxy injection")}
</Label>
<Switch
id="traffic-capture"
@@ -318,19 +339,23 @@ export default function SystemSettingsPage() {
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<RadioTowerIcon className="size-4" />
Automatic agent traffic binding
{t("Automatic agent traffic binding")}
</CardTitle>
<CardDescription id="agent-traffic-binding-description">
Off by default. When enabled, the report agent triggered on vulnerability creation reviews existing HTTP requests/responses and links the matching traffic before writing the report.
<b>Reading packets and the extra tool calls increase token consumption.</b>
{rich(
t(
"Off by default. When enabled, the report agent triggered on vulnerability creation reviews existing HTTP requests/responses and links the matching traffic before writing the report. <b>Reading packets and the extra tool calls increase token consumption.</b>",
),
)}
<br />
Reporting still works for TCP, uncaptured traffic, or when no traffic matches. This switch does not affect traffic capture, manual binding, or viewing saved evidence. It takes effect for the
next round of agents; once disabled, new automatic bindings are rejected immediately.
{t(
"Reporting still works for TCP, uncaptured traffic, or when no traffic matches. This switch does not affect traffic capture, manual binding, or viewing saved evidence. It takes effect for the next round of agents; once disabled, new automatic bindings are rejected immediately.",
)}
</CardDescription>
</CardHeader>
<CardContent className="flex items-center justify-between gap-4">
<Label htmlFor="agent-traffic-binding" className="text-sm font-normal text-muted-foreground">
{agentTrafficBinding ? "On · increases token consumption" : "Off · manual binding still available"}
{agentTrafficBinding ? t("On · increases token consumption") : t("Off · manual binding still available")}
</Label>
<Switch
id="agent-traffic-binding"
@@ -346,39 +371,49 @@ export default function SystemSettingsPage() {
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<RadioTowerIcon className="size-4" />
Global proxy
{t("Global proxy")}
</CardTitle>
<CardDescription>
All agents' <b>target traffic</b> egresses through this proxy (hide the source IP / use a jump host). Supports <b>http / https / socks5</b>, optionally with{" "}
<code>user:pass</code> authentication. Empty = direct connection.
{rich(
t(
"All agents' <b>target traffic</b> egresses through this proxy (hide the source IP / use a jump host). Supports <b>http / https / socks5</b>, optionally with <code>user:pass</code> authentication. Empty = direct connection.",
),
)}
<br />
With <b>traffic capture</b> on, it acts as the recording proxy's <b>upstream</b> (traffic is still stored in full, then egresses through this proxy); with capture off, it is injected directly into
the agent's bash / WebFetch egress. Independent of the web search proxy and the LLM proxy.
{rich(
t(
"With <b>traffic capture</b> on, it acts as the recording proxy's <b>upstream</b> (traffic is still stored in full, then egresses through this proxy); with capture off, it is injected directly into the agent's bash / WebFetch egress. Independent of the web search proxy and the LLM proxy.",
),
)}
<br />
<b>Note</b>: with <b>capture off</b>, socks5 relies on each CLI tool honoring <code>ALL_PROXY</code> (curl
works; some tools may ignore it). If you mainly use socks5, enable traffic capture — on that path the MITM
does the dialing itself, invisible to tools and reliably effective.
{rich(
t(
"<b>Note</b>: with <b>capture off</b>, socks5 relies on each CLI tool honoring <code>ALL_PROXY</code> (curl works; some tools may ignore it). If you mainly use socks5, enable traffic capture — on that path the MITM does the dialing itself, invisible to tools and reliably effective.",
),
)}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-2">
<Label htmlFor="global-proxy" className="text-sm font-normal text-muted-foreground">
Proxy address
{t("Proxy address")}
</Label>
<div className="flex items-center gap-2">
<Input
id="global-proxy"
autoComplete="off"
placeholder="socks5://user:pass@host:1080 or http://host:port (empty = direct)"
placeholder={t("socks5://user:pass@host:1080 or http://host:port (empty = direct)")}
value={globalProxyInput}
disabled={!loaded || savingGlobalProxy}
onChange={(e) => setGlobalProxyInput(e.target.value)}
/>
<Button type="button" onClick={saveGlobalProxy} disabled={!loaded || savingGlobalProxy}>
Save
{t("Save")}
</Button>
</div>
<p className="text-muted-foreground text-xs">
{globalProxyInput.trim() ? "Configured · all target traffic egresses through this proxy" : "Not configured · target traffic egresses directly"}
{globalProxyInput.trim()
? t("Configured · all target traffic egresses through this proxy")
: t("Not configured · target traffic egresses directly")}
</p>
</CardContent>
</Card>
@@ -387,20 +422,26 @@ export default function SystemSettingsPage() {
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ShieldAlertIcon className="size-4" />
Operation constraint injection
{t("Operation constraint injection")}
</CardTitle>
<CardDescription>
When enabled, each task's <b>operation constraints</b> (the allow/deny entries maintained under "Operation constraints" in the task overview) are spliced into the corresponding agent's
system prompt to bound the exploration scope (e.g. "only test the current port", "no brute forcing").
{rich(
t(
'When enabled, each task\'s <b>operation constraints</b> (the allow/deny entries maintained under "Operation constraints" in the task overview) are spliced into the corresponding agent\'s system prompt to bound the exploration scope (e.g. "only test the current port", "no brute forcing").',
),
)}
<br />
You can control injection into the <b>planner</b> and the <b>worker</b> separately
; both are on by default. Switching takes effect immediately (read on the next turn) without rebuilding agents. When off, the agent no longer sees the constraints.
{rich(
t(
"You can control injection into the <b>planner</b> and the <b>worker</b> separately; both are on by default. Switching takes effect immediately (read on the next turn) without rebuilding agents. When off, the agent no longer sees the constraints.",
),
)}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-4">
<Label htmlFor="inject-planner" className="text-sm font-normal text-muted-foreground">
Inject into planner{injectPlanner ? " · On" : " · Off"}
{injectPlanner ? t("Inject into planner · On") : t("Inject into planner · Off")}
</Label>
<Switch
id="inject-planner"
@@ -411,7 +452,7 @@ export default function SystemSettingsPage() {
</div>
<div className="flex items-center justify-between gap-4">
<Label htmlFor="inject-worker" className="text-sm font-normal text-muted-foreground">
Inject into worker{injectWorker ? " · On" : " · Off"}
{injectWorker ? t("Inject into worker · On") : t("Inject into worker · Off")}
</Label>
<Switch
id="inject-worker"
@@ -427,20 +468,23 @@ export default function SystemSettingsPage() {
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<FlaskConicalIcon className="size-4" />
Experimental features
{t("Experimental features")}
</CardTitle>
<CardDescription>
Mechanisms still being validated, off by default. They may change agent behavior or affect stability; enable only after understanding the impact.
{t(
"Mechanisms still being validated, off by default. They may change agent behavior or affect stability; enable only after understanding the impact.",
)}
<br />
<b>noa context compaction</b>: the model actively compacts long conversation history (norma v0.4.0). When enabled, the four agent types integrated into the platform (
<b>planner / worker / main agent / chat</b>) switch to noa-managed context in place of the built-in compaction,
and the pre-compaction originals are archived under the task working directory for later review. Switching takes effect immediately (for runs started afterwards) without rebuilding agents;
when disabled, the built-in compaction is restored immediately.
{rich(
t(
"<b>noa context compaction</b>: the model actively compacts long conversation history (norma v0.4.0). When enabled, the four agent types integrated into the platform (<b>planner / worker / main agent / chat</b>) switch to noa-managed context in place of the built-in compaction, and the pre-compaction originals are archived under the task working directory for later review. Switching takes effect immediately (for runs started afterwards) without rebuilding agents; when disabled, the built-in compaction is restored immediately.",
),
)}
</CardDescription>
</CardHeader>
<CardContent className="flex items-center justify-between gap-4">
<Label htmlFor="noa-compaction" className="text-sm font-normal text-muted-foreground">
noa context compaction{noaCompaction ? " · On" : " · Off"}
{noaCompaction ? t("noa context compaction · On") : t("noa context compaction · Off")}
</Label>
<Switch
id="noa-compaction"
@@ -455,22 +499,28 @@ export default function SystemSettingsPage() {
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<SearchIcon className="size-4" />
Web search
{t("Web search")}
</CardTitle>
<CardDescription>
This is the web search <b>master switch + source config</b>. Only when it is enabled can <b>each agent's config</b> separately choose whether to enable
<b>web_search</b> (returns only titles/links/snippets without fetching bodies; fetching is handled by WebFetch). Web search does <b>not</b> go through
the recording proxy and is independent of traffic capture.
{rich(
t(
"This is the web search <b>master switch + source config</b>. Only when it is enabled can <b>each agent's config</b> separately choose whether to enable <b>web_search</b> (returns only titles/links/snippets without fetching bodies; fetching is handled by WebFetch). Web search does <b>not</b> go through the recording proxy and is independent of traffic capture.",
),
)}
<br />
Sources: <b>DuckDuckGo (ddgs)</b> (no key needed), <b>Brave (free tier)</b> (requires a Brave API Key),{" "}
<b>Tavily</b> (requires a Tavily API Key) or <b>DeepSeek</b> (reuses the current LLM config). When the master switch is off, the
per-agent web search switches are unavailable.
{rich(
t(
"Sources: <b>DuckDuckGo (ddgs)</b> (no key needed), <b>Brave (free tier)</b> (requires a Brave API Key), <b>Tavily</b> (requires a Tavily API Key) or <b>DeepSeek</b> (reuses the current LLM config). When the master switch is off, the per-agent web search switches are unavailable.",
),
)}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-4">
<Label htmlFor="web-search" className="text-sm font-normal text-muted-foreground">
{webSearch ? "Master switch on · can be enabled per agent config" : "Off · agents cannot enable web search"}
{webSearch
? t("Master switch on · can be enabled per agent config")
: t("Off · agents cannot enable web search")}
</Label>
<Switch
id="web-search"
@@ -485,7 +535,7 @@ export default function SystemSettingsPage() {
{webSearch && (
<div className="flex items-center justify-between gap-4">
<Label className="text-sm font-normal text-muted-foreground">Search source</Label>
<Label className="text-sm font-normal text-muted-foreground">{t("Search source")}</Label>
<Select
value={backend}
disabled={!loaded || saving}
@@ -495,14 +545,14 @@ export default function SystemSettingsPage() {
}}
>
<SelectTrigger className="w-48 shrink-0">
<SelectValue placeholder="Choose a source" />
<SelectValue placeholder={t("Choose a source")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="ddgs">DuckDuckGo (ddgs · free, no key)</SelectItem>
<SelectItem value="brave-free">Brave (free tier · requires key)</SelectItem>
<SelectItem value="tavily">Tavily (requires key)</SelectItem>
<SelectItem value="keenable">Keenable (keyless, optional key)</SelectItem>
<SelectItem value="deepseek">DeepSeek (official)</SelectItem>
<SelectItem value="ddgs">{t("DuckDuckGo (ddgs · free, no key)")}</SelectItem>
<SelectItem value="brave-free">{t("Brave (free tier · requires key)")}</SelectItem>
<SelectItem value="tavily">{t("Tavily (requires key)")}</SelectItem>
<SelectItem value="keenable">{t("Keenable (keyless, optional key)")}</SelectItem>
<SelectItem value="deepseek">{t("DeepSeek (official)")}</SelectItem>
</SelectContent>
</Select>
</div>
@@ -510,19 +560,25 @@ export default function SystemSettingsPage() {
{webSearch && backend === "deepseek" && (
<div className="border-border/60 bg-muted/30 flex flex-col gap-2 rounded-md border p-3">
<p className="text-sm font-medium">DeepSeek official web search</p>
<p className="text-sm font-medium">{t("DeepSeek official web search")}</p>
<p className="text-muted-foreground text-xs leading-relaxed">
This source directly reuses the <b>currently active LLM config</b>. It therefore
supports <b>official DeepSeek models only</b>, and that config <b>must use the anthropic protocol</b>
— DeepSeek's OpenAI-protocol endpoint does not support server-side search. This source may stop working after switching LLM configs.
{rich(
t(
"This source directly reuses the <b>currently active LLM config</b>. It therefore supports <b>official DeepSeek models only</b>, and that config <b>must use the anthropic protocol</b> — DeepSeek's OpenAI-protocol endpoint does not support server-side search. This source may stop working after switching LLM configs.",
),
)}
</p>
<p className="text-muted-foreground text-xs leading-relaxed">
Unlike other sources, the search runs <b>server-side on DeepSeek</b>: each search consumes an extra model call (incurring token
costs), search requests <b>do not go through the egress proxy above</b> and are <b>not recorded as traffic</b>; results contain <b>titles and links only</b>
(no snippets); use WebFetch when you need the page body.
{rich(
t(
"Unlike other sources, the search runs <b>server-side on DeepSeek</b>: each search consumes an extra model call (incurring token costs), search requests <b>do not go through the egress proxy above</b> and are <b>not recorded as traffic</b>; results contain <b>titles and links only</b> (no snippets); use WebFetch when you need the page body.",
),
)}
</p>
<p className="text-muted-foreground text-xs leading-relaxed">
Verify these conditions yourself; the system does not block on them. Use the "Test search" button below to run a real search and check.
{t(
'Verify these conditions yourself; the system does not block on them. Use the "Test search" button below to run a real search and check.',
)}
</p>
</div>
)}
@@ -531,14 +587,14 @@ export default function SystemSettingsPage() {
<div className="flex flex-col gap-2">
<Label htmlFor="brave-key" className="text-sm font-normal text-muted-foreground">
Brave Search API Key
{braveKeySet && <span className="ml-2 text-xs text-emerald-500">Configured</span>}
{braveKeySet && <span className="ml-2 text-xs text-emerald-500">{t("Configured")}</span>}
</Label>
<div className="flex items-center gap-2">
<Input
id="brave-key"
type="password"
autoComplete="off"
placeholder={braveKeySet ? "Configured (leave empty to keep)" : "Enter Brave API Key"}
placeholder={braveKeySet ? t("Configured (leave empty to keep)") : t("Enter Brave API Key")}
value={braveKeyInput}
disabled={!loaded || savingKey}
onChange={(e) => setBraveKeyInput(e.target.value)}
@@ -548,16 +604,16 @@ export default function SystemSettingsPage() {
onClick={saveBraveKey}
disabled={!loaded || savingKey || braveKeyInput.trim() === ""}
>
Save
{t("Save")}
</Button>
</div>
{braveNeedsKey && (
<p className="text-xs text-amber-500">
Brave is selected but no key is configured — the search tool stays disabled until you save one.
{t("Brave is selected but no key is configured — the search tool stays disabled until you save one.")}
</p>
)}
<p className="text-muted-foreground text-xs">
The free tier allows about 2,000 queries/month. Get a key at https://brave.com/search/api/.
{t("The free tier allows about 2,000 queries/month. Get a key at https://brave.com/search/api/.")}
</p>
</div>
)}
@@ -566,14 +622,14 @@ export default function SystemSettingsPage() {
<div className="flex flex-col gap-2">
<Label htmlFor="tavily-key" className="text-sm font-normal text-muted-foreground">
Tavily Search API Key
{tavilyKeySet && <span className="ml-2 text-xs text-emerald-500">Configured</span>}
{tavilyKeySet && <span className="ml-2 text-xs text-emerald-500">{t("Configured")}</span>}
</Label>
<div className="flex items-center gap-2">
<Input
id="tavily-key"
type="password"
autoComplete="off"
placeholder={tavilyKeySet ? "Configured (leave empty to keep)" : "Enter Tavily API Key (tvly-…)"}
placeholder={tavilyKeySet ? t("Configured (leave empty to keep)") : t("Enter Tavily API Key (tvly-…)")}
value={tavilyKeyInput}
disabled={!loaded || savingTavilyKey}
onChange={(e) => setTavilyKeyInput(e.target.value)}
@@ -583,30 +639,34 @@ export default function SystemSettingsPage() {
onClick={saveTavilyKey}
disabled={!loaded || savingTavilyKey || tavilyKeyInput.trim() === ""}
>
Save
{t("Save")}
</Button>
</div>
{webSearch && backend === "tavily" && !tavilyKeySet && (
<p className="text-xs text-amber-500">
Tavily is selected but no key is configured — the search tool stays disabled until you save one.
{t("Tavily is selected but no key is configured — the search tool stays disabled until you save one.")}
</p>
)}
<p className="text-muted-foreground text-xs">Register and get an API key at https://tavily.com.</p>
<p className="text-muted-foreground text-xs">{t("Register and get an API key at https://tavily.com.")}</p>
</div>
)}
{webSearch && backend === "keenable" && (
<div className="flex flex-col gap-2">
<Label htmlFor="keenable-key" className="text-sm font-normal text-muted-foreground">
Keenable Search API Key (optional)
{keenableKeySet && <span className="ml-2 text-xs text-emerald-500">Configured</span>}
{t("Keenable Search API Key (optional)")}
{keenableKeySet && <span className="ml-2 text-xs text-emerald-500">{t("Configured")}</span>}
</Label>
<div className="flex items-center gap-2">
<Input
id="keenable-key"
type="password"
autoComplete="off"
placeholder={keenableKeySet ? "Configured (leave empty to keep)" : "Optional: leave empty for the keyless endpoint"}
placeholder={
keenableKeySet
? t("Configured (leave empty to keep)")
: t("Optional: leave empty for the keyless endpoint")
}
value={keenableKeyInput}
disabled={!loaded || savingKeenableKey}
onChange={(e) => setKeenableKeyInput(e.target.value)}
@@ -616,14 +676,15 @@ export default function SystemSettingsPage() {
onClick={saveKeenableKey}
disabled={!loaded || savingKeenableKey || keenableKeyInput.trim() === ""}
>
Save
{t("Save")}
</Button>
</div>
<p className="text-muted-foreground text-xs leading-relaxed">
Queries leave this instance and go to api.keenable.ai. The request carries{" "}
<b>X-Keenable-Title: ARTEX</b> so the provider can identify the caller. With no key, the
public endpoint is rate-limited per IP; a key raises the limit, but the backend works
without one.
{rich(
t(
"Queries leave this instance and go to api.keenable.ai. The request carries <b>X-Keenable-Title: ARTEX</b> so the provider can identify the caller. With no key, the public endpoint is rate-limited per IP; a key raises the limit, but the backend works without one.",
),
)}
</p>
</div>
)}
@@ -631,23 +692,25 @@ export default function SystemSettingsPage() {
{webSearch && (
<div className="flex flex-col gap-2">
<Label htmlFor="ws-proxy" className="text-sm font-normal text-muted-foreground">
Egress proxy (optional)
{t("Egress proxy (optional)")}
</Label>
<div className="flex items-center gap-2">
<Input
id="ws-proxy"
autoComplete="off"
placeholder="http://host:port or socks5://host:port (empty = direct)"
placeholder={t("http://host:port or socks5://host:port (empty = direct)")}
value={proxyInput}
disabled={!loaded || savingProxy}
onChange={(e) => setProxyInput(e.target.value)}
/>
<Button type="button" onClick={saveProxy} disabled={!loaded || savingProxy}>
Save
{t("Save")}
</Button>
</div>
<p className="text-muted-foreground text-xs">
A dedicated egress proxy used only to reach search endpoints (VPN/SOCKS etc.). Unrelated to the traffic-recording MITM proxy; use it to reach endpoints when the network is blocked.
{t(
"A dedicated egress proxy used only to reach search endpoints (VPN/SOCKS etc.). Unrelated to the traffic-recording MITM proxy; use it to reach endpoints when the network is blocked.",
)}
</p>
</div>
)}
@@ -655,7 +718,7 @@ export default function SystemSettingsPage() {
{webSearch && (
<div className="flex items-center justify-between gap-4 border-t pt-4">
<p className="text-muted-foreground text-xs">
Run a real "test" search with the current config (source + proxy + key) to verify it works.
{t('Run a real "test" search with the current config (source + proxy + key) to verify it works.')}
</p>
<Button
type="button"
@@ -664,7 +727,7 @@ export default function SystemSettingsPage() {
disabled={!loaded || testing}
className="shrink-0"
>
{testing ? "Testing…" : "Test search"}
{testing ? t("Testing…") : t("Test search")}
</Button>
</div>
)}
@@ -675,27 +738,30 @@ export default function SystemSettingsPage() {
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<RadioTowerIcon className="size-4" />
Custom scripts · Python interpreter
{t("Custom scripts · Python interpreter")}
</CardTitle>
<CardDescription>
Custom <b>script</b> tools run Python with it. Auto-detected at startup (python3 first); you can enter an absolute path to a venv /
specific version here; leave empty to auto-detect at runtime.
{rich(
t(
"Custom <b>script</b> tools run Python with it. Auto-detected at startup (python3 first); you can enter an absolute path to a venv / specific version here; leave empty to auto-detect at runtime.",
),
)}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<Input
className="font-mono text-sm"
placeholder="/usr/bin/python3 (empty = auto-detect)"
placeholder={t("/usr/bin/python3 (empty = auto-detect)")}
value={pyInterp}
disabled={!loaded || saving}
onChange={(e) => setPyInterp(e.target.value)}
/>
<Button variant="outline" onClick={detectPython} disabled={!loaded || saving}>
Re-detect
{t("Re-detect")}
</Button>
<Button onClick={savePython} disabled={!loaded || saving}>
Save
{t("Save")}
</Button>
</div>
</CardContent>
@@ -705,11 +771,14 @@ export default function SystemSettingsPage() {
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<CpuIcon className="size-4" />
Work concurrency · worker agent count
{t("Work concurrency · worker agent count")}
</CardTitle>
<CardDescription>
The number of worker agents running concurrently per task (default 3). Higher values mean more parallel probing and higher consumption. Changes
<b>apply to tasks started afterwards</b>; running tasks are unaffected.
{rich(
t(
"The number of worker agents running concurrently per task (default 3). Higher values mean more parallel probing and higher consumption. Changes <b>apply to tasks started afterwards</b>; running tasks are unaffected.",
),
)}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
@@ -724,7 +793,7 @@ export default function SystemSettingsPage() {
onChange={(e) => setWorkers(e.target.value)}
/>
<Button onClick={saveWorkers} disabled={!loaded || savingWorkers}>
Save
{t("Save")}
</Button>
</div>
</CardContent>
@@ -734,17 +803,23 @@ export default function SystemSettingsPage() {
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<KeyboardIcon className="size-4" />
Chat input send key binding
{t("Chat input send key binding")}
</CardTitle>
<CardDescription>
Shared by the main-agent chat inputs on the chat page and task details; takes effect immediately on selection, no saving needed.
{t(
"Shared by the main-agent chat inputs on the chat page and task details; takes effect immediately on selection, no saving needed.",
)}
<br />
This preference <b>lives only in this browser</b>, does not sync with the account, and must be set again after switching browsers or clearing site data.
{rich(
t(
"This preference <b>lives only in this browser</b>, does not sync with the account, and must be set again after switching browsers or clearing site data.",
),
)}
</CardDescription>
</CardHeader>
<CardContent className="flex items-center justify-between gap-4">
<Label htmlFor="chat-send-mode" className="text-sm font-normal text-muted-foreground">
Send mode
{t("Send mode")}
</Label>
<Select value={sendMode} onValueChange={(v) => setChatSendMode(v as ChatSendMode)}>
<SelectTrigger id="chat-send-mode" className="w-72">
+120 -97
View File
@@ -43,11 +43,12 @@ import {
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";
import { api } from "@/lib/api";
import { intlLocale, t } from "@/i18n";
import type { Agent, SkillItem, MCPServer, SkillCall, MissingSkill } from "@/lib/types";
function fmtTime(ts?: string) {
if (!ts) return "Never called";
return new Date(ts).toLocaleString("zh-CN", {
if (!ts) return t("Never called");
return new Date(ts).toLocaleString(intlLocale, {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
@@ -177,23 +178,31 @@ function SkillsOverview({
if (skills.length === 0) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground">No skills yet — click "Create" or "Upload archive" on the left to get started</p>
<p className="text-sm text-muted-foreground">{t("No skills yet — click \"Create\" or \"Upload archive\" on the left to get started")}</p>
</div>
);
}
const stats: { label: string; value: React.ReactNode; hint?: string }[] = [
{ label: "Total skills", value: skills.length, hint: `${agg.usedCount} have been called` },
{ label: "Total calls", value: agg.totalCalls },
{ label: "Unused", value: agg.neverUsed.length, hint: agg.neverUsed.length > 0 ? "never loaded by any agent" : "all used" },
{ label: "Missed calls", value: agg.missingCalls, hint: missing.length > 0 ? `${missing.length} missing skills` : "none" },
{ label: t("Total skills"), value: skills.length, hint: t("{count} have been called", { count: agg.usedCount }) },
{ label: t("Total calls"), value: agg.totalCalls },
{
label: t("Unused"),
value: agg.neverUsed.length,
hint: agg.neverUsed.length > 0 ? t("never loaded by any agent") : t("all used"),
},
{
label: t("Missed calls"),
value: agg.missingCalls,
hint: missing.length > 0 ? t("{count} missing skills", { count: missing.length }) : t("none"),
},
];
return (
<div className="mx-auto w-full max-w-3xl space-y-6">
<div>
<h2 className="text-base font-semibold">Skill library overview</h2>
<p className="text-muted-foreground text-sm">Select a skill on the left to view details and call history, or get a quick picture of overall usage here.</p>
<h2 className="text-base font-semibold">{t("Skill library overview")}</h2>
<p className="text-muted-foreground text-sm">{t("Select a skill on the left to view details and call history, or get a quick picture of overall usage here.")}</p>
</div>
{/* stat cards */}
@@ -209,10 +218,10 @@ function SkillsOverview({
{/* call ranking */}
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">Call ranking</Label>
<Label className="text-xs text-muted-foreground">{t("Call ranking")}</Label>
{agg.ranked.length === 0 ? (
<p className="text-muted-foreground rounded-lg border border-dashed p-4 text-center text-xs">
No skill call records yet.
{t("No skill call records yet.")}
</p>
) : (
<div className="space-y-1.5">
@@ -231,7 +240,7 @@ function SkillsOverview({
/>
</span>
<span className="w-16 shrink-0 text-right text-xs tabular-nums text-muted-foreground">
{s.calls} calls
{t("{count} calls", { count: s.calls })}
</span>
</button>
))}
@@ -242,9 +251,9 @@ function SkillsOverview({
<div className="grid gap-6 sm:grid-cols-2">
{/* recent calls */}
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">Recent calls</Label>
<Label className="text-xs text-muted-foreground">{t("Recent calls")}</Label>
{agg.recent.length === 0 ? (
<p className="text-muted-foreground text-xs">No records yet.</p>
<p className="text-muted-foreground text-xs">{t("No records yet.")}</p>
) : (
<div className="space-y-1">
{agg.recent.map((s) => (
@@ -265,11 +274,11 @@ function SkillsOverview({
{/* unused (candidates for cleanup / exposure) */}
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">
Unused skills
{t("Unused skills")}
{agg.neverUsed.length > 0 && <span className="ml-1 font-normal"> ({agg.neverUsed.length})</span>}
</Label>
{agg.neverUsed.length === 0 ? (
<p className="text-muted-foreground text-xs">All skills have been called.</p>
<p className="text-muted-foreground text-xs">{t("All skills have been called.")}</p>
) : (
<div className="flex flex-wrap gap-1.5">
{agg.neverUsed.map((s) => (
@@ -362,18 +371,18 @@ export default function SkillsPage() {
setUploading(true);
try {
const r = await api.uploadSkill(file, overwrite);
toast.success(`Skill installed: ${r.name} (${r.files} files)`);
toast.success(t("Skill installed: {name} ({count} files)", { name: r.name, count: r.files }));
load();
} catch (e) {
const msg = (e as Error).message;
// offer overwrite when the skill already exists
if (!overwrite && msg.includes("already exists")) {
if (window.confirm(`${msg}\n\nOverwrite the skill with the same name?`)) {
if (window.confirm(`${msg}\n\n${t("Overwrite the skill with the same name?")}`)) {
await uploadZip(file, true);
return;
}
} else {
toast.error("Upload failed: " + msg);
toast.error(t("Upload failed: {error}", { error: msg }));
}
} finally {
setUploading(false);
@@ -415,7 +424,7 @@ export default function SkillsPage() {
setFileLoading(true);
api.readSkillFile(selected.skill, selected.path)
.then((c) => { setFileContent(c); setDirty(false); })
.catch(() => toast.error("Failed to read the file"))
.catch(() => toast.error(t("Failed to read the file")))
.finally(() => setFileLoading(false));
}, [selected]);
@@ -469,17 +478,17 @@ export default function SkillsPage() {
try {
if (c.kind === "dir") {
await api.createSkillDir(c.skill, fullPath);
toast.success(`Folder created: ${fullPath}`);
toast.success(t("Folder created: {path}", { path: fullPath }));
ensureExpanded(c.skill, fullPath);
} else {
await api.writeSkillFile(c.skill, fullPath, "");
toast.success(`File created: ${fullPath}`);
toast.success(t("File created: {path}", { path: fullPath }));
setSelected({ skill: c.skill, path: fullPath });
ensureExpanded(c.skill, c.inDir);
}
load();
} catch (e) {
toast.error("Create failed: " + (e as Error).message);
toast.error(t("Create failed: {error}", { error: (e as Error).message }));
}
}
@@ -492,22 +501,22 @@ export default function SkillsPage() {
async function deletePath(skill: string, path: string) {
try {
await api.deleteSkillPath(skill, path);
toast.success(`Deleted: ${path}`);
toast.success(t("Deleted: {path}", { path }));
if (selected?.skill === skill && selected.path === path) setSelected(null);
load();
} catch (e) {
toast.error("Delete failed: " + (e as Error).message);
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
}
}
async function deleteSkill(name: string) {
try {
await api.deleteSkill(name);
toast.success(`Skill deleted: ${name}`);
toast.success(t("Skill deleted: {name}", { name }));
if (selected?.skill === name) setSelected(null);
load();
} catch (e) {
toast.error("Delete failed: " + (e as Error).message);
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
}
}
@@ -529,10 +538,10 @@ export default function SkillsPage() {
setSaving(true);
try {
await api.writeSkillFile(selected.skill, selected.path, fileContent);
toast.success("Saved");
toast.success(t("Saved"));
setDirty(false);
} catch (e) {
toast.error("Save failed: " + (e as Error).message);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally { setSaving(false); }
}
@@ -543,12 +552,12 @@ export default function SkillsPage() {
setDetailMcps(next);
try {
await api.updateSkillMeta(skillName, { mcps: next });
toast.success(`${mcpOn ? "Linked" : "Unlinked"} "${mcpName}"`);
toast.success(mcpOn ? t('Linked "{name}"', { name: mcpName }) : t('Unlinked "{name}"', { name: mcpName }));
load();
} catch (e) {
// roll back on error
setDetailMcps(detailMcps);
toast.error("Operation failed: " + (e as Error).message);
toast.error(t("Operation failed: {error}", { error: (e as Error).message }));
}
}
@@ -556,17 +565,21 @@ export default function SkillsPage() {
const on = (visibility[skillName] ?? []).includes(agentId);
try {
await api.toggleSkillVisibility(agentId, skillName, !on);
toast.success(`${on ? "Revoked" : "Granted"} visibility to "${agentName}"`);
toast.success(
on
? t('Revoked visibility to "{name}"', { name: agentName })
: t('Granted visibility to "{name}"', { name: agentName }),
);
const ids = await api.skillVisibility(skillName);
setVisibility((v) => ({ ...v, [skillName]: ids }));
} catch (e) {
toast.error("Operation failed: " + (e as Error).message);
toast.error(t("Operation failed: {error}", { error: (e as Error).message }));
}
}
async function createNewSkill() {
if (!newName.trim()) { toast.error("Please fill in the name"); return; }
if (!newDesc.trim()) { toast.error("description is required"); return; }
if (!newName.trim()) { toast.error(t("Please fill in the name")); return; }
if (!newDesc.trim()) { toast.error(t("description is required")); return; }
setCreatingSkill(true);
try {
const name = newName.trim();
@@ -579,13 +592,13 @@ export default function SkillsPage() {
});
// apply initial visibility (fire-and-forget per agent; best-effort)
await Promise.all(newVisibility.map((id) => api.toggleSkillVisibility(id, name, true)));
toast.success("Skill created");
toast.success(t("Skill created"));
setNewOpen(false);
setNewName(""); setNewDesc(""); setNewLicense(""); setNewCompat(""); setNewInst("");
setNewMcps([]); setNewVisibility([]);
load();
} catch (e) {
toast.error("Create failed: " + (e as Error).message);
toast.error(t("Create failed: {error}", { error: (e as Error).message }));
} finally { setCreatingSkill(false); }
}
@@ -642,15 +655,15 @@ export default function SkillsPage() {
<span className="min-w-0 flex-1 truncate" title={node.path}>{node.name}</span>
{/* Absolute so a long name can never push the actions out of view */}
<span className="absolute inset-y-0 right-1 hidden items-center gap-0.5 rounded bg-muted pl-1 group-hover:flex">
<Button size="icon" variant="ghost" className="size-5" title="New file"
<Button size="icon" variant="ghost" className="size-5" title={t("New file")}
onClick={(e) => { e.stopPropagation(); startCreate(skill, node.path, "file"); }}>
<FilePlusIcon className="size-3 text-muted-foreground" />
</Button>
<Button size="icon" variant="ghost" className="size-5" title="New folder"
<Button size="icon" variant="ghost" className="size-5" title={t("New folder")}
onClick={(e) => { e.stopPropagation(); startCreate(skill, node.path, "dir"); }}>
<FolderPlusIcon className="size-3 text-muted-foreground" />
</Button>
<Button size="icon" variant="ghost" className="size-5" title="Delete folder"
<Button size="icon" variant="ghost" className="size-5" title={t("Delete folder")}
onClick={(e) => { e.stopPropagation(); setPendingDelete({ kind: "dir", skill, path: node.path }); }}>
<Trash2Icon className="size-3 text-destructive" />
</Button>
@@ -686,7 +699,7 @@ export default function SkillsPage() {
isSelected ? "bg-accent" : "bg-muted",
)}>
<Button size="icon" variant="ghost" className="size-5"
title="Delete file"
title={t("Delete file")}
onClick={(e) => { e.stopPropagation(); setPendingDelete({ kind: "file", skill, path: node.path }); }}>
<Trash2Icon className="size-3 text-destructive" />
</Button>
@@ -704,8 +717,8 @@ export default function SkillsPage() {
<div data-content-padding="false" className="flex flex-1 flex-col overflow-hidden">
<div className="flex items-center gap-3 border-b px-4 py-2.5 lg:px-6">
<div className="flex flex-col gap-0.5">
<h1 className="text-sm font-semibold leading-tight">Skill</h1>
<p className="text-muted-foreground text-xs">Skill library · agentskills.io spec · visibility granted per agent</p>
<h1 className="text-sm font-semibold leading-tight">{t("Skill")}</h1>
<p className="text-muted-foreground text-xs">{t("Skill library · agentskills.io spec · visibility granted per agent")}</p>
</div>
{/* Gap list: skills agents invoke by name but missing from the library — direct evidence of what to add. */}
{missing.length > 0 && (
@@ -713,18 +726,18 @@ export default function SkillsPage() {
<PopoverTrigger asChild>
<Button size="sm" variant="outline" className="ml-auto">
<AlertTriangleIcon className="size-3.5 text-amber-500" />
{missing.length} missed calls
{t("{count} missed calls", { count: missing.length })}
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-80">
<p className="mb-2 text-xs text-muted-foreground">
Skills agents invoke by name that do not exist in the library. Sorted by invocation count.
{t("Skills agents invoke by name that do not exist in the library. Sorted by invocation count.")}
</p>
<div className="space-y-1">
{missing.map((m) => (
<div key={m.skill} className="flex items-center gap-2 text-sm">
<code className="min-w-0 flex-1 truncate font-mono text-xs" title={m.skill}>{m.skill}</code>
<span className="shrink-0 text-xs tabular-nums text-muted-foreground">{m.calls} calls</span>
<span className="shrink-0 text-xs tabular-nums text-muted-foreground">{t("{count} calls", { count: m.calls })}</span>
<span className="shrink-0 text-xs text-muted-foreground">{fmtTime(m.last_used)}</span>
</div>
))}
@@ -738,7 +751,8 @@ export default function SkillsPage() {
<div className="flex w-64 shrink-0 flex-col border-r">
<div className="flex flex-col gap-2 border-b p-2">
<Button size="sm" variant="outline" className="w-full" onClick={() => setNewOpen(true)}>
<PlusIcon className="size-3.5" />Create skill
<PlusIcon className="size-3.5" />
{t("Create skill")}
</Button>
<input
ref={uploadRef}
@@ -753,10 +767,10 @@ export default function SkillsPage() {
className="w-full"
disabled={uploading}
onClick={() => uploadRef.current?.click()}
title="Upload a .zip archive containing SKILL.md"
title={t("Upload a .zip archive containing SKILL.md")}
>
<UploadIcon className="size-3.5" />
{uploading ? "Uploading…" : "Upload archive"}
{uploading ? t("Uploading…") : t("Upload archive")}
</Button>
</div>
{/* Radix viewport wraps children in a display:table div that grows with
@@ -790,7 +804,7 @@ export default function SkillsPage() {
{s.calls > 0 && (
<span
className="shrink-0 rounded bg-muted px-1 text-[10px] tabular-nums text-muted-foreground"
title={`Called ${s.calls} times · last ${fmtTime(s.last_used)}`}
title={t("Called {count} times · last {time}", { count: s.calls, time: fmtTime(s.last_used) })}
>
{s.calls}
</span>
@@ -799,15 +813,15 @@ export default function SkillsPage() {
"absolute inset-y-0 right-1 hidden items-center gap-0.5 rounded pl-1 group-hover:flex",
isSkillSelected ? "bg-accent" : "bg-muted",
)}>
<Button size="icon" variant="ghost" className="size-5" title="New file"
<Button size="icon" variant="ghost" className="size-5" title={t("New file")}
onClick={(e) => { e.stopPropagation(); startCreate(s.name, "", "file"); }}>
<FilePlusIcon className="size-3 text-muted-foreground" />
</Button>
<Button size="icon" variant="ghost" className="size-5" title="New folder"
<Button size="icon" variant="ghost" className="size-5" title={t("New folder")}
onClick={(e) => { e.stopPropagation(); startCreate(s.name, "", "dir"); }}>
<FolderPlusIcon className="size-3 text-muted-foreground" />
</Button>
<Button size="icon" variant="ghost" className="size-5" title="Delete skill"
<Button size="icon" variant="ghost" className="size-5" title={t("Delete skill")}
onClick={(e) => { e.stopPropagation(); setPendingDelete({ kind: "skill", skill: s.name }); }}>
<Trash2Icon className="size-3 text-destructive" />
</Button>
@@ -827,7 +841,7 @@ export default function SkillsPage() {
})}
{skills.length === 0 && (
<p className="p-3 text-xs text-muted-foreground">No skills yet — click "Create" to get started</p>
<p className="p-3 text-xs text-muted-foreground">{t("No skills yet — click \"Create\" to get started")}</p>
)}
</div>
</ScrollArea>
@@ -852,7 +866,9 @@ export default function SkillsPage() {
)}
<div className="mt-2 flex flex-wrap gap-2">
{selectedSkill.license && (
<Badge variant="outline" className="text-xs font-normal">License: {selectedSkill.license}</Badge>
<Badge variant="outline" className="text-xs font-normal">
{t("License: {license}", { license: selectedSkill.license })}
</Badge>
)}
{selectedSkill.compatibility && (
<Badge variant="secondary" className="text-xs font-normal">{selectedSkill.compatibility}</Badge>
@@ -866,50 +882,52 @@ export default function SkillsPage() {
<div className="flex flex-col gap-6 lg:flex-row-reverse lg:items-start">
{/* ── right: call stats ── */}
<div className="space-y-2 lg:w-80 lg:shrink-0">
<Label className="text-xs text-muted-foreground">Call stats</Label>
<Label className="text-xs text-muted-foreground">{t("Call stats")}</Label>
<div className="grid grid-cols-3 gap-2">
<div className="rounded-md border p-2">
<p className="text-lg font-semibold tabular-nums">{selectedSkill.calls}</p>
<p className="text-xs text-muted-foreground">Total calls</p>
<p className="text-xs text-muted-foreground">{t("Total calls")}</p>
</div>
<div className="rounded-md border p-2">
<p className="text-lg font-semibold tabular-nums">{selectedSkill.tasks}</p>
<p className="text-xs text-muted-foreground">Tasks covered</p>
<p className="text-xs text-muted-foreground">{t("Tasks covered")}</p>
</div>
<div className="rounded-md border p-2">
<p className="truncate text-sm font-medium" title={fmtTime(selectedSkill.last_used)}>
{fmtTime(selectedSkill.last_used)}
</p>
<p className="text-xs text-muted-foreground">Last called</p>
<p className="text-xs text-muted-foreground">{t("Last called")}</p>
</div>
</div>
{selectedSkill.usage_agents.length > 0 && (
<div className="flex flex-wrap items-center gap-1">
<span className="text-xs text-muted-foreground">Called by:</span>
<span className="text-xs text-muted-foreground">{t("Called by:")}</span>
{selectedSkill.usage_agents.map((k) => (
<Badge key={k} variant="secondary" className="text-xs font-normal">{k}</Badge>
))}
</div>
)}
{usageLoading ? (
<p className="text-xs text-muted-foreground">Loading call details…</p>
<p className="text-xs text-muted-foreground">{t("Loading call details…")}</p>
) : usageCalls.length > 0 ? (
<div className="rounded-md border">
<div className="border-b px-2 py-1 text-xs text-muted-foreground">Last {usageCalls.length} calls</div>
<div className="border-b px-2 py-1 text-xs text-muted-foreground">
{t("Last {count} calls", { count: usageCalls.length })}
</div>
<div className="max-h-56 overflow-y-auto">
{usageCalls.map((c, i) => (
<div key={`${c.ts}-${i}`} className="flex items-center gap-2 border-b px-2 py-1 text-xs last:border-b-0">
<span className="tabular-nums text-muted-foreground">{fmtTime(c.ts)}</span>
<Badge variant="outline" className="font-normal">{c.agent_key || "—"}</Badge>
<span className="ml-auto text-muted-foreground">
{c.task_id > 0 ? `Task #${c.task_id}` : c.session_id ? "Chat session" : "—"}
{c.task_id > 0 ? t("Task #{id}", { id: c.task_id }) : c.session_id ? t("Chat session") : "—"}
</span>
</div>
))}
</div>
</div>
) : (
<p className="text-xs text-muted-foreground">No call records yet.</p>
<p className="text-xs text-muted-foreground">{t("No call records yet.")}</p>
)}
</div>
@@ -917,11 +935,11 @@ export default function SkillsPage() {
<div className="space-y-5 lg:min-w-0 lg:flex-1">
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">
Linked MCP
<span className="ml-1 font-normal"> (tools are disclosed/unlocked only when the skill loads)</span>
{t("Linked MCP")}
<span className="ml-1 font-normal"> {t("(tools are disclosed/unlocked only when the skill loads)")}</span>
</Label>
{mcpOptions.length === 0 ? (
<p className="text-xs text-muted-foreground">No MCP servers yet; add one on the "MCP" page.</p>
<p className="text-xs text-muted-foreground">{t('No MCP servers yet; add one on the "MCP" page.')}</p>
) : (
<div className="flex flex-wrap gap-x-4 gap-y-2">
{mcpOptions.map((m) => (
@@ -938,7 +956,7 @@ export default function SkillsPage() {
</div>
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">Visibility (granted per agent)</Label>
<Label className="text-xs text-muted-foreground">{t("Visibility (granted per agent)")}</Label>
<div className="space-y-2">
{agents.map((a) => (
<label key={a.key} className="flex cursor-pointer items-center gap-2 text-sm">
@@ -950,7 +968,7 @@ export default function SkillsPage() {
</label>
))}
{agents.length === 0 && (
<span className="text-xs text-muted-foreground">(no agents)</span>
<span className="text-xs text-muted-foreground">{t("(no agents)")}</span>
)}
</div>
</div>
@@ -966,11 +984,11 @@ export default function SkillsPage() {
<span>/</span>
<span className="font-mono">{selected.path}</span>
<Button size="sm" className="ml-auto" onClick={saveFile} disabled={!dirty || saving}>
{saving ? "Saving…" : "Save"}
{saving ? t("Saving…") : t("Save")}
</Button>
</div>
{fileLoading ? (
<p className="text-xs text-muted-foreground">Loading…</p>
<p className="text-xs text-muted-foreground">{t("Loading…")}</p>
) : (
<Textarea
className="flex-1 resize-none font-mono text-xs"
@@ -988,25 +1006,25 @@ export default function SkillsPage() {
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{pendingDelete?.kind === "skill" && `Delete skill "${pendingDelete.skill}"?`}
{pendingDelete?.kind === "dir" && `Delete folder "${pendingDelete.path}"?`}
{pendingDelete?.kind === "file" && `Delete file "${pendingDelete.path}"?`}
{pendingDelete?.kind === "skill" && t('Delete skill "{name}"?', { name: pendingDelete.skill })}
{pendingDelete?.kind === "dir" && t('Delete folder "{path}"?', { path: pendingDelete.path })}
{pendingDelete?.kind === "file" && t('Delete file "{path}"?', { path: pendingDelete.path })}
</AlertDialogTitle>
<AlertDialogDescription>
{pendingDelete?.kind === "skill"
? "This deletes all of the skill's files, MCP links and visibility config. This action cannot be undone."
? t("This deletes all of the skill's files, MCP links and visibility config. This action cannot be undone.")
: pendingDelete?.kind === "dir"
? "This also deletes all files under the folder. This action cannot be undone."
: "This action cannot be undone."}
? t("This also deletes all files under the folder. This action cannot be undone.")
: t("This action cannot be undone.")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
<AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction
disabled={deleting}
onClick={(e) => { e.preventDefault(); void runPendingDelete(); }}
>
{deleting ? "Deleting…" : "Delete"}
{deleting ? t("Deleting…") : t("Delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -1016,13 +1034,13 @@ export default function SkillsPage() {
<Sheet open={newOpen} onOpenChange={setNewOpen}>
<SheetContent side="right" className="flex w-full flex-col gap-0 data-[side=right]:sm:max-w-xl">
<SheetHeader className="px-4 pt-4">
<SheetTitle>Create skill</SheetTitle>
<SheetTitle>{t("Create skill")}</SheetTitle>
</SheetHeader>
<Tabs defaultValue="basic" className="flex min-h-0 flex-1 flex-col">
<TabsList className="mx-4 mt-3 shrink-0 justify-start">
<TabsTrigger value="basic">Basics</TabsTrigger>
<TabsTrigger value="basic">{t("Basics")}</TabsTrigger>
<TabsTrigger value="mcp">
Linked MCP
{t("Linked MCP")}
{newMcps.length > 0 && (
<span className="ml-1.5 rounded-full bg-primary px-1.5 py-0.5 text-[10px] leading-none text-primary-foreground">
{newMcps.length}
@@ -1030,7 +1048,7 @@ export default function SkillsPage() {
)}
</TabsTrigger>
<TabsTrigger value="visibility">
Visibility
{t("Visibility")}
{newVisibility.length > 0 && (
<span className="ml-1.5 rounded-full bg-primary px-1.5 py-0.5 text-[10px] leading-none text-primary-foreground">
{newVisibility.length}
@@ -1042,40 +1060,45 @@ export default function SkillsPage() {
{/* basics */}
<TabsContent value="basic" className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4 pt-4 data-[state=inactive]:hidden">
<div className="grid gap-1.5">
<Label htmlFor="sk-name">Name <span className="text-destructive">*</span></Label>
<Label htmlFor="sk-name">{t("Name")} <span className="text-destructive">*</span></Label>
<Input id="sk-name" placeholder="sqli-deepdive" value={newName} onChange={(e) => setNewName(e.target.value)} />
<p className="text-muted-foreground text-xs">Lowercase letters / digits / hyphens, 1–64 characters</p>
<p className="text-muted-foreground text-xs">{t("Lowercase letters / digits / hyphens, 1–64 characters")}</p>
</div>
<div className="grid gap-1.5">
<Label htmlFor="sk-desc">Description <span className="text-destructive">*</span></Label>
<Label htmlFor="sk-desc">{t("Description")} <span className="text-destructive">*</span></Label>
<Textarea id="sk-desc" rows={2} className="resize-none"
placeholder="What this skill does and when to use it."
placeholder={t("What this skill does and when to use it.")}
value={newDesc} onChange={(e) => setNewDesc(e.target.value)} />
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid gap-1.5">
<Label className="text-muted-foreground text-xs">license</Label>
<Input placeholder="MIT / Proprietary" value={newLicense} onChange={(e) => setNewLicense(e.target.value)} />
<Input placeholder={t("MIT / Proprietary")} value={newLicense} onChange={(e) => setNewLicense(e.target.value)} />
</div>
<div className="grid gap-1.5">
<Label className="text-muted-foreground text-xs">compatibility</Label>
<Input placeholder="Requires sqlmap, python3" value={newCompat} onChange={(e) => setNewCompat(e.target.value)} />
<Input placeholder={t("Requires sqlmap, python3")} value={newCompat} onChange={(e) => setNewCompat(e.target.value)} />
</div>
</div>
<div className="flex min-h-0 flex-1 flex-col gap-1.5">
<Label htmlFor="sk-inst">Body <span className="text-muted-foreground text-xs font-normal">(skeleton generated automatically when empty)</span></Label>
<Label htmlFor="sk-inst">
{t("Body")}{" "}
<span className="text-muted-foreground text-xs font-normal">{t("(skeleton generated automatically when empty)")}</span>
</Label>
<Textarea id="sk-inst"
className="min-h-40 flex-1 resize-none font-mono text-sm leading-relaxed"
placeholder={"## How to run\n\n1. Probe for errors first\n2. Distinguish blind injection types\n\nScripts go in the scripts/ directory."}
placeholder={t(
"## How to run\n\n1. Probe for errors first\n2. Distinguish blind injection types\n\nScripts go in the scripts/ directory.",
)}
value={newInst} onChange={(e) => setNewInst(e.target.value)} />
</div>
</TabsContent>
{/* linked MCP */}
<TabsContent value="mcp" className="overflow-y-auto px-4 pb-4 pt-4 data-[state=inactive]:hidden">
<p className="mb-3 text-xs text-muted-foreground">The selected MCP's tools are disclosed and unlocked only when the skill loads.</p>
<p className="mb-3 text-xs text-muted-foreground">{t("The selected MCP's tools are disclosed and unlocked only when the skill loads.")}</p>
{mcpOptions.length === 0 ? (
<p className="text-xs text-muted-foreground">No MCP servers yet; add one on the "MCP" page.</p>
<p className="text-xs text-muted-foreground">{t('No MCP servers yet; add one on the "MCP" page.')}</p>
) : (
<div className="flex flex-col gap-2">
{mcpOptions.map((m) => (
@@ -1095,9 +1118,9 @@ export default function SkillsPage() {
{/* visibility */}
<TabsContent value="visibility" className="overflow-y-auto px-4 pb-4 pt-4 data-[state=inactive]:hidden">
<p className="mb-3 text-xs text-muted-foreground">The selected agents will see this skill once it is created.</p>
<p className="mb-3 text-xs text-muted-foreground">{t("The selected agents will see this skill once it is created.")}</p>
{agents.length === 0 ? (
<p className="text-xs text-muted-foreground">(no agents)</p>
<p className="text-xs text-muted-foreground">{t("(no agents)")}</p>
) : (
<div className="flex flex-col gap-2">
{agents.map((a) => (
@@ -1117,8 +1140,8 @@ export default function SkillsPage() {
</Tabs>
<SheetFooter className="flex-row justify-end gap-2 border-t px-4 py-3">
<Button variant="outline" onClick={() => setNewOpen(false)}>Cancel</Button>
<Button onClick={createNewSkill} disabled={creatingSkill}>{creatingSkill ? "Creating…" : "Create"}</Button>
<Button variant="outline" onClick={() => setNewOpen(false)}>{t("Cancel")}</Button>
<Button onClick={createNewSkill} disabled={creatingSkill}>{creatingSkill ? t("Creating…") : t("Create")}</Button>
</SheetFooter>
</SheetContent>
</Sheet>
+109 -81
View File
@@ -34,6 +34,7 @@ import {
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { Agent, Tool } from "@/lib/types";
@@ -176,11 +177,11 @@ function ToolEditor({
agents: bound,
enabled,
});
toast.success(`Tool "${tool.key}" saved`);
toast.success(t('Tool "{key}" saved', { key: tool.key }));
onSaved();
onClose();
} catch (e) {
toast.error("Save failed: " + (e as Error).message);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
}
@@ -188,11 +189,11 @@ function ToolEditor({
async function reset() {
try {
await api.resetTool(tool.key);
toast.success(`Restored "${tool.key}" to the code default`);
toast.success(t('Restored "{key}" to the code default', { key: tool.key }));
onSaved();
onClose();
} catch (e) {
toast.error("Restore failed: " + (e as Error).message);
toast.error(t("Restore failed: {error}", { error: (e as Error).message }));
}
}
@@ -201,13 +202,23 @@ function ToolEditor({
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4">
{trafficGated && (
<div className="border-amber-500/40 bg-amber-500/10 text-muted-foreground rounded-md border px-3 py-2 text-xs">
This tool depends on <b>traffic capture</b>. Enable traffic capture under "System settings" first before binding it to agents and enabling it.
{(() => {
const [before, after] = t("This tool depends on {capture}.").split("{capture}");
return (
<>
{before}
<b>{t("traffic capture")}</b>
{after}
</>
);
})()}{" "}
{t('Enable traffic capture under "System settings" first before binding it to agents and enabling it.')}
</div>
)}
{/* binding + switch */}
<div className="flex flex-wrap items-center gap-x-6 gap-y-3">
<div className="grid gap-1.5">
<Label className="text-muted-foreground text-xs">Bind agents (controls which agents get this tool)</Label>
<Label className="text-muted-foreground text-xs">{t("Bind agents (controls which agents get this tool)")}</Label>
<div className="flex flex-wrap gap-3">
{agents.map((ag) => (
<label key={ag.key} className="flex items-center gap-2 text-sm">
@@ -220,20 +231,20 @@ function ToolEditor({
<span className="text-muted-foreground font-mono text-xs">{ag.key}</span>
</label>
))}
{agents.length === 0 && <span className="text-muted-foreground text-xs">(no agents)</span>}
{agents.length === 0 && <span className="text-muted-foreground text-xs">{t("(no agents)")}</span>}
</div>
</div>
<div className="flex items-center gap-2">
<Switch checked={enabled} onCheckedChange={setEnabled} id={`en-${tool.key}`} />
<Label htmlFor={`en-${tool.key}`} className="text-sm">
Enable
{t("Enable")}
</Label>
</div>
</div>
{/* description */}
<div className="grid gap-1.5">
<Label className="text-muted-foreground text-xs">Tool description (sent to the model)</Label>
<Label className="text-muted-foreground text-xs">{t("Tool description (sent to the model)")}</Label>
<Textarea
className="font-mono text-xs"
rows={6}
@@ -245,9 +256,9 @@ function ToolEditor({
{/* params */}
<div className="grid gap-2">
<Label className="text-muted-foreground text-xs">
Parameters (name / type / required are read-only; description and default are editable)
{t("Parameters (name / type / required are read-only; description and default are editable)")}
</Label>
{rows.length === 0 && <span className="text-muted-foreground text-xs">(no parameters)</span>}
{rows.length === 0 && <span className="text-muted-foreground text-xs">{t("(no parameters)")}</span>}
{rows.map((r, i) => (
<div
key={(r.parentKey ?? "") + "." + r.name}
@@ -264,16 +275,16 @@ function ToolEditor({
</Badge>
{r.required && (
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
Required
{t("Required")}
</Badge>
)}
{r.parentKey && (
<span className="text-muted-foreground text-[10px]">items sub-field</span>
<span className="text-muted-foreground text-[10px]">{t("items sub-field")}</span>
)}
</div>
<div className="grid gap-2">
<div className="grid gap-1">
<Label className="text-muted-foreground text-[11px]">Description</Label>
<Label className="text-muted-foreground text-[11px]">{t("Description")}</Label>
<Input
className="text-xs"
value={r.description}
@@ -281,10 +292,10 @@ function ToolEditor({
/>
</div>
<div className="grid gap-1">
<Label className="text-muted-foreground text-[11px]">Default</Label>
<Label className="text-muted-foreground text-[11px]">{t("Default")}</Label>
<Input
className="text-xs"
placeholder={r.scalar ? "(empty = no default)" : "scalars only"}
placeholder={r.scalar ? t("(empty = no default)") : t("scalars only")}
disabled={!r.scalar}
value={r.defaultStr}
onChange={(e) => setRow(i, { defaultStr: e.target.value })}
@@ -299,10 +310,10 @@ function ToolEditor({
<Separator className="mt-4" />
<div className="flex flex-wrap gap-2 p-4">
<Button size="sm" onClick={save} disabled={saving}>
<SaveIcon /> Save
<SaveIcon /> {t("Save")}
</Button>
<Button size="sm" variant="outline" onClick={reset}>
<RotateCcwIcon /> Restore defaults
<RotateCcwIcon /> {t("Restore defaults")}
</Button>
</div>
</div>
@@ -321,37 +332,37 @@ function ToolGridCard({ tool, onClick }: { tool: Tool; onClick: () => void }) {
<span className="font-mono text-sm font-medium">{tool.key}</span>
{tool.system ? (
<Badge variant="secondary" className="px-1.5 py-0 text-[10px]">
System
{t("System")}
</Badge>
) : (
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
Custom · {tool.kind}
{t("Custom · {kind}", { kind: tool.kind ?? "" })}
</Badge>
)}
{tool.deferred && (
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
deferred
{t("deferred")}
</Badge>
)}
{!tool.enabled && (
<Badge variant="outline" className="text-destructive px-1.5 py-0 text-[10px]">
Disabled
{t("Disabled")}
</Badge>
)}
<Badge
variant="secondary"
className="ml-auto px-1.5 py-0 text-[10px] tabular-nums"
title={`${tool.calls ?? 0} calls in total`}
title={t("{count} calls in total", { count: tool.calls ?? 0 })}
>
{tool.calls ?? 0} calls
{t("{count} calls", { count: tool.calls ?? 0 })}
</Badge>
</div>
<p className="text-muted-foreground line-clamp-1 h-4 text-xs">
{tool.description || "(no description)"}
{tool.description || t("(no description)")}
</p>
<div className="mt-auto flex flex-wrap gap-1 pt-1">
{tool.agents.length === 0 && (
<span className="text-muted-foreground text-[10px]">(no agents bound)</span>
<span className="text-muted-foreground text-[10px]">{t("(no agents bound)")}</span>
)}
{tool.agents.map((a) => (
<Badge key={a} variant="outline" className="px-1.5 py-0 text-[10px]">
@@ -402,14 +413,14 @@ export default function ToolsPage() {
<div className="flex flex-1 flex-col gap-4 md:gap-6">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-xl font-semibold tracking-tight">Tools</h1>
<p className="text-muted-foreground text-sm">Descriptions/bindings for system tools, plus custom tools (command/script/http)</p>
<h1 className="text-xl font-semibold tracking-tight">{t("Tools")}</h1>
<p className="text-muted-foreground text-sm">{t("Descriptions/bindings for system tools, plus custom tools (command/script/http)")}</p>
</div>
<div className="relative w-64">
<SearchIcon className="text-muted-foreground absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2" />
<Input
className="h-8 pl-8 text-sm"
placeholder="Search tool name, description, agent…"
placeholder={t("Search tool name, description, agent…")}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
@@ -418,24 +429,29 @@ export default function ToolsPage() {
<Tabs defaultValue="system">
<TabsList>
<TabsTrigger value="system">System tools</TabsTrigger>
<TabsTrigger value="custom">Custom tools</TabsTrigger>
<TabsTrigger value="system">{t("System tools")}</TabsTrigger>
<TabsTrigger value="custom">{t("Custom tools")}</TabsTrigger>
</TabsList>
<TabsContent value="system">
<Card>
<CardHeader>
<CardTitle>System tools</CardTitle>
<CardTitle>{t("System tools")}</CardTitle>
<CardDescription>
{query.trim()
? `${systemTools.length} / ${allSystemCount} matching; click a card to edit the description, parameter defaults and agent bindings`
: `${allSystemCount} total; click a card to edit the description, parameter defaults and agent bindings`}
? t(
"{count} / {total} matching; click a card to edit the description, parameter defaults and agent bindings",
{ count: systemTools.length, total: allSystemCount },
)
: t("{total} total; click a card to edit the description, parameter defaults and agent bindings", {
total: allSystemCount,
})}
</CardDescription>
</CardHeader>
<CardContent>
{systemTools.length === 0 ? (
<p className="text-muted-foreground py-6 text-center text-sm">
{query.trim() ? "No matching system tools" : "(no system tools yet, waiting for the backend seed)"}
{query.trim() ? t("No matching system tools") : t("(no system tools yet, waiting for the backend seed)")}
</p>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
@@ -453,22 +469,28 @@ export default function ToolsPage() {
<CardHeader>
<div className="flex items-start justify-between gap-3">
<div>
<CardTitle>Custom tools</CardTitle>
<CardTitle>{t("Custom tools")}</CardTitle>
<CardDescription>
{query.trim()
? `shell/command/script/http, ${customTools.length} / ${allCustomCount} matching; click a card to edit`
: `shell (bash declaration) / command (command template) / script (Python) / http (API), ${allCustomCount} total; click a card to edit`}
? t("shell/command/script/http, {count} / {total} matching; click a card to edit", {
count: customTools.length,
total: allCustomCount,
})
: t(
"shell (bash declaration) / command (command template) / script (Python) / http (API), {total} total; click a card to edit",
{ total: allCustomCount },
)}
</CardDescription>
</div>
<Button size="sm" onClick={() => setCustomEdit("new")}>
<PlusIcon /> Create custom tool
<PlusIcon /> {t("Create custom tool")}
</Button>
</div>
</CardHeader>
<CardContent>
{customTools.length === 0 ? (
<p className="text-muted-foreground py-6 text-center text-sm">
{query.trim() ? "No matching custom tools" : "(no custom tools yet; click 'Create custom tool' in the top right)"}
{query.trim() ? t("No matching custom tools") : t("(no custom tools yet; click 'Create custom tool' in the top right)")}
</p>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
@@ -491,7 +513,7 @@ export default function ToolsPage() {
<>
<SheetHeader className="px-4">
<SheetTitle className="font-mono">{selected.key}</SheetTitle>
<SheetDescription>Edit the description, parameter defaults and agent bindings</SheetDescription>
<SheetDescription>{t("Edit the description, parameter defaults and agent bindings")}</SheetDescription>
</SheetHeader>
<ToolEditor
key={selected.key}
@@ -609,20 +631,20 @@ function CustomToolDialog({
async function save() {
if (isNew && !/^[a-z][a-z0-9_]*$/.test(key.trim())) {
toast.error("key must start with a lowercase letter and contain only lowercase letters/digits/underscores");
toast.error(t("key must start with a lowercase letter and contain only lowercase letters/digits/underscores"));
return;
}
let schema: Record<string, unknown> = {};
if (schemaText.trim()) {
try { schema = JSON.parse(schemaText); } catch { toast.error("Invalid parameter JSON Schema"); return; }
try { schema = JSON.parse(schemaText); } catch { toast.error(t("Invalid parameter JSON Schema")); return; }
}
if (kind === "http" && ex.headers.trim()) {
try { JSON.parse(ex.headers); } catch { toast.error("Invalid headers JSON"); return; }
try { JSON.parse(ex.headers); } catch { toast.error(t("Invalid headers JSON")); return; }
}
if (kind === "http") {
const props = (schema as { properties?: Record<string, unknown> }).properties;
if (!props || Object.keys(props).length === 0) {
toast.error("http tools must provide a parameter JSON Schema (with properties; cannot be empty)");
toast.error(t("http tools must provide a parameter JSON Schema (with properties; cannot be empty)"));
return;
}
}
@@ -631,10 +653,10 @@ function CustomToolDialog({
try {
if (isNew) await api.createCustomTool({ key: key.trim(), ...payload });
else await api.updateCustomTool(tool!.key, payload);
toast.success(isNew ? "Custom tool created" : "Saved");
toast.success(isNew ? t("Custom tool created") : t("Saved"));
onSaved();
} catch (e) {
toast.error("Save failed: " + (e as Error).message);
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
}
@@ -643,10 +665,10 @@ function CustomToolDialog({
if (!tool) return;
try {
await api.deleteCustomTool(tool.key);
toast.success("Deleted");
toast.success(t("Deleted"));
onSaved();
} catch (e) {
toast.error("Delete failed: " + (e as Error).message);
toast.error(t("Delete failed: {error}", { error: (e as Error).message }));
}
}
// runTest dry-runs the CURRENT form (unsaved) with the sample params, so a
@@ -654,10 +676,10 @@ function CustomToolDialog({
async function runTest() {
let params: Record<string, unknown> = {};
if (paramsText.trim()) {
try { params = JSON.parse(paramsText); } catch { toast.error("Invalid test parameter JSON"); return; }
try { params = JSON.parse(paramsText); } catch { toast.error(t("Invalid test parameter JSON")); return; }
}
if (kind === "http" && ex.headers.trim()) {
try { JSON.parse(ex.headers); } catch { toast.error("Invalid headers JSON"); return; }
try { JSON.parse(ex.headers); } catch { toast.error(t("Invalid headers JSON")); return; }
}
setTesting(true);
setTestResult(null);
@@ -679,47 +701,51 @@ function CustomToolDialog({
className="flex flex-col gap-0 p-0 data-[side=right]:w-[45vw] data-[side=right]:sm:max-w-[45vw] data-[side=right]:min-w-[480px]"
>
<SheetHeader className="px-4">
<SheetTitle>{isNew ? "Create custom tool" : `Edit ${tool?.key}`}</SheetTitle>
<SheetDescription>shell = a bash environment declaration (name + description only, telling the model bash is available); command/script/http need an execution spec.</SheetDescription>
<SheetTitle>{isNew ? t("Create custom tool") : t("Edit {key}", { key: tool?.key ?? "" })}</SheetTitle>
<SheetDescription>
{t(
"shell = a bash environment declaration (name + description only, telling the model bash is available); command/script/http need an execution spec.",
)}
</SheetDescription>
</SheetHeader>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4">
<div className="grid gap-1.5">
<Label className="text-xs">Key</Label>
<Input className="font-mono" placeholder="e.g. nmap_scan" value={key} disabled={!isNew}
<Label className="text-xs">{t("Key")}</Label>
<Input className="font-mono" placeholder={t("e.g. nmap_scan")} value={key} disabled={!isNew}
onChange={(e) => setKey(e.target.value)} />
</div>
<div className="grid gap-1.5">
<Label className="text-xs">Description (sent to the model)</Label>
<Label className="text-xs">{t("Description (sent to the model)")}</Label>
<Textarea rows={2} value={description} onChange={(e) => setDescription(e.target.value)} />
</div>
<div className="grid gap-1.5">
<Label className="text-xs">Type</Label>
<Label className="text-xs">{t("Type")}</Label>
<Select value={kind} onValueChange={(v) => setKind(v as "shell" | "command" | "script" | "http")}>
<SelectTrigger className="w-56"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="shell">shell (bash environment declaration)</SelectItem>
<SelectItem value="command">command (shell command template)</SelectItem>
<SelectItem value="script">script (Python script)</SelectItem>
<SelectItem value="http">http (API request)</SelectItem>
<SelectItem value="shell">{t("shell (bash environment declaration)")}</SelectItem>
<SelectItem value="command">{t("command (shell command template)")}</SelectItem>
<SelectItem value="script">{t("script (Python script)")}</SelectItem>
<SelectItem value="http">{t("http (API request)")}</SelectItem>
</SelectContent>
</Select>
{kind === "shell" && (
<p className="text-muted-foreground text-xs">Suited to well-known tools like nmap, sqlmap, ffuf — the model already knows their usage; you only need to declare "can be invoked in bash". The name + description are appended to the Bash tool's description.</p>
<p className="text-muted-foreground text-xs">{t("Suited to well-known tools like nmap, sqlmap, ffuf — the model already knows their usage; you only need to declare \"can be invoked in bash\". The name + description are appended to the Bash tool's description.")}</p>
)}
</div>
{kind === "command" && (
<div className="grid gap-1.5">
<Label className="text-xs">Command template (placeholder {"{param}"}, e.g. nmap -p {"{ports}"} {"{target}"})</Label>
<Label className="text-xs">{t("Command template (placeholder {param}, e.g. nmap -p {ports} {target})")}</Label>
<Textarea className="font-mono text-xs" rows={2} value={ex.command}
onChange={(e) => setEx({ ...ex, command: e.target.value })} />
</div>
)}
{kind === "script" && (
<div className="grid gap-1.5">
<Label className="text-xs">Python body (params arrive via stdin JSON / os.environ["TOOL_X"])</Label>
<Label className="text-xs">{t("Python body (params arrive via stdin JSON / os.environ[\"TOOL_X\"])")}</Label>
<Textarea className="font-mono text-xs" rows={10} value={ex.code}
placeholder={'import json,sys\nargs=json.load(sys.stdin)\nprint(...)'}
onChange={(e) => setEx({ ...ex, code: e.target.value })} />
@@ -729,31 +755,31 @@ function CustomToolDialog({
<div className="grid gap-2">
<div className="flex gap-2">
<div className="grid gap-1.5">
<Label className="text-xs">Method</Label>
<Label className="text-xs">{t("Method")}</Label>
<Input className="w-24" value={ex.method} onChange={(e) => setEx({ ...ex, method: e.target.value })} />
</div>
<div className="grid flex-1 gap-1.5">
<Label className="text-xs">URL (may contain {"{param}"})</Label>
<Label className="text-xs">{t("URL (may contain {param})")}</Label>
<Input className="font-mono text-xs" value={ex.url} onChange={(e) => setEx({ ...ex, url: e.target.value })} />
</div>
</div>
<div className="grid gap-1.5">
<Label className="text-xs">Headers (JSON, may contain {"{param}"})</Label>
<Label className="text-xs">{t("Headers (JSON, may contain {param})")}</Label>
<Textarea className="font-mono text-xs" rows={2} value={ex.headers}
placeholder={'{"Authorization": "Bearer {token}"}'} onChange={(e) => setEx({ ...ex, headers: e.target.value })} />
</div>
<div className="grid gap-1.5">
<Label className="text-xs">Body (may contain {"{param}"})</Label>
<Label className="text-xs">{t("Body (may contain {param})")}</Label>
<Textarea className="font-mono text-xs" rows={2} value={ex.body} onChange={(e) => setEx({ ...ex, body: e.target.value })} />
</div>
<div className="flex items-center gap-4">
<div className="grid gap-1.5">
<Label className="text-xs">Proxy URL (empty = direct)</Label>
<Label className="text-xs">{t("Proxy URL (empty = direct)")}</Label>
<Input className="font-mono text-xs w-56" value={ex.proxy} onChange={(e) => setEx({ ...ex, proxy: e.target.value })} />
</div>
<label className="mt-4 flex items-center gap-2 text-sm">
<Checkbox checked={ex.use_recording_proxy} onCheckedChange={(v) => setEx({ ...ex, use_recording_proxy: !!v })} />
Use recording proxy
{t("Use recording proxy")}
</label>
</div>
</div>
@@ -762,7 +788,7 @@ function CustomToolDialog({
{kind !== "shell" && (
<div className="flex items-center gap-3">
<div className="grid gap-1.5">
<Label className="text-xs">Timeout (ms, empty = default)</Label>
<Label className="text-xs">{t("Timeout (ms, empty = default)")}</Label>
<Input type="number" className="w-32" value={ex.timeout_ms} onChange={(e) => setEx({ ...ex, timeout_ms: e.target.value })} />
</div>
</div>
@@ -771,7 +797,9 @@ function CustomToolDialog({
{kind !== "shell" && (
<div className="grid gap-1.5">
<Label className="text-xs">
Parameter JSON Schema{kind === "http" ? " (required for http tools, must include properties)" : " (empty = a thin {args} shell is generated automatically)"}
{kind === "http"
? t("Parameter JSON Schema (required for http tools, must include properties)")
: t("Parameter JSON Schema (empty = a thin {args} shell is generated automatically)")}
</Label>
<Textarea className="font-mono text-xs" rows={4} value={schemaText}
placeholder={'{"type":"object","properties":{"target":{"type":"string"}},"required":["target"]}'}
@@ -780,7 +808,7 @@ function CustomToolDialog({
)}
<div className="grid gap-1.5">
<Label className="text-muted-foreground text-xs">Bind agents</Label>
<Label className="text-muted-foreground text-xs">{t("Bind agents")}</Label>
<div className="flex flex-wrap gap-3">
{agents.map((a) => (
<label key={a.key} className="flex items-center gap-2 text-sm">
@@ -793,24 +821,24 @@ function CustomToolDialog({
<div className="flex items-center gap-6">
<label className="flex items-center gap-2 text-sm">
<Switch checked={enabled} onCheckedChange={setEnabled} /> Enable
<Switch checked={enabled} onCheckedChange={setEnabled} /> {t("Enable")}
</label>
{kind !== "shell" && (
<label className="flex items-center gap-2 text-sm">
<Switch checked={deferred} onCheckedChange={setDeferred} /> deferred (enable only for many rarely-used tools)
<Switch checked={deferred} onCheckedChange={setDeferred} /> {t("deferred (enable only for many rarely-used tools)")}
</label>
)}
</div>
{kind !== "shell" && (
<div className="grid gap-1.5 rounded-md border p-3">
<Label className="text-xs font-medium">Test run (uses the current form, nothing is saved)</Label>
<Label className="text-xs font-medium">{t("Test run (uses the current form, nothing is saved)")}</Label>
<Textarea className="font-mono text-xs" rows={2} value={paramsText}
placeholder={'Sample params JSON, e.g. {"target":"example.com"}'}
placeholder={t('Sample params JSON, e.g. {"target":"example.com"}')}
onChange={(e) => setParamsText(e.target.value)} />
<div>
<Button size="sm" variant="outline" onClick={runTest} disabled={testing}>
<PlayIcon /> {testing ? "Running…" : "Test run"}
<PlayIcon /> {testing ? t("Running…") : t("Test run")}
</Button>
</div>
{testResult && (
@@ -820,7 +848,7 @@ function CustomToolDialog({
(testResult.is_error ? "text-destructive" : "")
}
>
{testResult.output || "(no output)"}
{testResult.output || t("(no output)")}
</pre>
)}
</div>
@@ -830,11 +858,11 @@ function CustomToolDialog({
<Separator />
<div className="flex items-center gap-2 p-4">
<Button size="sm" onClick={save} disabled={saving}>
<SaveIcon /> {isNew ? "Create" : "Save"}
<SaveIcon /> {isNew ? t("Create") : t("Save")}
</Button>
{!isNew && (
<Button size="sm" variant="outline" className="text-destructive" onClick={del}>
<Trash2Icon /> Delete
<Trash2Icon /> {t("Delete")}
</Button>
)}
</div>
+11 -3
View File
@@ -1,16 +1,24 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { t } from "@/i18n";
export default function NotFound() {
// This page is prerendered in the build-time locale; render the text only on the
// client so a reader in another locale gets no hydration mismatch.
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return <div className="h-dvh" />;
return (
<div className="flex h-dvh flex-col items-center justify-center space-y-2 text-center">
<h1 className="font-semibold text-2xl">Page not found.</h1>
<p className="text-muted-foreground">The page you are looking for could not be found.</p>
<h1 className="font-semibold text-2xl">{t("Page not found.")}</h1>
<p className="text-muted-foreground">{t("The page you are looking for could not be found.")}</p>
<Link prefetch={false} replace href="/function/tasks">
<Button variant="outline">Go back home</Button>
<Button variant="outline">{t("Go back home")}</Button>
</Link>
</div>
);
File diff suppressed because it is too large Load Diff
@@ -4,6 +4,7 @@ import * as React from "react";
import { Button } from "@/components/ui/button";
import { api } from "@/lib/api";
import type { Activity, InterceptExecution } from "@/lib/types";
import { t } from "@/i18n";
// Resolve one exact persisted call, independently of transcript pagination.
export function useApprovalFocus({ taskId, conversationId }: { taskId?: string; conversationId?: number }) {
@@ -34,12 +35,12 @@ export function useApprovalFocus({ taskId, conversationId }: { taskId?: string;
? source.conversation_id !== conversationId
: source.task_id !== taskId || source.conversation_id != null
) {
throw new Error("Approval source does not match the current conversation");
throw new Error(t("Approval source does not match the current conversation"));
}
setState({ id, source, loading: false });
})
.catch((e) => {
if (!cancelled) setState({ id, error: (e as Error).message || "Unable to locate the original execution", loading: false });
if (!cancelled) setState({ id, error: (e as Error).message || t("Unable to locate the original execution"), loading: false });
});
return () => {
cancelled = true;
@@ -78,13 +79,13 @@ export function useApprovalHistory(
const page = await loadPage(before);
if (cancelled) return;
if (!page.items.length || (before > 0 && page.items[0].seq >= before)) {
throw new Error("Matching tool call not found in the conversation; the record may have been deleted");
throw new Error(t("Matching tool call not found in the conversation; the record may have been deleted"));
}
mergePage(page);
current = page.items;
before = current[0].seq;
if (!page.hasMore && !current.some((a) => a.seq === source.seq)) {
throw new Error("Matching tool call not found in the conversation");
throw new Error(t("Matching tool call not found in the conversation"));
}
}
if (!cancelled) setResult({ source });
@@ -118,19 +119,19 @@ export function ApprovalExecutionFocus({
>
<span className={error ? "text-destructive" : "text-muted-foreground"}>
{error
? `Unable to locate: ${error}`
? t("Unable to locate: {error}", { error })
: history.ready
? `Expanded the tool call for approval #${state.id}`
: `Loading the conversation position of approval #${state.id}…`}
? t("Expanded the tool call for approval #{id}", { id: state.id })
: t("Loading the conversation position of approval #{id}…", { id: state.id })}
</span>
<div className="flex gap-2">
{error ? (
<Button size="sm" variant="outline" onClick={focus.retry}>
Retry locate
{t("Retry locate")}
</Button>
) : null}
<Button size="sm" variant="ghost" onClick={focus.close}>
Cancel locate
{t("Cancel locate")}
</Button>
</div>
</div>
+221 -169
View File
@@ -48,10 +48,11 @@ import type {
} from "@/lib/types";
import { cn } from "@/lib/utils";
import { setVisibleInterval } from "@/lib/polling";
import { intlLocale, t } from "@/i18n";
function fmtTime(value?: string) {
if (!value) return "—";
return new Date(value).toLocaleString("zh-CN", {
return new Date(value).toLocaleString(intlLocale, {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
@@ -68,13 +69,13 @@ function source(row: InterceptApprovalRow) {
function originLabel(row: InterceptApprovalRow) {
if (row.task_id) return row.task_id;
if (row.conversation_id) return `Conversation #${row.conversation_id}`;
if (row.conversation_id) return t("Conversation #{id}", { id: row.conversation_id });
return "—";
}
function ApprovalOrigin({ row, detail = false }: { row: InterceptApprovalRow; detail?: boolean }) {
const [locating, setLocating] = React.useState(false);
const label = detail && row.task_id ? `Task ${row.task_id}` : originLabel(row);
const label = detail && row.task_id ? t("Task {id}", { id: row.task_id }) : originLabel(row);
const query = new URLSearchParams({ approval: String(row.id) });
let href: string | undefined;
if (row.conversation_id) {
@@ -88,7 +89,7 @@ function ApprovalOrigin({ row, detail = false }: { row: InterceptApprovalRow; de
<a
href={href}
className="text-primary underline-offset-4 hover:underline"
aria-label={`Locate the source of approval #${row.id}: ${label}`}
aria-label={t("Locate the source of approval #{id}: {label}", { id: row.id, label })}
aria-busy={locating}
onClick={async (e) => {
e.stopPropagation();
@@ -100,7 +101,7 @@ function ApprovalOrigin({ row, detail = false }: { row: InterceptApprovalRow; de
await api.interceptExecution(row.id, row.conversation_id ?? undefined);
window.location.assign(href);
} catch (error) {
toast.error((error as Error).message || "Unable to locate the corresponding execution");
toast.error((error as Error).message || t("Unable to locate the corresponding execution"));
setLocating(false);
}
}}
@@ -113,7 +114,12 @@ function ApprovalOrigin({ row, detail = false }: { row: InterceptApprovalRow; de
}
function StatusBadge({ status }: { status: string }) {
const labels: Record<string, string> = { pending: "Pending approval", allowed: "Allowed", denied: "Denied", timeout: "Timed out" };
const labels: Record<string, string> = {
pending: t("Pending approval"),
allowed: t("Allowed"),
denied: t("Denied"),
timeout: t("Timed out"),
};
let variant: "default" | "destructive" | "secondary" | "outline" = "outline";
if (status === "allowed") variant = "default";
if (status === "denied") variant = "destructive";
@@ -121,7 +127,12 @@ function StatusBadge({ status }: { status: string }) {
return <Badge variant={variant}>{labels[status] ?? status}</Badge>;
}
const decidedByLabels: Record<string, string> = { human: "Human", rule: "Rule", model: "Model", system: "System" };
const decidedByLabels: Record<string, string> = {
human: t("Human"),
rule: t("Rule"),
model: t("Model"),
system: t("System"),
};
// decided_by is shown exactly as stored, so a row always sits under the
// "Decided by" filter option matching its badge. A decided row without an actor
@@ -131,14 +142,14 @@ function DecidedByBadge({ row }: { row: InterceptApprovalRow }) {
if (!row.decided_by) {
return (
<Badge variant="outline" className="text-muted-foreground">
Legacy
{t("Legacy")}
</Badge>
);
}
return <Badge variant="outline">{decidedByLabels[row.decided_by] ?? row.decided_by}</Badge>;
}
const riskLabels: Record<InterceptRisk["level"], string> = { low: "Low", medium: "Medium", high: "High" };
const riskLabels: Record<InterceptRisk["level"], string> = { low: t("Low"), medium: t("Medium"), high: t("High") };
// RiskBadge shows the server's deterministic risk level of a pending request.
function RiskBadge({ risk }: { risk?: InterceptRisk }) {
@@ -147,7 +158,7 @@ function RiskBadge({ risk }: { risk?: InterceptRisk }) {
if (risk.level === "high") variant = "destructive";
if (risk.level === "medium") variant = "secondary";
return (
<Badge variant={variant} title={`Risk score ${risk.score}/100`}>
<Badge variant={variant} title={t("Risk score {score}/100", { score: risk.score })}>
{riskLabels[risk.level] ?? risk.level}
</Badge>
);
@@ -160,14 +171,14 @@ function MatchCell({ row, showReason = true }: { row: InterceptApprovalRow; show
{source(row) === "model" ? (
<Badge variant="outline">
<BotIcon />
Model decision
{t("Model decision")}
</Badge>
) : (
<span className="truncate">{row.rule_name || "Rule not recorded or deleted"}</span>
<span className="truncate">{row.rule_name || t("Rule not recorded or deleted")}</span>
)}
{showReason ? (
<p className="truncate text-muted-foreground text-xs" title={reason}>
{reason || "No reason recorded"}
{reason || t("No reason recorded")}
</p>
) : null}
</div>
@@ -178,9 +189,9 @@ function CodeBlock({ label, text, truncated = false }: { label: string; text: st
async function copy() {
try {
await navigator.clipboard.writeText(text);
toast.success("Copied");
toast.success(t("Copied"));
} catch {
toast.error("Copy failed; select the content manually to copy");
toast.error(t("Copy failed; select the content manually to copy"));
}
}
return (
@@ -188,106 +199,114 @@ function CodeBlock({ label, text, truncated = false }: { label: string; text: st
<div className="flex items-center justify-between gap-2">
<h3 className="font-medium text-muted-foreground text-xs">{label}</h3>
{text ? (
<Button variant="ghost" size="icon-xs" aria-label={`Copy ${label}`} onClick={() => void copy()}>
<Button variant="ghost" size="icon-xs" aria-label={t("Copy {label}", { label })} onClick={() => void copy()}>
<CopyIcon />
</Button>
) : null}
</div>
<pre className="max-h-80 min-w-0 overflow-auto whitespace-pre-wrap break-words rounded-lg bg-muted/60 p-3 font-mono text-xs leading-6 [overflow-wrap:anywhere]">
{text || "Not recorded"}
{text || t("Not recorded")}
</pre>
{truncated ? <p className="text-muted-foreground text-xs">Content truncated; the above is the saved excerpt.</p> : null}
{truncated ? (
<p className="text-muted-foreground text-xs">{t("Content truncated; the above is the saved excerpt.")}</p>
) : null}
</section>
);
}
const contextLabels: Record<string, string> = {
user: "User message",
assistant: "Agent message",
text: "Agent message",
tool_use: "Tool request",
tool_result: "Tool output",
user: t("User message"),
assistant: t("Agent message"),
text: t("Agent message"),
tool_use: t("Tool request"),
tool_result: t("Tool output"),
};
const actionLabels: Record<string, string> = { allow: "Allow", ask: "Escalate to human approval", deny: "Deny" };
const actionLabels: Record<string, string> = { allow: t("Allow"), ask: t("Escalate to human approval"), deny: t("Deny") };
const executionLabels: Record<InterceptAudit["execution_status"], string> = {
not_started: "Not started",
not_executed: "Not executed",
awaiting_result: "Allowed, awaiting execution result",
succeeded: "Execution succeeded",
failed: "Execution failed",
unknown: "Execution result unknown",
not_started: t("Not started"),
not_executed: t("Not executed"),
awaiting_result: t("Allowed, awaiting execution result"),
succeeded: t("Execution succeeded"),
failed: t("Execution failed"),
unknown: t("Execution result unknown"),
};
function ModelReviewContext({ input }: { input: InterceptReviewInput }) {
return (
<section className="flex min-w-0 flex-col gap-4" aria-label="Model review context">
<section className="flex min-w-0 flex-col gap-4" aria-label={t("Model review context")}>
<div className="flex flex-col gap-2">
<h3 className="font-medium text-sm">Model review context</h3>
<h3 className="font-medium text-sm">{t("Model review context")}</h3>
<p className="text-muted-foreground text-xs">
Below is the snapshot of the input actually sent to the review model for this decision. The background only helps it understand the current action; the verdict follows the review policy.
{input.version < 4 ? "This record used the legacy input format; the content actually sent at the time is preserved." : null}
{t("Below is the snapshot of the input actually sent to the review model for this decision. The background only helps it understand the current action; the verdict follows the review policy.")}
{input.version < 4
? ` ${t("This record used the legacy input format; the content actually sent at the time is preserved.")}`
: null}
</p>
</div>
<CodeBlock
label="Call under review"
label={t("Call under review")}
text={JSON.stringify({ tool_name: input.tool_name, arguments: input.arguments }, null, 2)}
/>
{input.version >= 2 ? (
input.background ? (
<div className="flex min-w-0 flex-col gap-2">
<CodeBlock
label={input.background.source === "user_message" ? "Background · user message" : "Background · Worker intent summary (legacy)"}
label={
input.background.source === "user_message"
? t("Background · user message")
: t("Background · Worker intent summary (legacy)")
}
text={input.background.text}
truncated={input.background.truncated}
/>
<p className="text-muted-foreground text-xs">
{input.background.source === "user_message"
? "Taken from the current user message."
: "This is the legacy Worker intent summary that used to be sent; the new Worker review no longer sends it."}
? t("Taken from the current user message.")
: t("This is the legacy Worker intent summary that used to be sent; the new Worker review no longer sends it.")}
</p>
</div>
) : (
<p className="text-muted-foreground text-xs">No background message was attached to this review.</p>
<p className="text-muted-foreground text-xs">{t("No background message was attached to this review.")}</p>
)
) : (
<>
{input.turn_input ? (
<CodeBlock label="Current turn input (legacy)" text={input.turn_input} truncated={input.background_truncated} />
<CodeBlock label={t("Current turn input (legacy)")} text={input.turn_input} truncated={input.background_truncated} />
) : null}
{input.task ? (
<>
<CodeBlock label="Task description (legacy)" text={input.task.description} truncated={input.task.truncated} />
<CodeBlock label="Task goals (legacy)" text={input.task.goal} truncated={input.task.truncated} />
<CodeBlock label="Task operation constraints (legacy)" text={JSON.stringify(input.task.constraints, null, 2)} />
<CodeBlock label={t("Task description (legacy)")} text={input.task.description} truncated={input.task.truncated} />
<CodeBlock label={t("Task goals (legacy)")} text={input.task.goal} truncated={input.task.truncated} />
<CodeBlock label={t("Task operation constraints (legacy)")} text={JSON.stringify(input.task.constraints, null, 2)} />
</>
) : null}
{input.worker_intent ? (
<CodeBlock label="Worker intent (legacy)" text={input.worker_intent} truncated={input.background_truncated} />
<CodeBlock label={t("Worker intent (legacy)")} text={input.worker_intent} truncated={input.background_truncated} />
) : null}
</>
)}
{input.working_directory ? <CodeBlock label="Working directory" text={input.working_directory} /> : null}
{input.working_directory ? <CodeBlock label={t("Working directory")} text={input.working_directory} /> : null}
{input.version >= 3 ? (
<p className="text-muted-foreground text-xs">No past calls or execution results were sent for this review.</p>
<p className="text-muted-foreground text-xs">{t("No past calls or execution results were sent for this review.")}</p>
) : (
<div className="flex min-w-0 flex-col gap-3">
<h4 className="font-medium text-muted-foreground text-xs">Past calls provided to the model at the time (legacy)</h4>
<h4 className="font-medium text-muted-foreground text-xs">{t("Past calls provided to the model at the time (legacy)")}</h4>
{input.history?.length ? (
input.history.map((entry) => (
<div key={entry.tool_use_id} className="flex min-w-0 flex-col gap-2 rounded-lg border p-3">
<p className="break-words font-medium text-xs">
{entry.tool} · {entry.status === "succeeded" ? "Succeeded" : "Failed (may have partial side effects)"}
{entry.tool} · {entry.status === "succeeded" ? t("Succeeded") : t("Failed (may have partial side effects)")}
</p>
<CodeBlock label="Past call arguments" text={entry.arguments_preview} truncated={entry.truncated} />
<CodeBlock label="Past execution result" text={entry.result} truncated={entry.truncated} />
<CodeBlock label={t("Past call arguments")} text={entry.arguments_preview} truncated={entry.truncated} />
<CodeBlock label={t("Past execution result")} text={entry.result} truncated={entry.truncated} />
</div>
))
) : (
<p className="text-muted-foreground text-xs">No paired past tool executions were provided.</p>
<p className="text-muted-foreground text-xs">{t("No paired past tool executions were provided.")}</p>
)}
{input.history_truncated ? (
<p className="text-muted-foreground text-xs">History is a limited window; some content is truncated.</p>
<p className="text-muted-foreground text-xs">{t("History is a limited window; some content is truncated.")}</p>
) : null}
</div>
)}
@@ -296,11 +315,11 @@ function ModelReviewContext({ input }: { input: InterceptReviewInput }) {
<CollapsibleTrigger asChild>
<Button variant="outline" size="sm" className="self-start">
<ChevronDownIcon data-icon="inline-start" />
View full model review input JSON
{t("View full model review input JSON")}
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="pt-3">
<CodeBlock label="Model review input" text={JSON.stringify(input, null, 2)} />
<CodeBlock label={t("Model review input")} text={JSON.stringify(input, null, 2)} />
</CollapsibleContent>
</Collapsible>
</section>
@@ -315,11 +334,11 @@ function DecisionActions({ row, busy, decide }: { row: InterceptApprovalRow; bus
<div className="flex flex-wrap gap-2">
<Button size="sm" disabled={busy} onClick={() => void decide(row.id, "allowed")}>
<CheckIcon data-icon="inline-start" />
Allow
{t("Allow")}
</Button>
<Button size="sm" variant="destructive" disabled={busy} onClick={() => void decide(row.id, "denied")}>
<XIcon data-icon="inline-start" />
Deny
{t("Deny")}
</Button>
</div>
);
@@ -335,8 +354,8 @@ function AlwaysAllowAction({ id, prefix }: { id: number; prefix?: string }) {
const res = await api.interceptAlwaysAllow(id);
toast.success(
res.created
? "Rule created, the request is still pending approval"
: "Rule already exists, the request is still pending approval",
? t("Rule created, the request is still pending approval")
: t("Rule already exists, the request is still pending approval"),
);
} catch (e) {
toast.error((e as Error).message);
@@ -347,11 +366,10 @@ function AlwaysAllowAction({ id, prefix }: { id: number; prefix?: string }) {
return (
<div className="flex flex-col gap-1">
<Button size="sm" variant="outline" className="self-start" disabled={busy} onClick={() => void create()}>
{prefix ? `Toujours autoriser "${prefix} *"` : "Toujours autoriser"}
{prefix ? t('Always allow "{prefix} *"', { prefix }) : t("Always allow")}
</Button>
<p className="text-muted-foreground text-xs">
The prefix does not constrain flags, and it does not cover what the program does next (git hooks, npm
scripts, docker images).
{t("The prefix does not constrain flags, and it does not cover what the program does next (git hooks, npm scripts, docker images).")}
</p>
</div>
);
@@ -393,7 +411,7 @@ export function ApprovalDetail({
if (next.status === "pending" || next.audit?.execution_status === "awaiting_result")
timer = setTimeout(() => void load(), 5000);
} catch (e) {
if (!cancelled) setError((e as Error).message || "Failed to load details");
if (!cancelled) setError((e as Error).message || t("Failed to load details"));
}
}
void load();
@@ -406,19 +424,19 @@ export function ApprovalDetail({
// Row updates are authoritative until the lazy detail has caught up.
const current = detail?.status === row.status ? detail : row;
const audit = detail?.audit;
let execution = audit ? executionLabels[audit.execution_status] : "Not recorded";
if (row.status === "pending") execution = "Not started";
if (audit && audit.correlation !== "exact" && audit.effective_action === "allow") execution = "No linked execution result";
let execution = audit ? executionLabels[audit.execution_status] : t("Not recorded");
if (row.status === "pending") execution = t("Not started");
if (audit && audit.correlation !== "exact" && audit.effective_action === "allow") execution = t("No linked execution result");
const command = typeof row.tool_input?.command === "string" ? row.tool_input.command : undefined;
let initialLabel = source(row) === "model" ? "Model initial decision" : "Rule initial decision";
if (audit?.model_fallback) initialLabel = "Model error fallback";
let initialLabel = source(row) === "model" ? t("Model initial decision") : t("Rule initial decision");
if (audit?.model_fallback) initialLabel = t("Model error fallback");
return (
<div className="flex min-w-0 flex-col gap-4 p-3 sm:p-5">
<div className="grid min-w-0 gap-5 rounded-xl border bg-muted/20 p-4 lg:grid-cols-2">
<div className="flex min-w-0 flex-col gap-3">
<CodeBlock
label={`${current.agent_name || current.conv_agent_key || "Agent"} · tool request`}
label={t("{agent} · tool request", { agent: current.agent_name || current.conv_agent_key || t("Agent") })}
text={JSON.stringify(row.tool_input ?? {}, null, 2)}
/>
{command ? (
@@ -426,47 +444,49 @@ export function ApprovalDetail({
<CollapsibleTrigger asChild>
<Button variant="ghost" size="sm">
<ChevronDownIcon data-icon="inline-start" />
View command content
{t("View command content")}
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="pt-2">
<CodeBlock label="Command content" text={command} />
<CodeBlock label={t("Command content")} text={command} />
</CollapsibleContent>
</Collapsible>
) : null}
<p className="text-muted-foreground text-xs">
Execution result: <span className="text-foreground">{detail ? execution : "Loading…"}</span>
{t("Execution result:")} <span className="text-foreground">{detail ? execution : t("Loading…")}</span>
</p>
</div>
<div className="flex min-w-0 flex-col gap-4 lg:border-l lg:pl-5">
<h3 className="font-medium text-muted-foreground text-xs">
{current.status === "pending" ? "Review status" : "Approval decision"}
{current.status === "pending" ? t("Review status") : t("Approval decision")}
</h3>
<div className="flex flex-wrap items-center gap-2">
<StatusBadge status={current.status} />
<MatchCell row={current} showReason={false} />
</div>
<p className="whitespace-pre-wrap break-words text-sm leading-7 [overflow-wrap:anywhere]">
{current.reason?.replace(/^\[model\]\s*/, "") || "No approval reason recorded"}
{current.reason?.replace(/^\[model\]\s*/, "") || t("No approval reason recorded")}
</p>
{audit?.decision_reason ? <p className="text-sm">{audit.decision_reason}</p> : null}
{audit?.effective_action ? <p className="text-sm">Final action: {actionLabels[audit.effective_action]}</p> : null}
{audit?.effective_action ? (
<p className="text-sm">{t("Final action: {action}", { action: actionLabels[audit.effective_action] })}</p>
) : null}
<dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-2 text-xs">
<dt className="text-muted-foreground">Source</dt>
<dt className="text-muted-foreground">{t("Source")}</dt>
<dd className="break-words">
<ApprovalOrigin row={current} detail />
</dd>
<dt className="text-muted-foreground">Requested at</dt>
<dt className="text-muted-foreground">{t("Requested at")}</dt>
<dd>{fmtTime(row.created_at)}</dd>
<dt className="text-muted-foreground">Decided at</dt>
<dt className="text-muted-foreground">{t("Decided at")}</dt>
<dd>{fmtTime(current.decided_at)}</dd>
<dt className="text-muted-foreground">Decided by</dt>
<dt className="text-muted-foreground">{t("Decided by")}</dt>
<dd>
<DecidedByBadge row={current} />
</dd>
{row.risk ? (
<>
<dt className="text-muted-foreground">Risk</dt>
<dt className="text-muted-foreground">{t("Risk")}</dt>
<dd className="flex flex-col gap-1">
<span className="flex items-center gap-2">
<RiskBadge risk={row.risk} />
@@ -484,13 +504,13 @@ export function ApprovalDetail({
) : null}
{audit?.rule_name ? (
<>
<dt className="text-muted-foreground">Rule snapshot</dt>
<dt className="text-muted-foreground">{t("Rule snapshot")}</dt>
<dd>{audit.rule_name}</dd>
</>
) : null}
{audit?.profile_id ? (
<>
<dt className="text-muted-foreground">Approval model profile</dt>
<dt className="text-muted-foreground">{t("Approval model profile")}</dt>
<dd>#{audit.profile_id}</dd>
</>
) : null}
@@ -505,9 +525,9 @@ export function ApprovalDetail({
<Alert variant="destructive">
<AlertDescription>
<div className="flex flex-wrap items-center gap-2">
<span>Failed to load details: {error}</span>
<span>{t("Failed to load details: {error}", { error })}</span>
<Button variant="outline" size="sm" onClick={() => setRetry((v) => v + 1)}>
Retry
{t("Retry")}
</Button>
</div>
</AlertDescription>
@@ -516,7 +536,9 @@ export function ApprovalDetail({
{!detail && !error ? <Skeleton className="h-8 w-60" /> : null}
{detail && !audit ? (
<Alert>
<AlertDescription>This record has no saved approval detail snapshot, so the context, model initial decision, and execution output at the time cannot be restored.</AlertDescription>
<AlertDescription>
{t("This record has no saved approval detail snapshot, so the context, model initial decision, and execution output at the time cannot be restored.")}
</AlertDescription>
</Alert>
) : null}
{audit ? (
@@ -524,7 +546,7 @@ export function ApprovalDetail({
<CollapsibleTrigger asChild>
<Button variant="ghost" size="sm">
<ChevronDownIcon data-icon="inline-start" className={cn(more && "rotate-180")} />
{more ? "Collapse context" : "View context and execution result"}
{more ? t("Collapse context") : t("View context and execution result")}
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="pt-4">
@@ -535,8 +557,8 @@ export function ApprovalDetail({
<Alert>
<AlertDescription>
{audit.model_input_digest
? "This legacy record saved only the review input fingerprint, not the input itself, so the context sent to the model at the time cannot be restored. This does not mean the review had no context; newly produced model decisions keep an input snapshot."
: "This record has no saved model review input; it may have been decided directly by a rule, failed before the model call, or come from an old version."}
? t("This legacy record saved only the review input fingerprint, not the input itself, so the context sent to the model at the time cannot be restored. This does not mean the review had no context; newly produced model decisions keep an input snapshot.")
: t("This record has no saved model review input; it may have been decided directly by a rule, failed before the model call, or come from an old version.")}
</AlertDescription>
</Alert>
)}
@@ -546,38 +568,42 @@ export function ApprovalDetail({
<Button variant="ghost" size="sm">
<ChevronDownIcon data-icon="inline-start" />
{audit.model_input && audit.model_input.version >= 3
? "View conversation audit excerpt (not sent to model)"
: "View conversation audit excerpt"}
? t("View conversation audit excerpt (not sent to model)")
: t("View conversation audit excerpt")}
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="pt-3">
<div className="flex min-w-0 flex-col gap-3">
{audit.user_message ? (
<CodeBlock
label="Conversation current-turn input (audit excerpt)"
label={t("Conversation current-turn input (audit excerpt)")}
text={audit.user_message}
truncated={audit.user_truncated}
/>
) : null}
<section className="flex min-w-0 flex-col gap-3">
<h3 className="font-medium text-muted-foreground text-xs">Visible conversation context</h3>
<h3 className="font-medium text-muted-foreground text-xs">{t("Visible conversation context")}</h3>
<p className="text-muted-foreground text-xs">
Conversation record excerpt saved at {fmtTime(audit.captured_at)}. What the model actually used follows "Model review input".
{t('Conversation record excerpt saved at {time}. What the model actually used follows "Model review input".', {
time: fmtTime(audit.captured_at),
})}
</p>
{audit.context_truncated ? (
<p className="text-muted-foreground text-xs">Only the most recent context is saved; some content is truncated.</p>
<p className="text-muted-foreground text-xs">
{t("Only the most recent context is saved; some content is truncated.")}
</p>
) : null}
{audit.context?.length ? (
audit.context.map((entry, index) => (
<CodeBlock
key={`${entry.kind}-${entry.tool_use_id || index}`}
label={`${contextLabels[entry.kind] ?? entry.kind}${entry.tool ? ` · ${entry.tool}` : ""}${entry.is_error ? " · error" : ""}`}
label={`${contextLabels[entry.kind] ?? entry.kind}${entry.tool ? ` · ${entry.tool}` : ""}${entry.is_error ? ` · ${t("error")}` : ""}`}
text={entry.text}
truncated={entry.truncated}
/>
))
) : (
<p className="text-muted-foreground text-sm">No linkable context recorded</p>
<p className="text-muted-foreground text-sm">{t("No linkable context recorded")}</p>
)}
</section>
</div>
@@ -590,30 +616,37 @@ export function ApprovalDetail({
/>
{audit.judge_answers?.length ? (
<CodeBlock
label="Judge answers"
label={t("Judge answers")}
text={audit.judge_answers.map((a) => `${a.id}: ${a.answer}${a.evidence ? ` - ${a.evidence}` : ""}`).join("\n")}
/>
) : null}
<CodeBlock
label="Execution output"
text={audit.output ?? (audit.execution_status === "not_executed" ? "Tool not executed." : "No execution output yet")}
label={t("Execution output")}
text={
audit.output ??
(audit.execution_status === "not_executed" ? t("Tool not executed.") : t("No execution output yet"))
}
truncated={audit.output_truncated}
/>
{audit.correlation !== "exact" ? (
<Alert>
<AlertDescription>
{audit.correlation === "ambiguous"
? "Concurrent calls with identical arguments exist, so the tool call cannot be uniquely linked; this record does not show a guessed execution result."
: "No uniquely linkable tool call ID recorded."}
? t("Concurrent calls with identical arguments exist, so the tool call cannot be uniquely linked; this record does not show a guessed execution result.")
: t("No uniquely linkable tool call ID recorded.")}
</AlertDescription>
</Alert>
) : null}
<dl className="grid gap-2 text-muted-foreground text-xs [overflow-wrap:anywhere]">
<div>Tool call ID: {audit.tool_use_id || "Not recorded"}</div>
<div>Arguments digest SHA-256: {audit.input_digest}</div>
<div>Review config fingerprint SHA-256: {audit.config_digest || "Not recorded"}</div>
{audit.model_input_digest ? <div>Model review input SHA-256: {audit.model_input_digest}</div> : null}
{audit.execution_ended_at ? <div>Result recorded at: {fmtTime(audit.execution_ended_at)}</div> : null}
<div>{t("Tool call ID: {value}", { value: audit.tool_use_id || t("Not recorded") })}</div>
<div>{t("Arguments digest SHA-256: {value}", { value: audit.input_digest })}</div>
<div>{t("Review config fingerprint SHA-256: {value}", { value: audit.config_digest || t("Not recorded") })}</div>
{audit.model_input_digest ? (
<div>{t("Model review input SHA-256: {value}", { value: audit.model_input_digest })}</div>
) : null}
{audit.execution_ended_at ? (
<div>{t("Result recorded at: {time}", { time: fmtTime(audit.execution_ended_at) })}</div>
) : null}
</dl>
</div>
</CollapsibleContent>
@@ -683,7 +716,7 @@ function ApprovalTable({
{selection ? (
<TableHead className="w-10">
<Checkbox
aria-label="Select all pending approvals on this page"
aria-label={t("Select all pending approvals on this page")}
checked={allChecked}
disabled={busy || !rows.length}
onCheckedChange={() => selection.toggleAll()}
@@ -691,17 +724,17 @@ function ApprovalTable({
</TableHead>
) : null}
<TableHead className="w-10">
<span className="sr-only">Expand details</span>
<span className="sr-only">{t("Expand details")}</span>
</TableHead>
<TableHead className="hidden w-14 sm:table-cell">#</TableHead>
<TableHead className="w-28">Tool</TableHead>
<TableHead className="hidden md:table-cell">Source</TableHead>
<TableHead className="hidden lg:table-cell">Matched rule</TableHead>
<TableHead className="hidden xl:table-cell">Arguments</TableHead>
<TableHead className="w-24">Status</TableHead>
<TableHead className="hidden w-24 lg:table-cell">Decided by</TableHead>
<TableHead className="hidden w-36 lg:table-cell">Requested at</TableHead>
<TableHead className="hidden w-36 xl:table-cell">Decided at</TableHead>
<TableHead className="w-28">{t("Tool")}</TableHead>
<TableHead className="hidden md:table-cell">{t("Source")}</TableHead>
<TableHead className="hidden lg:table-cell">{t("Matched rule")}</TableHead>
<TableHead className="hidden xl:table-cell">{t("Arguments")}</TableHead>
<TableHead className="w-24">{t("Status")}</TableHead>
<TableHead className="hidden w-24 lg:table-cell">{t("Decided by")}</TableHead>
<TableHead className="hidden w-36 lg:table-cell">{t("Requested at")}</TableHead>
<TableHead className="hidden w-36 xl:table-cell">{t("Decided at")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -718,7 +751,7 @@ function ApprovalTable({
{selection ? (
<TableCell onClick={(e) => e.stopPropagation()}>
<Checkbox
aria-label={`Select approval #${row.id}`}
aria-label={t("Select approval #{id}", { id: row.id })}
checked={selection.selected.has(row.id)}
disabled={busy || row.status !== "pending"}
onCheckedChange={() => selection.toggle(row.id)}
@@ -729,7 +762,9 @@ function ApprovalTable({
<Button
variant="ghost"
size="icon-sm"
aria-label={`${open ? "Collapse" : "Expand"} approval #${row.id}`}
aria-label={
open ? t("Collapse approval #{id}", { id: row.id }) : t("Expand approval #{id}", { id: row.id })
}
aria-expanded={open}
aria-controls={open ? panelID : undefined}
onClick={(e) => {
@@ -779,7 +814,7 @@ function ApprovalTable({
{open ? (
<TableRow className="hover:bg-transparent has-aria-expanded:bg-transparent">
<TableCell colSpan={columns} className="whitespace-normal p-0">
<section id={panelID} aria-label={`Approval details #${row.id}`}>
<section id={panelID} aria-label={t("Approval details #{id}", { id: row.id })}>
<ApprovalDetail row={row} busy={busy} decide={decide} revision={revision} />
</section>
</TableCell>
@@ -839,17 +874,17 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
setTotal(history.value.total);
setError("");
} else {
setError((history.reason as Error).message || "Failed to load");
setError((history.reason as Error).message || t("Failed to load"));
}
if (pending.status === "fulfilled") {
setPendingRows(pending.value);
setPendingError("");
} else {
setPendingError((pending.reason as Error).message || "Failed to load");
setPendingError((pending.reason as Error).message || t("Failed to load"));
}
if (manual) setRevision((v) => v + 1);
} catch (e) {
if (id === request.current) setError((e as Error).message || "Failed to load");
if (id === request.current) setError((e as Error).message || t("Failed to load"));
} finally {
if (id === request.current) {
setLoading(false);
@@ -904,7 +939,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
);
setPendingRows((prev) => prev.filter((row) => row.id !== id));
setRevision((v) => v + 1);
toast.success(decision === "allowed" ? "Execution allowed" : "Execution denied");
toast.success(decision === "allowed" ? t("Execution allowed") : t("Execution denied"));
// Re-fetch counts and rows: a decided item may no longer match the filter.
await latestLoad.current(true);
} catch (e) {
@@ -922,7 +957,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
.map((row) => ({
conv_title: "",
conv_agent_key: "",
rule_name: row.rule_id ? `Rule #${row.rule_id}` : "",
rule_name: row.rule_id ? t("Rule #{id}", { id: row.rule_id }) : "",
...historyById.get(row.id),
...row,
}));
@@ -961,9 +996,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
try {
const res = await api.interceptBatchDecide(ids.slice(start, start + batchDecideMax), decision);
decided += res.decided;
for (const r of res.results) if (!r.ok) failed.push({ id: r.id, error: r.error || "Not decided" });
for (const r of res.results) if (!r.ok) failed.push({ id: r.id, error: r.error || t("Not decided") });
} catch (e) {
const error = `Not sent: ${(e as Error).message || "request failed"}`;
const error = t("Not sent: {error}", { error: (e as Error).message || t("request failed") });
for (const id of ids.slice(start)) failed.push({ id, error });
break;
}
@@ -972,9 +1007,13 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
setBatchErrors(failed);
setSelected(new Set(failed.map((f) => f.id)));
setRevision((v) => v + 1);
const verb = decision === "allowed" ? "allowed" : "denied";
if (failed.length) toast.error(`${decided} ${verb}, ${failed.length} not decided (see the errors listed above)`);
else toast.success(`${decided} ${verb}`);
if (failed.length)
toast.error(
decision === "allowed"
? t("{decided} allowed, {failed} not decided (see the errors listed above)", { decided, failed: failed.length })
: t("{decided} denied, {failed} not decided (see the errors listed above)", { decided, failed: failed.length }),
);
else toast.success(decision === "allowed" ? t("{count} allowed", { count: decided }) : t("{count} denied", { count: decided }));
} finally {
decisionLock.current = false;
setDeciding(false);
@@ -982,24 +1021,28 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
await latestLoad.current(true);
}
};
const title = taskId ? "Interception approval" : "Approval records";
const title = taskId ? t("Interception approval") : t("Approval records");
return (
<div className="flex min-w-0 flex-col gap-5">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2">
<ClipboardListIcon className="size-5 text-muted-foreground" />
<h1 className="font-semibold text-xl">{title}</h1>
{pending.length ? <Badge variant="secondary">{pending.length} pending</Badge> : null}
{pending.length ? (
<Badge variant="secondary">{t("{count} pending", { count: pending.length })}</Badge>
) : null}
</div>
<Button variant="outline" size="sm" onClick={() => void load(true)} disabled={loading || refreshing}>
<RefreshCwIcon data-icon="inline-start" className={cn(refreshing && "animate-spin")} />
Refresh
{t("Refresh")}
</Button>
</div>
<p className="text-muted-foreground text-sm">Expand a record to view the tool request and approval decision, along with the context and execution result at the time.</p>
<FieldGroup className="flex-row flex-wrap items-end gap-3" aria-label="Approval record filters">
<p className="text-muted-foreground text-sm">
{t("Expand a record to view the tool request and approval decision, along with the context and execution result at the time.")}
</p>
<FieldGroup className="flex-row flex-wrap items-end gap-3" aria-label={t("Approval record filters")}>
<Field className="w-full sm:w-40">
<FieldLabel htmlFor={`${filterID}-status`}>Approval status</FieldLabel>
<FieldLabel htmlFor={`${filterID}-status`}>{t("Approval status")}</FieldLabel>
<Select
value={filter.status ?? "all"}
onValueChange={(value) =>
@@ -1014,17 +1057,17 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="all">All statuses</SelectItem>
<SelectItem value="denied">Denied</SelectItem>
<SelectItem value="pending">Pending approval</SelectItem>
<SelectItem value="allowed">Allowed</SelectItem>
<SelectItem value="timeout">Timed out</SelectItem>
<SelectItem value="all">{t("All statuses")}</SelectItem>
<SelectItem value="denied">{t("Denied")}</SelectItem>
<SelectItem value="pending">{t("Pending approval")}</SelectItem>
<SelectItem value="allowed">{t("Allowed")}</SelectItem>
<SelectItem value="timeout">{t("Timed out")}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
<Field className="w-full sm:w-40">
<FieldLabel htmlFor={`${filterID}-source`}>Decision source</FieldLabel>
<FieldLabel htmlFor={`${filterID}-source`}>{t("Decision source")}</FieldLabel>
<Select
value={filter.decision_source ?? "all"}
onValueChange={(value) =>
@@ -1039,16 +1082,16 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="all">All sources</SelectItem>
<SelectItem value="model">Model decision</SelectItem>
<SelectItem value="rule">Rule decision</SelectItem>
<SelectItem value="unknown">Unknown source</SelectItem>
<SelectItem value="all">{t("All sources")}</SelectItem>
<SelectItem value="model">{t("Model decision")}</SelectItem>
<SelectItem value="rule">{t("Rule decision")}</SelectItem>
<SelectItem value="unknown">{t("Unknown source")}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
<Field className="w-full sm:w-40">
<FieldLabel htmlFor={`${filterID}-decided-by`}>Decided by</FieldLabel>
<FieldLabel htmlFor={`${filterID}-decided-by`}>{t("Decided by")}</FieldLabel>
<Select
value={filter.decided_by ?? "all"}
onValueChange={(value) =>
@@ -1063,35 +1106,39 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="all">All actors</SelectItem>
<SelectItem value="model">AI-decided</SelectItem>
<SelectItem value="human">Human</SelectItem>
<SelectItem value="rule">Rule</SelectItem>
<SelectItem value="system">System</SelectItem>
<SelectItem value="all">{t("All actors")}</SelectItem>
<SelectItem value="model">{t("AI-decided")}</SelectItem>
<SelectItem value="human">{t("Human")}</SelectItem>
<SelectItem value="rule">{t("Rule")}</SelectItem>
<SelectItem value="system">{t("System")}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
{filtered ? (
<Button variant="ghost" size="sm" onClick={() => changeFilter({})}>
Clear filters
{t("Clear filters")}
</Button>
) : null}
</FieldGroup>
{error ? (
<Alert variant="destructive">
<AlertDescription>Failed to load records: {error}. Click Refresh to retry.</AlertDescription>
<AlertDescription>{t("Failed to load records: {error}. Click Refresh to retry.", { error })}</AlertDescription>
</Alert>
) : null}
{pendingError ? (
<Alert variant="destructive">
<AlertDescription>Failed to load pending approvals: {pendingError}. Click Refresh to retry.</AlertDescription>
<AlertDescription>
{t("Failed to load pending approvals: {error}. Click Refresh to retry.", { error: pendingError })}
</AlertDescription>
</Alert>
) : null}
{batchErrors.length ? (
<Alert variant="destructive">
<AlertDescription>
<p>{batchErrors.length} selected request(s) were not decided and stay pending:</p>
<p>
{t("{count} selected request(s) were not decided and stay pending:", { count: batchErrors.length })}
</p>
<ul className="list-disc pl-4">
{batchErrors.map((f) => (
<li key={f.id}>
@@ -1106,22 +1153,23 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
<section className="overflow-hidden rounded-xl border">
<div className="flex items-center gap-2 border-b bg-muted/40 px-4 py-3 font-medium text-sm">
<ShieldAlertIcon className="size-4" />
Pending ({pending.length})<span className="text-muted-foreground text-xs">expand to allow or deny</span>
{t("Pending ({count})", { count: pending.length })}
<span className="text-muted-foreground text-xs">{t("expand to allow or deny")}</span>
</div>
<ApprovalTable
rows={pending}
busy={deciding}
decide={decide}
revision={revision}
label="Pending approvals"
label={t("Pending approvals")}
selection={selection}
/>
<div className="flex flex-wrap items-center justify-between gap-2 border-t px-4 py-3 text-sm">
<span className="text-muted-foreground">{selectedRows.length} selected</span>
<span className="text-muted-foreground">{t("{count} selected", { count: selectedRows.length })}</span>
<div className="flex flex-wrap gap-2">
<Button size="sm" disabled={deciding || !selectedRows.length} onClick={() => setBatchDecision("allowed")}>
<CheckIcon data-icon="inline-start" />
Approve selected
{t("Approve selected")}
</Button>
<Button
size="sm"
@@ -1130,7 +1178,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
onClick={() => setBatchDecision("denied")}
>
<XIcon data-icon="inline-start" />
Deny selected
{t("Deny selected")}
</Button>
</div>
</div>
@@ -1145,15 +1193,19 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{batchDecision === "denied" ? "Deny" : "Approve"} {selectedRows.length} request(s)?
{batchDecision === "denied"
? t("Deny {count} request(s)?", { count: selectedRows.length })
: t("Approve {count} request(s)?", { count: selectedRows.length })}
</AlertDialogTitle>
<AlertDialogDescription>
{selectedHigh ? `${selectedHigh} of them are high risk.` : "None of them is high risk."} Each request is
decided on its own; one that cannot be decided stays pending and is listed.
{selectedHigh
? t("{count} of them are high risk.", { count: selectedHigh })
: t("None of them is high risk.")}{" "}
{t("Each request is decided on its own; one that cannot be decided stays pending and is listed.")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deciding}>Cancel</AlertDialogCancel>
<AlertDialogCancel disabled={deciding}>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction
variant={batchDecision === "denied" ? "destructive" : "default"}
disabled={deciding || !selectedRows.length}
@@ -1162,14 +1214,14 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
if (batchDecision) void batchDecide(batchDecision);
}}
>
{batchDecision === "denied" ? "Deny selected" : "Approve selected"}
{batchDecision === "denied" ? t("Deny selected") : t("Approve selected")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<section className="overflow-hidden rounded-xl border">
<div className="border-b px-4 py-3 font-medium text-sm">
{filtered ? "Filtered results" : "All records"} ({total})
{filtered ? t("Filtered results ({total})", { total }) : t("All records ({total})", { total })}
</div>
{loading ? (
<div className="flex flex-col gap-3 p-4">
@@ -1184,17 +1236,17 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
<EmptyMedia variant="icon">
<ClipboardListIcon />
</EmptyMedia>
<EmptyTitle>{filtered ? "No approval records match the filters" : "No approval records"}</EmptyTitle>
<EmptyTitle>{filtered ? t("No approval records match the filters") : t("No approval records")}</EmptyTitle>
<EmptyDescription>
{filtered
? "Adjust the approval status, decision source or deciding actor, or clear the filters to see all records."
: "Records will appear here once a rule or model makes an approval decision."}
? t("Adjust the approval status, decision source or deciding actor, or clear the filters to see all records.")
: t("Records will appear here once a rule or model makes an approval decision.")}
</EmptyDescription>
</EmptyHeader>
</Empty>
) : null}
{rows.length ? (
<ApprovalTable rows={rows} busy={deciding} decide={decide} revision={revision} label="Approval record list" />
<ApprovalTable rows={rows} busy={deciding} decide={decide} revision={revision} label={t("Approval record list")} />
) : null}
{!loading && !error ? (
<TablePagination
+84 -77
View File
@@ -5,6 +5,7 @@ import * as React from "react";
import { SearchIcon } from "lucide-react";
import { Input } from "@/components/ui/input";
import { t } from "@/i18n";
import { cn } from "@/lib/utils";
// ── DSL autocomplete ──────────────────────────────────────────────────────────
@@ -14,167 +15,167 @@ import { cn } from "@/lib/utils";
const DSL_FIELDS: { name: string; desc: string; ops: { op: string; desc: string }[] }[] = [
{
name: "domain",
desc: "Domain (root domain/subdomain/service domain)",
desc: t("Domain (root domain/subdomain/service domain)"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "ip",
desc: "IPv4/IPv6 address",
desc: t("IPv4/IPv6 address"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "url",
desc: "Full URL (service/endpoint)",
desc: t("Full URL (service/endpoint)"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "root_domain",
desc: "Root domain",
desc: t("Root domain"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "page_title",
desc: "Page title (HTTP service)",
desc: t("Page title (HTTP service)"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "icp",
desc: "ICP filing number",
desc: t("ICP filing number"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "service_name",
desc: "Service name (non-HTTP service)",
desc: t("Service name (non-HTTP service)"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "app_name",
desc: "App name",
desc: t("App name"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "bundle_id",
desc: "App Bundle ID",
desc: t("App Bundle ID"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "category",
desc: "App category",
desc: t("App category"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "app_icp",
desc: "App ICP filing",
desc: t("App ICP filing"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "method",
desc: "HTTP method GET/POST/PUT/…",
desc: t("HTTP method GET/POST/PUT/…"),
ops: [
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "service_type",
desc: "Service type: http | other",
desc: t("Service type: http | other"),
ops: [
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "record_type",
desc: "DNS record type A/CNAME/MX/…",
desc: t("DNS record type A/CNAME/MX/…"),
ops: [
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "technology",
desc: "Technology fingerprint (array field)",
desc: t("Technology fingerprint (array field)"),
ops: [
{ op: "=", desc: "fuzzy match" },
{ op: "==", desc: "exact match" },
{ op: "!=", desc: "exclude" },
{ op: "=", desc: t("fuzzy match") },
{ op: "==", desc: t("exact match") },
{ op: "!=", desc: t("exclude") },
],
},
{
name: "port",
desc: "Port number (integer)",
desc: t("Port number (integer)"),
ops: [
{ op: "==", desc: "equals" },
{ op: "!=", desc: "not equals" },
{ op: ">", desc: "greater than" },
{ op: ">=", desc: "greater than or equal" },
{ op: "<", desc: "less than" },
{ op: "<=", desc: "less than or equal" },
{ op: "==", desc: t("equals") },
{ op: "!=", desc: t("not equals") },
{ op: ">", desc: t("greater than") },
{ op: ">=", desc: t("greater than or equal") },
{ op: "<", desc: t("less than") },
{ op: "<=", desc: t("less than or equal") },
],
},
{
name: "status_code",
desc: "HTTP status code (integer)",
desc: t("HTTP status code (integer)"),
ops: [
{ op: "==", desc: "equals" },
{ op: "!=", desc: "not equals" },
{ op: ">", desc: "greater than" },
{ op: ">=", desc: "greater than or equal" },
{ op: "<", desc: "less than" },
{ op: "<=", desc: "less than or equal" },
{ op: "==", desc: t("equals") },
{ op: "!=", desc: t("not equals") },
{ op: ">", desc: t("greater than") },
{ op: ">=", desc: t("greater than or equal") },
{ op: "<", desc: t("less than") },
{ op: "<=", desc: t("less than or equal") },
],
},
{ name: "company_id", desc: "Owning company ID (integer)", ops: [{ op: "==", desc: "equals" }] },
{ name: "task_id", desc: "Source task ID (integer)", ops: [{ op: "==", desc: "equals" }] },
{ name: "company_id", desc: t("Owning company ID (integer)"), ops: [{ op: "==", desc: t("equals") }] },
{ name: "task_id", desc: t("Source task ID (integer)"), ops: [{ op: "==", desc: t("equals") }] },
];
const LOGIC_OPS = [
{ label: "AND", desc: "AND (both conditions must match)" },
{ label: "OR", desc: "OR (either one matches)" },
{ label: "AND", desc: t("AND (both conditions must match)") },
{ label: "OR", desc: t("OR (either one matches)") },
];
interface DslSuggestion {
@@ -341,7 +342,7 @@ export function AssetDslSearch({
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
ref={inputRef}
placeholder="DSL search: domain=example AND status_code>=400"
placeholder={t("DSL search: {example}", { example: "domain=example AND status_code>=400" })}
value={query}
onChange={handleChange}
onKeyDown={handleKeyDown}
@@ -375,7 +376,13 @@ export function AssetDslSearch({
</div>
{query.trim() && !open && (
<p className="pl-1 text-[11px] text-muted-foreground">
{loading ? "Searching…" : error ? <span className="text-destructive">{error}</span> : `Found ${count ?? 0}`}
{loading ? (
t("Searching…")
) : error ? (
<span className="text-destructive">{error}</span>
) : (
t("Found {count}", { count: count ?? 0 })
)}
</p>
)}
</div>
@@ -7,6 +7,7 @@ import { PlusIcon, Trash2Icon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { NativeSelect, NativeSelectOption } from "@/components/ui/native-select";
import { t } from "@/i18n";
import type { AssetInterceptKind, AssetInterceptRuleInput } from "@/lib/types";
// Uses NativeSelect (a native <select>) instead of shadcn Select: this editor is used inside a Sheet drawer,
@@ -16,13 +17,13 @@ export const ASSET_INTERCEPT_KIND_OPTIONS: {
label: string;
placeholder: string;
}[] = [
{ value: "exact_domain", label: "Domain (exact)", placeholder: "example.gov.cn" },
{ value: "exact_ip", label: "IP (exact)", placeholder: "203.0.113.10" },
{ value: "exact_url", label: "URL (exact)", placeholder: "https://example.com/login" },
{ value: "fuzzy_domain", label: "Domain (fuzzy)", placeholder: ".gov.cn" },
{ value: "fuzzy_ip", label: "IP (fuzzy)", placeholder: "203.0.113." },
{ value: "fuzzy_url", label: "URL (fuzzy)", placeholder: "/admin" },
{ value: "cidr", label: "CIDR range", placeholder: "192.168.0.0/16" },
{ value: "exact_domain", label: t("Domain (exact)"), placeholder: "example.gov.cn" },
{ value: "exact_ip", label: t("IP (exact)"), placeholder: "203.0.113.10" },
{ value: "exact_url", label: t("URL (exact)"), placeholder: "https://example.com/login" },
{ value: "fuzzy_domain", label: t("Domain (fuzzy)"), placeholder: ".gov.cn" },
{ value: "fuzzy_ip", label: t("IP (fuzzy)"), placeholder: "203.0.113." },
{ value: "fuzzy_url", label: t("URL (fuzzy)"), placeholder: "/admin" },
{ value: "cidr", label: t("CIDR range"), placeholder: "192.168.0.0/16" },
];
// AssetInterceptRulesEditor is a controlled multi-row editor for block/allow rules (block/allow +
@@ -56,8 +57,8 @@ export function AssetInterceptRulesEditor({
value={r.action}
onChange={(e) => update(i, { action: e.target.value as "block" | "allow" })}
>
<NativeSelectOption value="block">Block</NativeSelectOption>
<NativeSelectOption value="allow">Allow</NativeSelectOption>
<NativeSelectOption value="block">{t("Block")}</NativeSelectOption>
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
</NativeSelect>
<NativeSelect
size="sm"
@@ -79,7 +80,7 @@ export function AssetInterceptRulesEditor({
/>
<Input
className="w-[120px] shrink-0"
placeholder="Note (optional)"
placeholder={t("Note (optional)")}
value={r.note}
onChange={(e) => update(i, { note: e.target.value })}
/>
@@ -96,7 +97,7 @@ export function AssetInterceptRulesEditor({
);
})}
<Button type="button" size="sm" variant="outline" className="w-fit" onClick={add}>
<PlusIcon className="size-4" /> Add row
<PlusIcon className="size-4" /> {t("Add row")}
</Button>
</div>
);
+4 -3
View File
@@ -6,6 +6,7 @@ import { CheckIcon, CopyIcon } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { t } from "@/i18n";
import { cn, copyText } from "@/lib/utils";
type CopyButtonProps = {
@@ -23,8 +24,8 @@ type CopyButtonProps = {
// contexts it degrades automatically (see copyText).
export function CopyButton({
text,
successMessage = "Copied",
label = "Copy",
successMessage = t("Copied"),
label = t("Copy"),
size = "sm",
variant = "outline",
className,
@@ -47,7 +48,7 @@ export function CopyButton({
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(false), 1500);
} else {
toast.error("Copy failed; select the text manually to copy");
toast.error(t("Copy failed; select the text manually to copy"));
}
}
+7 -4
View File
@@ -2,12 +2,15 @@
import * as React from "react";
import { format, subDays } from "date-fns";
import { subDays } from "date-fns";
import type { DateRange } from "react-day-picker";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { intlLocale, t } from "@/i18n";
const fmtDate = (d: Date) => d.toLocaleDateString(intlLocale, { day: "numeric", month: "short", year: "numeric" });
interface DateRangePickerProps {
value?: DateRange;
@@ -22,14 +25,14 @@ export function DateRangePicker({ value, onChange }: DateRangePickerProps) {
return { from, to };
});
const dateRange = value ?? internalDateRange;
let dateRangeLabel = "Select date";
let dateRangeLabel = t("Select date");
if (dateRange?.from) {
dateRangeLabel = format(dateRange.from, "d MMM yyyy");
dateRangeLabel = fmtDate(dateRange.from);
}
if (dateRange?.from && dateRange.to) {
dateRangeLabel = `${format(dateRange.from, "d MMM yyyy")} - ${format(dateRange.to, "d MMM yyyy")}`;
dateRangeLabel = `${fmtDate(dateRange.from)} - ${fmtDate(dateRange.to)}`;
}
const handleDateChange = (nextValue: DateRange | undefined) => {
Binary file not shown.
+10 -10
View File
@@ -19,6 +19,7 @@ import { Spinner } from "@/components/ui/spinner";
import { Textarea } from "@/components/ui/textarea";
import { api } from "@/lib/api";
import type { FindingRetest } from "@/lib/types";
import { t } from "@/i18n";
interface FindingRetestDialogProps {
findingId: string;
@@ -42,9 +43,9 @@ export function FindingRetestDialog({ findingId, findingName, onClose, onStarted
const result = await api.startFindingRetest(findingId, notes.trim());
onStarted?.(result.retest);
onClose();
toast.success(result.created ? "Retest started; click 'Retesting' to view the session" : "This vulnerability is already being retested; view the existing session");
toast.success(result.created ? t("Retest started; click 'Retesting' to view the session") : t("This vulnerability is already being retested; view the existing session"));
} catch (e) {
toast.error(`Failed to start retest: ${(e as Error).message}`);
toast.error(t("Failed to start retest: {error}", { error: (e as Error).message }));
} finally {
submitLock.current = false;
setSubmitting(false);
@@ -55,16 +56,15 @@ export function FindingRetestDialog({ findingId, findingName, onClose, onStarted
<Dialog open onOpenChange={(open) => !open && !submitLock.current && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>Retest vulnerability #{findingId}</DialogTitle>
<DialogTitle>{t("Retest vulnerability #{id}", { id: findingId })}</DialogTitle>
<DialogDescription className="break-words">
{findingName ? <span className="mb-2 block">{findingName}</span> : null}
Retest Agent
Reads the original evidence and test constraints, then runs targeted verification in a separate session. When the retest completes successfully and confirms the fix, the vulnerability status automatically becomes "Fixed"; other verdicts keep the current status.
{t('Retest Agent reads the original evidence and test constraints, then runs targeted verification in a separate session. When the retest completes successfully and confirms the fix, the vulnerability status automatically becomes "Fixed"; other verdicts keep the current status.')}
</DialogDescription>
</DialogHeader>
<FieldGroup>
<Field data-disabled={submitting}>
<FieldLabel htmlFor={notesId}>Notes (optional)</FieldLabel>
<FieldLabel htmlFor={notesId}>{t("Notes (optional)")}</FieldLabel>
<Textarea
id={notesId}
value={notes}
@@ -72,18 +72,18 @@ export function FindingRetestDialog({ findingId, findingName, onClose, onStarted
rows={4}
disabled={submitting}
onChange={(e) => setNotes(e.target.value)}
placeholder="e.g. verify the original endpoint with the original test account; fix version is v2."
placeholder={t("e.g. verify the original endpoint with the original test account; fix version is v2.")}
/>
<FieldDescription>Add the fix version, test conditions, or limitations of this run.</FieldDescription>
<FieldDescription>{t("Add the fix version, test conditions, or limitations of this run.")}</FieldDescription>
</Field>
</FieldGroup>
<DialogFooter>
<Button variant="outline" disabled={submitting} onClick={onClose}>
Cancel
{t("Cancel")}
</Button>
<Button disabled={submitting} onClick={() => void start()}>
{submitting ? <Spinner data-icon="inline-start" /> : <RotateCcwIcon data-icon="inline-start" />}
{submitting ? "Creating…" : "Start retest"}
{submitting ? t("Creating…") : t("Start retest")}
</Button>
</DialogFooter>
</DialogContent>
+21 -20
View File
@@ -17,15 +17,16 @@ import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import { api } from "@/lib/api";
import type { FindingRetest } from "@/lib/types";
import { intlLocale, t } from "@/i18n";
const statusLabels = {
pending: "Waiting to start",
running: "Retesting",
completed: "Completed",
failed: "Retest failed",
stopped: "Stopped",
pending: t("Waiting to start"),
running: t("Retesting"),
completed: t("Completed"),
failed: t("Retest failed"),
stopped: t("Stopped"),
};
const verdictLabels = { reproduced: "Still reproducible", fixed: "Fixed", inconclusive: "Inconclusive" };
const verdictLabels = { reproduced: t("Still reproducible"), fixed: t("Fixed"), inconclusive: t("Inconclusive") };
function active(r: FindingRetest) {
return r.status === "pending" || r.status === "running";
@@ -84,21 +85,21 @@ export function FindingRetestPanel({
<Card>
<CardHeader className="flex flex-row flex-wrap items-start justify-between gap-3">
<div className="flex flex-col gap-1.5">
<CardTitle>Vulnerability retest</CardTitle>
<CardDescription>Verifies the current state in a separate session, keeping each retest's verdict and evidence.</CardDescription>
<CardTitle>{t("Vulnerability retest")}</CardTitle>
<CardDescription>{t("Verifies the current state in a separate session, keeping each retest's verdict and evidence.")}</CardDescription>
</div>
{running?.conversation_id != null ? (
<Button asChild variant="outline" size="sm">
<Link href={`/chat?c=${running.conversation_id}`} title="View the running retest session">
<Link href={`/chat?c=${running.conversation_id}`} title={t("View the running retest session")}>
<Spinner data-icon="inline-start" aria-hidden="true" />
Retesting
{t("Retesting")}
</Link>
</Button>
) : null}
{!running && !readOnly ? (
<Button size="sm" onClick={() => setOpen(true)} disabled={items === null || !!error}>
<RotateCcwIcon data-icon="inline-start" />
Start retest
{t("Start retest")}
</Button>
) : null}
</CardHeader>
@@ -106,9 +107,9 @@ export function FindingRetestPanel({
{error ? (
<Alert variant="destructive">
<AlertDescription>
Failed to load retest records: {error}
{t("Failed to load retest records: {error}", { error })}
<Button variant="outline" size="sm" onClick={() => void load()}>
Retry
{t("Retry")}
</Button>
</AlertDescription>
</Alert>
@@ -117,8 +118,8 @@ export function FindingRetestPanel({
{!error && items?.length === 0 ? (
<Empty>
<EmptyHeader>
<EmptyTitle>No retest records</EmptyTitle>
<EmptyDescription>Once the fix is deployed, start a retest to compare new and old evidence.</EmptyDescription>
<EmptyTitle>{t("No retest records")}</EmptyTitle>
<EmptyDescription>{t("Once the fix is deployed, start a retest to compare new and old evidence.")}</EmptyDescription>
</EmptyHeader>
</Empty>
) : null}
@@ -134,14 +135,14 @@ export function FindingRetestPanel({
: statusLabels[item.status]}
</Badge>
<span className="text-muted-foreground text-xs">
#{item.id} · {new Date(item.created_at).toLocaleString("zh-CN")}
#{item.id} · {new Date(item.created_at).toLocaleString(intlLocale)}
</span>
{item.conversation_id != null ? (
<Button asChild variant="ghost" size="sm" className="ml-auto">
<Link href={`/chat?c=${item.conversation_id}`}>View session</Link>
<Link href={`/chat?c=${item.conversation_id}`}>{t("View session")}</Link>
</Button>
) : (
<span className="text-muted-foreground text-xs">Conversation deleted</span>
<span className="text-muted-foreground text-xs">{t("Conversation deleted")}</span>
)}
</div>
{item.status === "completed" && item.summary ? (
@@ -152,12 +153,12 @@ export function FindingRetestPanel({
) : null}
{item.notes ? (
<p className="whitespace-pre-wrap break-words text-muted-foreground text-xs">
Notes: {item.notes}
{t("Notes: {notes}", { notes: item.notes })}
</p>
) : null}
{item.status === "completed" && item.evidence ? (
<details className="min-w-0">
<summary className="cursor-pointer text-sm">Retest evidence</summary>
<summary className="cursor-pointer text-sm">{t("Retest evidence")}</summary>
<div className="mt-3 overflow-x-auto">
<Markdown text={item.evidence} />
</div>
+26 -25
View File
@@ -26,12 +26,13 @@ import { Skeleton } from "@/components/ui/skeleton";
import { Textarea } from "@/components/ui/textarea";
import { api } from "@/lib/api";
import type { FindingTraffic, FindingTrafficBinding, TrafficEvidenceRole } from "@/lib/types";
import { intlLocale, t } from "@/i18n";
const ROLES: Record<TrafficEvidenceRole, string> = {
baseline: "Baseline",
proof: "Vulnerability proof",
verification: "Supplementary verification",
supporting: "Supporting evidence",
baseline: t("Baseline"),
proof: t("Vulnerability proof"),
verification: t("Supplementary verification"),
supporting: t("Supporting evidence"),
};
export function FindingTrafficPanel({
@@ -78,7 +79,7 @@ export function FindingTrafficPanel({
setData(await action());
setEditing(null);
onChanged();
toast.success("Traffic evidence updated");
toast.success(t("Traffic evidence updated"));
} catch (e) {
toast.error((e as Error).message);
setReload((n) => n + 1);
@@ -99,17 +100,17 @@ export function FindingTrafficPanel({
<Card>
<CardHeader>
<div className="flex flex-wrap items-center justify-between gap-2">
<CardTitle>Linked traffic {data ? `(${data.bindings.length})` : ""}</CardTitle>
<CardTitle>{t("Linked traffic")} {data ? `(${data.bindings.length})` : ""}</CardTitle>
{!readOnly ? (
<Button variant="outline" size="sm" disabled={!data || busy} onClick={() => setAdding(true)}>
<PlusIcon data-icon="inline-start" />
Link traffic
{t("Link traffic")}
</Button>
) : (
<Badge variant="outline">Inherited evidence · read-only</Badge>
<Badge variant="outline">{t("Inherited evidence · read-only")}</Badge>
)}
</div>
<CardDescription>Requests and responses organized in reproduction order. Bound evidence is kept even after raw traffic is purged.</CardDescription>
<CardDescription>{t("Requests and responses organized in reproduction order. Bound evidence is kept even after raw traffic is purged.")}</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{error ? (
@@ -117,7 +118,7 @@ export function FindingTrafficPanel({
<AlertDescription>
{error}
<Button variant="link" onClick={() => setReload((n) => n + 1)}>
Retry
{t("Retry")}
</Button>
</AlertDescription>
</Alert>
@@ -127,8 +128,8 @@ export function FindingTrafficPanel({
) : data.bindings.length === 0 ? (
<Empty>
<EmptyHeader>
<EmptyTitle>No linked traffic</EmptyTitle>
<EmptyDescription>Link baseline, vulnerability proof, and supplementary verification requests.</EmptyDescription>
<EmptyTitle>{t("No linked traffic")}</EmptyTitle>
<EmptyDescription>{t("Link baseline, vulnerability proof, and supplementary verification requests.")}</EmptyDescription>
</EmptyHeader>
</Empty>
) : (
@@ -141,7 +142,7 @@ export function FindingTrafficPanel({
<Badge variant="secondary">
{b.snapshot.method} · {b.snapshot.status}
</Badge>
<span className="text-xs text-muted-foreground">Evidence #{b.id}</span>
<span className="text-xs text-muted-foreground">{t("Evidence #{id}", { id: b.id })}</span>
</div>
<Button
variant="link"
@@ -153,11 +154,11 @@ export function FindingTrafficPanel({
{b.note ? <p className="text-sm whitespace-pre-wrap">{b.note}</p> : null}
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-xs text-muted-foreground">
{new Date(b.snapshot.captured_at * 1000).toLocaleString("zh-CN")}
{new Date(b.snapshot.captured_at * 1000).toLocaleString(intlLocale)}
</span>
<div className="flex flex-wrap gap-1">
<Button variant="outline" size="sm" onClick={() => setPreview(b.id)}>
View message
{t("View message")}
</Button>
{!readOnly ? (
<>
@@ -171,12 +172,12 @@ export function FindingTrafficPanel({
setNote(b.note);
}}
>
Edit note
{t("Edit note")}
</Button>
<Button
variant="ghost"
size="icon-sm"
aria-label={`Move evidence ${b.id} up`}
aria-label={t("Move evidence {id} up", { id: b.id })}
disabled={busy || index === 0}
onClick={() => move(index, -1)}
>
@@ -185,7 +186,7 @@ export function FindingTrafficPanel({
<Button
variant="ghost"
size="icon-sm"
aria-label={`Move evidence ${b.id} down`}
aria-label={t("Move evidence {id} down", { id: b.id })}
disabled={busy || index === data.bindings.length - 1}
onClick={() => move(index, 1)}
>
@@ -199,7 +200,7 @@ export function FindingTrafficPanel({
void mutate(() => api.removeFindingTraffic(findingId, b.id, data.version, contextTask))
}
>
Unlink
{t("Unlink")}
</Button>
</>
) : null}
@@ -236,12 +237,12 @@ export function FindingTrafficPanel({
>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit traffic evidence</DialogTitle>
<DialogDescription>Explain how this set of requests/responses supports the vulnerability conclusion.</DialogDescription>
<DialogTitle>{t("Edit traffic evidence")}</DialogTitle>
<DialogDescription>{t("Explain how this set of requests/responses supports the vulnerability conclusion.")}</DialogDescription>
</DialogHeader>
<FieldGroup>
<Field>
<FieldLabel htmlFor="evidence-role">Role</FieldLabel>
<FieldLabel htmlFor="evidence-role">{t("Role")}</FieldLabel>
<Select value={role} onValueChange={(v) => setRole(v as TrafficEvidenceRole)}>
<SelectTrigger id="evidence-role">
<SelectValue />
@@ -258,13 +259,13 @@ export function FindingTrafficPanel({
</Select>
</Field>
<Field>
<FieldLabel htmlFor="evidence-note">Evidence note</FieldLabel>
<FieldLabel htmlFor="evidence-note">{t("Evidence note")}</FieldLabel>
<Textarea id="evidence-note" value={note} onChange={(e) => setNote(e.target.value)} />
</Field>
</FieldGroup>
<DialogFooter>
<Button variant="outline" disabled={busy} onClick={() => setEditing(null)}>
Cancel
{t("Cancel")}
</Button>
<Button
disabled={busy || !editing || !data}
@@ -275,7 +276,7 @@ export function FindingTrafficPanel({
);
}}
>
Save note
{t("Save note")}
</Button>
</DialogFooter>
</DialogContent>
+8 -7
View File
@@ -7,6 +7,7 @@ import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn, copyText } from "@/lib/utils";
import { t } from "@/i18n";
export function statusTone(status: number) {
if (status >= 500) return "text-red-500";
@@ -114,7 +115,7 @@ function HighlightedBody({ body, format }: { body: string; format: BodyFormat })
export function HttpCodeBlock({ raw }: { raw: string }) {
const [wrapLines, setWrapLines] = React.useState(true);
const [copied, setCopied] = React.useState(false);
const value = raw || "(empty)";
const value = raw || t("(empty)");
const lines = value.replaceAll("\r\n", "\n").split("\n");
const separator = lines.indexOf("");
const body = separator >= 0 ? lines.slice(separator + 1).join("\n") : "";
@@ -132,7 +133,7 @@ export function HttpCodeBlock({ raw }: { raw: string }) {
setCopied(true);
return;
}
toast.error("Copy failed; use Ctrl/Cmd+A then copy");
toast.error(t("Copy failed; use Ctrl/Cmd+A then copy"));
};
const renderLine = (line: string, index: number) => {
@@ -151,14 +152,14 @@ export function HttpCodeBlock({ raw }: { raw: string }) {
type="button"
variant="ghost"
size="icon-xs"
aria-label={wrapLines ? "Disable word wrap" : "Enable word wrap"}
aria-label={wrapLines ? t("Disable word wrap") : t("Enable word wrap")}
aria-pressed={wrapLines}
onClick={() => setWrapLines((current) => !current)}
>
<WrapTextIcon />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">{wrapLines ? "Disable word wrap" : "Enable word wrap"}</TooltipContent>
<TooltipContent side="bottom">{wrapLines ? t("Disable word wrap") : t("Enable word wrap")}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
@@ -166,19 +167,19 @@ export function HttpCodeBlock({ raw }: { raw: string }) {
type="button"
variant="ghost"
size="icon-xs"
aria-label={copied ? "Message copied" : "Copy message"}
aria-label={copied ? t("Message copied") : t("Copy message")}
onClick={() => void copyPacket()}
>
{copied ? <CheckIcon /> : <CopyIcon />}
</Button>
</TooltipTrigger>
<TooltipContent side="bottom">{copied ? "Copied" : "Copy message"}</TooltipContent>
<TooltipContent side="bottom">{copied ? t("Copied") : t("Copy message")}</TooltipContent>
</Tooltip>
</div>
{/* biome-ignore lint/a11y/useSemanticElements: textarea cannot preserve line numbers and syntax-highlighting markup. */}
<div
role="textbox"
aria-label="HTTP message code"
aria-label={t("HTTP message code")}
aria-multiline="true"
aria-readonly="true"
tabIndex={0}
+21 -14
View File
@@ -18,6 +18,7 @@ import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { api } from "@/lib/api";
import type { Finding, FindingsPage } from "@/lib/types";
import { t } from "@/i18n";
export function LinkTrafficDialog({
trafficIds,
@@ -66,7 +67,9 @@ export function LinkTrafficDialog({
selected.finding_id,
trafficIds.map((traffic_id) => ({ traffic_id })),
);
toast.success(`Linked ${trafficIds.length} traffic records to vulnerability #${selected.finding_id}`);
toast.success(
t("Linked {count} traffic records to vulnerability #{id}", { count: trafficIds.length, id: selected.finding_id }),
);
onBound();
onClose();
} catch (e) {
@@ -84,15 +87,19 @@ export function LinkTrafficDialog({
>
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
<DialogHeader>
<DialogTitle>Link to vulnerability</DialogTitle>
<DialogDescription>Save the {trafficIds.length} selected traffic records as evidence of an existing vulnerability.</DialogDescription>
<DialogTitle>{t("Link to vulnerability")}</DialogTitle>
<DialogDescription>
{t("Save the {count} selected traffic records as evidence of an existing vulnerability.", {
count: trafficIds.length,
})}
</DialogDescription>
</DialogHeader>
<FieldGroup>
<Field>
<FieldLabel htmlFor="link-finding-query">Find vulnerability</FieldLabel>
<FieldLabel htmlFor="link-finding-query">{t("Find vulnerability")}</FieldLabel>
<Input
id="link-finding-query"
placeholder="Name / summary / vulnerability class"
placeholder={t("Name / summary / vulnerability class")}
value={query}
onChange={(e) => {
setQuery(e.target.value);
@@ -126,35 +133,35 @@ export function LinkTrafficDialog({
))}
{!data?.items.length ? (
<p className="py-6 text-center text-sm text-muted-foreground">
{loading ? "Loading…" : "No matching vulnerabilities; register one first"}
{loading ? t("Loading…") : t("No matching vulnerabilities; register one first")}
</p>
) : null}
</div>
<div className="flex items-center justify-between gap-2">
<Button variant="outline" size="sm" disabled={loading || page <= 1} onClick={() => setPage((p) => p - 1)}>
Previous
{t("Previous")}
</Button>
<span className="text-xs">
Page {page} · {data?.total ?? 0} total
</span>
<span className="text-xs">{t("Page {page} · {total} total", { page, total: data?.total ?? 0 })}</span>
<Button
variant="outline"
size="sm"
disabled={loading || page * 20 >= (data?.total ?? 0)}
onClick={() => setPage((p) => p + 1)}
>
Next
{t("Next")}
</Button>
</div>
<p className="text-sm">
{selected ? `Selected: #${selected.finding_id} ${selected.name || selected.vulnclass}` : "Select a vulnerability"}
{selected
? t("Selected: #{id} {name}", { id: selected.finding_id ?? "", name: selected.name || selected.vulnclass })
: t("Select a vulnerability")}
</p>
<DialogFooter>
<Button variant="outline" disabled={busy} onClick={onClose}>
Cancel
{t("Cancel")}
</Button>
<Button disabled={busy || !selected} onClick={() => void save()}>
{busy ? "Saving…" : "Link"}
{busy ? t("Saving…") : t("Link")}
</Button>
</DialogFooter>
</DialogContent>
+20 -15
View File
@@ -17,6 +17,7 @@ import {
mentionToken,
selectedMentions,
} from "@/lib/chat-mentions";
import { t } from "@/i18n";
import { cn } from "@/lib/utils";
type Props = Omit<React.ComponentProps<"textarea">, "value" | "onChange" | "ref"> & {
@@ -198,7 +199,7 @@ export function MentionTextarea({ value, onValueChange, onKeyDown, className, in
value={value}
disabled={disabled}
className={className}
aria-label={props["aria-label"] ?? "Message, type @ to reference records"}
aria-label={props["aria-label"] ?? t("Message, type @ to reference records")}
aria-autocomplete="list"
aria-controls={open ? listId : undefined}
aria-expanded={open}
@@ -230,20 +231,22 @@ export function MentionTextarea({ value, onValueChange, onKeyDown, className, in
onInteractOutside={(event) => {
if (event.target === textarea.current) event.preventDefault();
}}
aria-label="Choose a reference record"
aria-label={t("Choose a reference record")}
>
<div className="flex items-center justify-between px-2 py-1 text-muted-foreground text-xs">
<span>
{categories.length
? "Choose a reference type"
: `Search ${mentionKinds.find((kind) => kind.kind === search.kind)?.label ?? "all records"}`}
? t("Choose a reference type")
: t("Search {kind}", {
kind: mentionKinds.find((kind) => kind.kind === search.kind)?.label ?? t("all records"),
})}
</span>
<span>↑↓ Select · Enter Confirm · Esc Close</span>
<span>{t("↑↓ Select · Enter Confirm · Esc Close")}</span>
</div>
<div
id={listId}
role="listbox"
aria-label="Reference candidates"
aria-label={t("Reference candidates")}
className="max-h-60 overflow-y-auto"
onScroll={(event) => {
const list = event.currentTarget;
@@ -272,17 +275,17 @@ export function MentionTextarea({ value, onValueChange, onKeyDown, className, in
{!categories.length && loading && (
<div role="status" className="flex items-center gap-2 p-3 text-muted-foreground text-sm">
<Loader2Icon className="size-4 animate-spin" />
Searching…
{t("Searching…")}
</div>
)}
{!categories.length && !loading && error && (
<div role="alert" className="p-3 text-destructive text-sm">
Search failed: {error}. Please retype and try again.
{t("Search failed: {error}. Please retype and try again.", { error })}
</div>
)}
{!categories.length && !loading && !error && !items.length && (
<div role="status" className="p-3 text-muted-foreground text-sm">
No matching records; try a different name, address, or ID
{t("No matching records; try a different name, address, or ID")}
</div>
)}
{items.map((item, index) => (
@@ -310,17 +313,19 @@ export function MentionTextarea({ value, onValueChange, onKeyDown, className, in
</div>
{!categories.length && (
<p className="px-2 py-1 text-muted-foreground text-xs">
{loadingMore && <span role="status">Loading more…</span>}
{loadingMore && <span role="status">{t("Loading more…")}</span>}
{!loadingMore && nextCursor && (
<button type="button" onMouseDown={(event) => event.preventDefault()} onClick={loadMore}>
{pageError ? "Failed to load, click to retry" : `Showing ${items.length}, scroll down for more`}
{pageError
? t("Failed to load, click to retry")
: t("Showing {count}, scroll down for more", { count: items.length })}
</button>
)}
{!loadingMore && !nextCursor && !loading && !error && items.length > 0 && `All ${items.length} shown`}
{!loadingMore && !nextCursor && !loading && !error && items.length > 0 && t("All {count} shown", { count: items.length })}
{!loadingMore &&
!nextCursor &&
(loading || !!error || items.length === 0) &&
"Type a name, address, or ID to search records"}
t("Type a name, address, or ID to search records")}
</p>
)}
</PopoverContent>
@@ -335,7 +340,7 @@ export function MentionTextarea({ value, onValueChange, onKeyDown, className, in
<button
type="button"
disabled={disabled}
aria-label={`Remove reference ${item.label}`}
aria-label={t("Remove reference {label}", { label: item.label })}
onClick={() => {
onValueChange(value.slice(0, item.start) + value.slice(item.start + item.token.length));
setCursor(null);
@@ -345,7 +350,7 @@ export function MentionTextarea({ value, onValueChange, onKeyDown, className, in
</button>
</Badge>
))}
<span className="text-muted-foreground text-xs">Latest details read on send · Up to 10 records</span>
<span className="text-muted-foreground text-xs">{t("Latest details read on send · Up to 10 records")}</span>
</div>
)}
</div>
+11 -8
View File
@@ -5,15 +5,16 @@ import * as React from "react";
import { Badge } from "@/components/ui/badge";
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field";
import { Textarea } from "@/components/ui/textarea";
import { t } from "@/i18n";
import type { ParsedCompanyScopeText } from "@/lib/company-scope";
import type { CompanyScopeKind } from "@/lib/types";
const SCOPE_KIND_LABELS: Record<CompanyScopeKind, string> = {
domain: "domain",
domain: t("domain"),
ip: "IP",
cidr: "CIDR",
icp: "ICP",
keyword: "keyword",
keyword: t("keyword"),
};
export function ScopeTextEditor({
@@ -21,8 +22,8 @@ export function ScopeTextEditor({
value,
onValueChange,
parsed,
label = "Asset scope",
description = "One per line; domains, IPs, CIDRs, ICP filings, and company keywords are recognized automatically.",
label = t("Asset scope"),
description = t("One per line; domains, IPs, CIDRs, ICP filings, and company keywords are recognized automatically."),
}: {
id: string;
value: string;
@@ -46,13 +47,13 @@ export function ScopeTextEditor({
rows={8}
value={value}
aria-invalid={parsed.errors.length > 0}
placeholder={"example.com\n203.0.113.10\n198.51.100.0/24\nBeijing ICP 12345678-1\nCompany name keyword"}
placeholder={`example.com\n203.0.113.10\n198.51.100.0/24\nBeijing ICP 12345678-1\n${t("Company name keyword")}`}
className="min-h-36 resize-y font-mono text-sm"
onChange={(event) => onValueChange(event.target.value)}
/>
{parsed.rules.length > 0 && (
<div className="flex flex-wrap items-center gap-1.5 text-muted-foreground text-xs">
<span>{parsed.rules.length} recognized</span>
<span>{t("{count} recognized", { count: parsed.rules.length })}</span>
{Object.entries(SCOPE_KIND_LABELS).map(([kind, kindLabel]) => {
const count = counts.get(kind as CompanyScopeKind) ?? 0;
return count > 0 ? (
@@ -67,10 +68,12 @@ export function ScopeTextEditor({
<FieldError>
{parsed.errors.slice(0, 5).map((item) => (
<span key={`${item.line}-${item.error}`} className="block">
Line {item.line}: {item.error}
{t("Line {line}: {error}", { line: item.line, error: item.error })}
</span>
))}
{parsed.errors.length > 5 && <span className="block">{parsed.errors.length - 5} more errors</span>}
{parsed.errors.length > 5 && (
<span className="block">{t("{count} more errors", { count: parsed.errors.length - 5 })}</span>
)}
</FieldError>
)}
</Field>
+43 -34
View File
@@ -25,24 +25,25 @@ import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/componen
import { Skeleton } from "@/components/ui/skeleton";
import { useIsMobile } from "@/hooks/use-mobile";
import type { SideQuestions } from "@/hooks/use-side-questions";
import { intlLocale, t } from "@/i18n";
import { cn } from "@/lib/utils";
type ComposerLayout = "inline" | "stacked";
const preparationLabels = {
preparing: "Preparing context…",
summarizing_history: "Summarizing earlier side Q&A…",
compressing_snapshot: "Compressing the side-question context copy…",
retrying: "Model context exceeded, shrinking and retrying…",
answering: "Answering…",
preparing: t("Preparing context…"),
summarizing_history: t("Summarizing earlier side Q&A…"),
compressing_snapshot: t("Compressing the side-question context copy…"),
retrying: t("Model context exceeded, shrinking and retrying…"),
answering: t("Answering…"),
};
export function SideQuestionButton({ side }: { side: SideQuestions }) {
if (!side.enabled) return null;
return (
<Button variant="outline" size="sm" onClick={() => side.setOpen(true)} title="/btw side question">
<Button variant="outline" size="sm" onClick={() => side.setOpen(true)} title={t("/btw side question")}>
<MessageCircleQuestionIcon data-icon="inline-start" />
Side question
{t("Side question")}
</Button>
);
}
@@ -65,13 +66,19 @@ function SidePanel({
useEffect(() => {
if (pinned.current && viewport.current) viewport.current.scrollTop = viewport.current.scrollHeight;
}, [tail?.answer, tail?.id]);
const status = { running: "Answering", completed: "Completed", failed: "Failed", cancelled: "Stopped", interrupted: "Interrupted" };
const status = {
running: t("Answering"),
completed: t("Completed"),
failed: t("Failed"),
cancelled: t("Stopped"),
interrupted: t("Interrupted"),
};
return (
<section className="flex h-full min-h-0 flex-col bg-background" aria-label="Side question panel">
<section className="flex h-full min-h-0 flex-col bg-background" aria-label={t("Side question panel")}>
<div className="flex items-center gap-2 border-b p-3">
<div className="min-w-0 flex-1">
<p className="font-medium">
Side question <span className="text-muted-foreground">/btw</span>
{t("Side question")} <span className="text-muted-foreground">/btw</span>
</p>
<p className="truncate text-muted-foreground text-xs">{label}</p>
</div>
@@ -80,11 +87,11 @@ function SidePanel({
size="icon-sm"
onClick={() => setConfirm(true)}
disabled={!side.items.length || side.busy}
aria-label="Clear side-question history"
aria-label={t("Clear side-question history")}
>
<Trash2Icon />
</Button>
<Button variant="ghost" size="icon-sm" onClick={() => side.setOpen(false)} aria-label="Close side-question panel">
<Button variant="ghost" size="icon-sm" onClick={() => side.setOpen(false)} aria-label={t("Close side-question panel")}>
<XIcon />
</Button>
</div>
@@ -92,10 +99,10 @@ function SidePanel({
{side.snapshot ? (
<>
<p>{side.snapshot.model.model}</p>
<p>Context updated {new Date(side.snapshot.captured_at).toLocaleString()}</p>
<p>{t("Context updated {time}", { time: new Date(side.snapshot.captured_at).toLocaleString(intlLocale) })}</p>
</>
) : (
"Ask anytime after the main agent's first run"
t("Ask anytime after the main agent's first run")
)}
</div>
<div
@@ -108,15 +115,15 @@ function SidePanel({
>
{side.nextCursor > 0 && (
<Button variant="ghost" size="sm" onClick={() => void side.load(side.nextCursor)}>
Load earlier side Q&A
{t("Load earlier side Q&A")}
</Button>
)}
{side.loading && <Skeleton className="h-16 w-full" />}
{!side.loading && side.items.length === 0 && (
<Empty>
<EmptyHeader>
<EmptyTitle>Ask a question anytime</EmptyTitle>
<EmptyDescription>Answered from the current agent's context while the main task keeps running.</EmptyDescription>
<EmptyTitle>{t("Ask a question anytime")}</EmptyTitle>
<EmptyDescription>{t("Answered from the current agent's context while the main task keeps running.")}</EmptyDescription>
</EmptyHeader>
</Empty>
)}
@@ -127,15 +134,15 @@ function SidePanel({
<div className="flex flex-wrap items-center gap-2 text-muted-foreground text-xs">
<Badge variant="secondary">{status[item.status]}</Badge>
<span className="truncate">{item.model.model}</span>
<time dateTime={item.snapshot_at} title={new Date(item.snapshot_at).toLocaleString()}>
Context {new Date(item.snapshot_at).toLocaleTimeString()}
<time dateTime={item.snapshot_at} title={new Date(item.snapshot_at).toLocaleString(intlLocale)}>
{t("Context {time}", { time: new Date(item.snapshot_at).toLocaleTimeString(intlLocale) })}
</time>
</div>
{item.context?.estimated_input_tokens != null && (
<p className="text-muted-foreground text-xs">
Last {item.context.recent_exchanges} Q&A exchanges verbatim
{item.context.history_summarized && " · earlier Q&A summarized"}
{item.context.snapshot_summarized && " · uses the main-context digest"}
{t("Last {count} Q&A exchanges verbatim", { count: item.context.recent_exchanges })}
{item.context.history_summarized && ` · ${t("earlier Q&A summarized")}`}
{item.context.snapshot_summarized && ` · ${t("uses the main-context digest")}`}
</p>
)}
{item.answer && <Markdown text={item.answer} />}
@@ -163,8 +170,8 @@ function SidePanel({
<InputGroupTextarea
rows={1}
className={cn("overflow-y-auto", inlineComposer ? "max-h-40 min-h-0" : "max-h-36 min-h-9")}
aria-label="Side question"
placeholder="Ask about the current context…"
aria-label={t("Side question")}
placeholder={t("Ask about the current context…")}
value={side.draft}
maxLength={4000}
disabled={side.busy}
@@ -177,14 +184,14 @@ function SidePanel({
}}
/>
<InputGroupAddon align={inlineComposer ? "inline-end" : "block-end"}>
{!inlineComposer && <span className="text-muted-foreground text-xs">Standalone Q&A · No tool execution</span>}
{!inlineComposer && <span className="text-muted-foreground text-xs">{t("Standalone Q&A · No tool execution")}</span>}
{side.running ? (
<InputGroupButton
className="ml-auto"
variant="destructive"
size="icon-xs"
onClick={() => void side.stop()}
aria-label="Stop the side answer"
aria-label={t("Stop the side answer")}
>
<SquareIcon />
</InputGroupButton>
@@ -195,7 +202,7 @@ function SidePanel({
size="icon-xs"
onClick={() => void side.ask(side.draft)}
disabled={side.busy || !side.draft.trim() || !side.snapshot?.available}
aria-label="Send side question"
aria-label={t("Send side question")}
>
<ArrowUpIcon />
</InputGroupButton>
@@ -204,19 +211,21 @@ function SidePanel({
</InputGroup>
</div>
{inlineComposer && (
<div className="shrink-0 truncate px-3 pt-0.5 pb-1 text-muted-foreground text-xs">Standalone Q&A · No tool execution</div>
<div className="shrink-0 truncate px-3 pt-0.5 pb-1 text-muted-foreground text-xs">{t("Standalone Q&A · No tool execution")}</div>
)}
<AlertDialog open={confirm} onOpenChange={setConfirm}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Clear side-question history?</AlertDialogTitle>
<AlertDialogTitle>{t("Clear side-question history?")}</AlertDialogTitle>
<AlertDialogDescription>
Deletes this agent's side Q&A and stops any answer still being generated. The main session and context snapshot are kept.
{t(
"Deletes this agent's side Q&A and stops any answer still being generated. The main session and context snapshot are kept.",
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={() => void side.clear()}>Clear history</AlertDialogAction>
<AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={() => void side.clear()}>{t("Clear history")}</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
@@ -254,8 +263,8 @@ export function SideQuestionWorkspace({
<Drawer open={mobile && side.open && side.enabled} onOpenChange={side.setOpen}>
<DrawerContent className="h-[85svh]">
<DrawerHeader className="sr-only">
<DrawerTitle>Side question</DrawerTitle>
<DrawerDescription>Standalone Q&A for {label}</DrawerDescription>
<DrawerTitle>{t("Side question")}</DrawerTitle>
<DrawerDescription>{t("Standalone Q&A for {label}", { label })}</DrawerDescription>
</DrawerHeader>
<SidePanel side={side} label={label} composerLayout={composerLayout} />
</DrawerContent>
+6 -7
View File
@@ -7,6 +7,7 @@ import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Pagination, PaginationContent, PaginationEllipsis, PaginationItem } from "@/components/ui/pagination";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { t } from "@/i18n";
interface TablePaginationProps {
page: number; // 1-based
@@ -64,13 +65,11 @@ export function TablePagination({
))}
</SelectContent>
</Select>
<span>per page</span>
<span>{t("per page")}</span>
{total > 0 ? (
<span className="tabular-nums">
{from}–{to} / {total} total
</span>
<span className="tabular-nums">{t("{from}–{to} / {total} total", { from, to, total })}</span>
) : (
<span>0 total</span>
<span>{t("{total} total", { total: 0 })}</span>
)}
</div>
@@ -83,7 +82,7 @@ export function TablePagination({
size="icon-sm"
disabled={safePage === 1}
onClick={() => onPageChange(safePage - 1)}
aria-label="Previous page"
aria-label={t("Previous page")}
>
<ChevronLeftIcon className="size-4" />
</Button>
@@ -112,7 +111,7 @@ export function TablePagination({
size="icon-sm"
disabled={safePage === totalPages}
onClick={() => onPageChange(safePage + 1)}
aria-label="Next page"
aria-label={t("Next page")}
>
<ChevronRightIcon className="size-4" />
</Button>
+35 -27
View File
@@ -19,6 +19,7 @@ import {
} from "@/components/ui/combobox";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { LLMProfile } from "@/lib/types";
@@ -36,15 +37,15 @@ interface TaskLLMProfileChainProps {
}
function ProfileRoleBadge({ index, currentIndex }: { index: number; currentIndex: number }) {
if (index === currentIndex) return <Badge variant="default">Current</Badge>;
if (index === currentIndex) return <Badge variant="default">{t("Current")}</Badge>;
if (index < currentIndex) {
return (
<Badge variant="outline" title="Profiles before the current cursor are not picked by automatic failover">
Skipped
<Badge variant="outline" title={t("Profiles before the current cursor are not picked by automatic failover")}>
{t("Skipped")}
</Badge>
);
}
return <Badge variant="secondary">Fallback {index - currentIndex}</Badge>;
return <Badge variant="secondary">{t("Fallback {n}", { n: index - currentIndex })}</Badge>;
}
export function TaskLLMProfileChain({
@@ -79,7 +80,7 @@ export function TaskLLMProfileChain({
const profileLabel = React.useCallback(
(id: string) => {
const profile = profilesByID.get(id);
return profile ? `${profile.name} ${profile.model}` : `Profile #${id}`;
return profile ? `${profile.name} ${profile.model}` : t("Profile #{id}", { id });
},
[profilesByID],
);
@@ -110,32 +111,38 @@ export function TaskLLMProfileChain({
{onRotateChange && (
<div className="flex flex-col gap-2">
<label htmlFor={rotationID} className="flex items-center justify-between gap-3 font-medium text-sm">
Enable multi-LLM worker rotation
{t("Enable multi-LLM worker rotation")}
<Switch id={rotationID} checked={rotate} onCheckedChange={onRotateChange} disabled={disabled} />
</label>
<p className="text-muted-foreground text-xs">
{rotate
? "New worker intents use the selected profiles in round-robin order. Independent workers can run on different providers simultaneously. Other roles keep the current profile."
: "Ordered failover: workers share the current profile and switch after quota exhaustion or repeated provider failures."}
? t(
"New worker intents use the selected profiles in round-robin order. Independent workers can run on different providers simultaneously. Other roles keep the current profile.",
)
: t(
"Ordered failover: workers share the current profile and switch after quota exhaustion or repeated provider failures.",
)}
</p>
{rotate && value.length < 2 && (
<p className="text-amber-600 text-xs">Select at least two profiles to distribute work across providers.</p>
<p className="text-amber-600 text-xs">{t("Select at least two profiles to distribute work across providers.")}</p>
)}
{rotate && workerBinding != null && (
<p role="alert" className="text-amber-600 text-xs">
Worker has a fixed model binding, which overrides rotation. Set Worker’s model to follow the task in Agent
settings to use these profiles.
{t(
"Worker has a fixed model binding, which overrides rotation. Set Worker’s model to follow the task in Agent settings to use these profiles.",
)}
</p>
)}
{rotate && bindingCheckFailed && (
<p className="text-amber-600 text-xs">
Worker binding could not be checked. A fixed Worker model overrides rotation; verify Agent settings.
{t("Worker binding could not be checked. A fixed Worker model overrides rotation; verify Agent settings.")}
</p>
)}
{rotate && (
<p className="text-muted-foreground text-xs">
Set concurrent worker count to at least 2 in System settings before starting the task. In-flight calls
keep their provider. Exhausted profiles are skipped until the chain is reset.
{t(
"Set concurrent worker count to at least 2 in System settings before starting the task. In-flight calls keep their provider. Exhausted profiles are skipped until the chain is reset.",
)}
</p>
)}
</div>
@@ -156,12 +163,12 @@ export function TaskLLMProfileChain({
</ComboboxValue>
<ComboboxChipsInput
id={inputId}
placeholder={profiles.length > 0 ? "Search and add LLM profiles" : "No LLM profiles available"}
placeholder={profiles.length > 0 ? t("Search and add LLM profiles") : t("No LLM profiles available")}
disabled={disabled ? true : profilesUnavailable}
/>
</ComboboxChips>
<ComboboxContent portalContainer={portalContainer}>
<ComboboxEmpty>No matching LLM profiles</ComboboxEmpty>
<ComboboxEmpty>{t("No matching LLM profiles")}</ComboboxEmpty>
<ComboboxList>
{(id) => {
const profile = profilesByID.get(id);
@@ -170,8 +177,9 @@ export function TaskLLMProfileChain({
<div className="flex min-w-0 flex-1 flex-col">
<span className="flex min-w-0 items-center gap-2">
<span className="truncate">
{profile?.name ?? `Profile #${id}`}
{profile?.is_default ? " (active)" : ""}
{profile?.is_default
? t("{name} (active)", { name: profile.name })
: (profile?.name ?? t("Profile #{id}", { id }))}
</span>
</span>
{profile && <span className="truncate text-muted-foreground text-xs">{profile.model}</span>}
@@ -185,7 +193,7 @@ export function TaskLLMProfileChain({
{value.length === 0 ? (
<p className="text-muted-foreground text-xs">
When no profile is set, the task follows the agent or the global active profile.
{t("When no profile is set, the task follows the agent or the global active profile.")}
</p>
) : (
<div className="flex flex-col divide-y rounded-lg border">
@@ -198,13 +206,13 @@ export function TaskLLMProfileChain({
>
<span className="w-5 shrink-0 text-center text-muted-foreground text-xs tabular-nums">{index + 1}</span>
<div className="min-w-0 sm:flex-1">
<p className="truncate font-medium text-sm">{profile?.name ?? `Profile #${id}`}</p>
<p className="truncate font-medium text-sm">{profile?.name ?? t("Profile #{id}", { id })}</p>
<div className="flex min-w-0 items-center gap-2">
<p className="truncate text-muted-foreground text-xs">{profile?.model ?? "Profile unavailable"}</p>
<p className="truncate text-muted-foreground text-xs">{profile?.model ?? t("Profile unavailable")}</p>
</div>
</div>
{rotate ? (
<Badge variant="secondary">Rotation {index + 1}</Badge>
<Badge variant="secondary">{t("Rotation {n}", { n: index + 1 })}</Badge>
) : (
<ProfileRoleBadge index={index} currentIndex={currentIndex} />
)}
@@ -213,7 +221,7 @@ export function TaskLLMProfileChain({
type="button"
variant="ghost"
size="icon-sm"
aria-label="Move profile up"
aria-label={t("Move profile up")}
onClick={() => move(index, -1)}
disabled={disabled ? true : index === 0}
>
@@ -223,7 +231,7 @@ export function TaskLLMProfileChain({
type="button"
variant="ghost"
size="icon-sm"
aria-label="Move profile down"
aria-label={t("Move profile down")}
onClick={() => move(index, 1)}
disabled={disabled ? true : index === value.length - 1}
>
@@ -233,7 +241,7 @@ export function TaskLLMProfileChain({
type="button"
variant="ghost"
size="icon-sm"
aria-label="Remove profile"
aria-label={t("Remove profile")}
onClick={() => remove(id)}
disabled={disabled}
>
@@ -248,7 +256,7 @@ export function TaskLLMProfileChain({
{onActiveProfileChange && value.length > 0 && (
<div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
<span className="font-medium text-sm">{rotate ? "Planner / failover profile" : "Current profile"}</span>
<span className="font-medium text-sm">{rotate ? t("Planner / failover profile") : t("Current profile")}</span>
<Select
value={activeProfileId && value.includes(activeProfileId) ? activeProfileId : value[0]}
onValueChange={onActiveProfileChange}
@@ -263,7 +271,7 @@ export function TaskLLMProfileChain({
const profile = profilesByID.get(id);
return (
<SelectItem key={id} value={id} disabled={!profile}>
{profile?.name ?? `Profile #${id}`}
{profile?.name ?? t("Profile #{id}", { id })}
</SelectItem>
);
})}
+52 -41
View File
@@ -34,6 +34,7 @@ import { Spinner } from "@/components/ui/spinner";
import { Textarea } from "@/components/ui/textarea";
import { api } from "@/lib/api";
import type { AssetInterceptRuleInput, TaskCategory, TaskTemplate } from "@/lib/types";
import { t } from "@/i18n";
import { cn } from "@/lib/utils";
interface TemplateDraft {
@@ -151,7 +152,7 @@ function TaskTemplateManager({
.filter((r) => r.pattern !== ""),
};
if (!input.name || !input.description || !input.goal) {
toast.error("Fill in the template name, description, and goal");
toast.error(t("Fill in the template name, description, and goal"));
return;
}
setSaving(true);
@@ -161,15 +162,15 @@ function TaskTemplateManager({
onCreated(created);
setSelectedID(created.id);
setDraft(templateDraft(created));
toast.success("Template created");
toast.success(t("Template created"));
} else {
const updated = await api.updateTaskTemplate(selectedID, input);
onUpdated(updated);
setDraft(templateDraft(updated));
toast.success("Template updated");
toast.success(t("Template updated"));
}
} catch (error) {
toast.error(`Save failed: ${(error as Error).message}`);
toast.error(t("Save failed: {error}", { error: (error as Error).message }));
} finally {
setSaving(false);
}
@@ -190,35 +191,39 @@ function TaskTemplateManager({
startNew();
}
setDeleteOpen(false);
toast.success("Template deleted");
toast.success(t("Template deleted"));
} catch (error) {
toast.error(`Delete failed: ${(error as Error).message}`);
toast.error(t("Delete failed: {error}", { error: (error as Error).message }));
} finally {
setDeleting(false);
}
}
let saveLabel = saving ? "Saving" : "Save changes";
if (!saving && selectedID == null) saveLabel = "Create template";
let saveLabel = saving ? t("Saving") : t("Save changes");
if (!saving && selectedID == null) saveLabel = t("Create template");
return (
<>
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="grid h-full w-full! max-w-none! grid-rows-[auto_minmax(0,1fr)_auto] gap-0 overflow-hidden p-0 sm:w-[48rem]! sm:max-w-[48rem]!">
<SheetHeader className="border-b px-6 py-5">
<SheetTitle>Task template management</SheetTitle>
<SheetDescription>Templates store the description, goal, category, and task-level intercept/allow rules; edits do not affect already-created tasks.</SheetDescription>
<SheetTitle>{t("Task template management")}</SheetTitle>
<SheetDescription>
{t(
"Templates store the description, goal, category, and task-level intercept/allow rules; edits do not affect already-created tasks.",
)}
</SheetDescription>
</SheetHeader>
<div className="grid min-h-0 overflow-y-auto lg:grid-cols-[15rem_minmax(0,1fr)] lg:overflow-hidden">
<div className="flex min-h-0 flex-col border-b p-3 lg:border-r lg:border-b-0">
<Button type="button" variant="outline" className="w-full" onClick={startNew}>
<PlusIcon data-icon="inline-start" />
Create template
{t("Create template")}
</Button>
<ScrollArea className="mt-2 max-h-44 lg:max-h-none lg:flex-1">
<div className="flex flex-col gap-1 pr-2">
{templates.length === 0 && (
<p className="px-2 py-6 text-center text-muted-foreground text-sm">No templates yet</p>
<p className="px-2 py-6 text-center text-muted-foreground text-sm">{t("No templates yet")}</p>
)}
{templates.map((template) => (
<button
@@ -240,37 +245,37 @@ function TaskTemplateManager({
<ScrollArea className="min-h-0">
<FieldGroup className="p-6">
<Field>
<FieldLabel htmlFor="task-template-name">Template name</FieldLabel>
<FieldLabel htmlFor="task-template-name">{t("Template name")}</FieldLabel>
<Input
id="task-template-name"
value={draft.name}
maxLength={120}
placeholder="e.g. External web penetration testing"
placeholder={t("e.g. External web penetration testing")}
onChange={(event) => updateDraft("name", event.target.value)}
/>
</Field>
<Field>
<FieldLabel htmlFor="task-template-description">Description</FieldLabel>
<FieldLabel htmlFor="task-template-description">{t("Description")}</FieldLabel>
<Textarea
id="task-template-description"
className="min-h-28"
value={draft.description}
placeholder="Test target and background"
placeholder={t("Test target and background")}
onChange={(event) => updateDraft("description", event.target.value)}
/>
</Field>
<Field>
<FieldLabel htmlFor="task-template-goal">Goal</FieldLabel>
<FieldLabel htmlFor="task-template-goal">{t("Goal")}</FieldLabel>
<Textarea
id="task-template-goal"
className="min-h-28"
value={draft.goal}
placeholder="Goals the task needs to achieve"
placeholder={t("Goals the task needs to achieve")}
onChange={(event) => updateDraft("goal", event.target.value)}
/>
</Field>
<Field>
<FieldLabel htmlFor="task-template-category">Task category</FieldLabel>
<FieldLabel htmlFor="task-template-category">{t("Task category")}</FieldLabel>
<NativeSelect
id="task-template-category"
className="w-full"
@@ -279,23 +284,23 @@ function TaskTemplateManager({
patchDraft({ categoryID: event.target.value === "" ? null : Number(event.target.value) })
}
>
<NativeSelectOption value="">Uncategorized</NativeSelectOption>
<NativeSelectOption value="">{t("Uncategorized")}</NativeSelectOption>
{categories.map((c) => (
<NativeSelectOption key={c.id} value={String(c.id)}>
{c.name}
</NativeSelectOption>
))}
</NativeSelect>
<FieldDescription>This category is prefilled when the template is applied (still editable).</FieldDescription>
<FieldDescription>{t("This category is prefilled when the template is applied (still editable).")}</FieldDescription>
</Field>
<Field>
<FieldLabel>Task-level intercept / allow rules</FieldLabel>
<FieldLabel>{t("Task-level intercept / allow rules")}</FieldLabel>
<AssetInterceptRulesEditor
value={draft.interceptRules}
onChange={(rules) => patchDraft({ interceptRules: rules })}
/>
<FieldDescription>
These task-level rules are prefilled when the template is applied (intercept/allow, effective only for new tasks, never global).
{t("These task-level rules are prefilled when the template is applied (intercept/allow, effective only for new tasks, never global).")}
</FieldDescription>
</Field>
</FieldGroup>
@@ -305,11 +310,11 @@ function TaskTemplateManager({
{selectedID != null && (
<Button type="button" variant="destructive" className="sm:mr-auto" onClick={() => setDeleteOpen(true)}>
<Trash2Icon data-icon="inline-start" />
Delete template
{t("Delete template")}
</Button>
)}
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Close
{t("Close")}
</Button>
<Button type="button" disabled={saving} onClick={() => void save()}>
{saving ? <Spinner data-icon="inline-start" /> : <SaveIcon data-icon="inline-start" />}
@@ -321,11 +326,11 @@ function TaskTemplateManager({
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete template "{draft.name || "Untitled template"}"?</AlertDialogTitle>
<AlertDialogDescription>Tasks already created from this template are not affected.</AlertDialogDescription>
<AlertDialogTitle>{t('Delete template "{name}"?', { name: draft.name || t("Untitled template") })}</AlertDialogTitle>
<AlertDialogDescription>{t("Tasks already created from this template are not affected.")}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
<AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
disabled={deleting}
@@ -335,7 +340,7 @@ function TaskTemplateManager({
}}
>
{deleting && <Spinner data-icon="inline-start" />}
{deleting ? "Deleting" : "Delete"}
{deleting ? t("Deleting") : t("Delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -378,7 +383,7 @@ export function TaskTemplateControls({
setTemplates(await api.taskTemplates());
} catch (error) {
setTemplates([]);
toast.error(`Failed to load templates: ${(error as Error).message}`);
toast.error(t("Failed to load templates: {error}", { error: (error as Error).message }));
} finally {
setLoading(false);
}
@@ -433,18 +438,18 @@ export function TaskTemplateControls({
if (selectedTemplateID === id) onSelectedTemplateIDChange(null);
};
let pickerPlaceholder = loading ? "Loading templates" : "No task templates yet";
if (!loading && templates.length > 0) pickerPlaceholder = "Search and select a task template";
let pickerPlaceholder = loading ? t("Loading templates") : t("No task templates yet");
if (!loading && templates.length > 0) pickerPlaceholder = t("Search and select a task template");
return (
<>
<Field>
<div className="flex flex-wrap items-center justify-between gap-2">
<FieldLabel htmlFor="task-template-picker">Task template</FieldLabel>
<FieldLabel htmlFor="task-template-picker">{t("Task template")}</FieldLabel>
<div className="flex flex-wrap gap-2">
<Button type="button" variant="ghost" size="sm" onClick={() => openManager(null)}>
<Settings2Icon data-icon="inline-start" />
Manage templates
{t("Manage templates")}
</Button>
<Button
type="button"
@@ -461,7 +466,7 @@ export function TaskTemplateControls({
}
>
<SaveIcon data-icon="inline-start" />
Save as template
{t("Save as template")}
</Button>
</div>
</div>
@@ -482,7 +487,7 @@ export function TaskTemplateControls({
showClear
/>
<ComboboxContent portalContainer={portalContainer}>
<ComboboxEmpty>No matching templates</ComboboxEmpty>
<ComboboxEmpty>{t("No matching templates")}</ComboboxEmpty>
<ComboboxList>
{(template) => (
<ComboboxItem key={template.id} value={template}>
@@ -498,7 +503,11 @@ export function TaskTemplateControls({
</ComboboxList>
</ComboboxContent>
</Combobox>
<FieldDescription>Selecting copies the template's description, goal, category, and task-level rules; no link to the template is kept.</FieldDescription>
<FieldDescription>
{t(
"Selecting copies the template's description, goal, category, and task-level rules; no link to the template is kept.",
)}
</FieldDescription>
</Field>
<AlertDialog
@@ -511,13 +520,15 @@ export function TaskTemplateControls({
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Use template "{pendingTemplate?.name}"?</AlertDialogTitle>
<AlertDialogDescription>The description and goal already filled in will be overwritten by the template.</AlertDialogDescription>
<AlertDialogTitle>{t('Use template "{name}"?', { name: pendingTemplate?.name ?? "" })}</AlertDialogTitle>
<AlertDialogDescription>
{t("The description and goal already filled in will be overwritten by the template.")}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={() => pendingTemplate && applyTemplate(pendingTemplate)}>
Overwrite and use
{t("Overwrite and use")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
+12 -10
View File
@@ -4,6 +4,7 @@ import * as React from "react";
import { ListTodo } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { t } from "@/i18n";
import { cn } from "@/lib/utils";
// TodoPopover shows the latest TodoWrite state of a session (chat conversation or
@@ -33,7 +34,7 @@ export function TodoPopover({
const parsed = JSON.parse(start >= 0 ? detail.slice(start) : detail);
setTodos(Array.isArray(parsed?.todos) ? parsed.todos : []);
} catch {
setErr("Failed to parse todos");
setErr(t("Failed to parse todos"));
setTodos(null);
} finally {
setLoading(false);
@@ -53,29 +54,30 @@ export function TodoPopover({
<button
type="button"
disabled={disabled}
title={disabled ? "No todos in this session" : "View latest todos"}
title={disabled ? t("No todos in this session") : t("View latest todos")}
className="text-muted-foreground/70 hover:text-primary flex items-center gap-0.5 text-xs disabled:pointer-events-none disabled:opacity-40"
>
<ListTodo className="size-3" />
Todo
{t("Todo")}
</button>
</PopoverTrigger>
<PopoverContent align="end" className="max-h-80 w-80 overflow-auto p-2">
<p className="text-muted-foreground px-1 pb-1 text-[11px] font-medium">
Latest todos{loading ? " · Loading…" : ""}
{t("Latest todos")}
{loading ? ` · ${t("Loading…")}` : ""}
</p>
{err && <p className="text-destructive px-1 text-xs">{err}</p>}
{todos && todos.length === 0 && !loading && (
<p className="text-muted-foreground px-1 text-xs">(empty)</p>
<p className="text-muted-foreground px-1 text-xs">{t("(empty)")}</p>
)}
<ul className="space-y-0.5">
{(todos ?? []).map((t, i) => (
{(todos ?? []).map((todo, i) => (
<li
key={`${i}:${t.content}`}
className={cn("flex gap-1.5 px-1 text-xs", t.status === "completed" && "text-muted-foreground line-through")}
key={`${i}:${todo.content}`}
className={cn("flex gap-1.5 px-1 text-xs", todo.status === "completed" && "text-muted-foreground line-through")}
>
<span className="shrink-0">{MARK[t.status] ?? "☐"}</span>
<span className="break-words">{t.content}</span>
<span className="shrink-0">{MARK[todo.status] ?? "☐"}</span>
<span className="break-words">{todo.content}</span>
</li>
))}
</ul>
+13 -11
View File
@@ -12,6 +12,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { api } from "@/lib/api";
import type { FindingTrafficDetail, TrafficDetail } from "@/lib/types";
import { intlLocale, t } from "@/i18n";
export function TrafficEvidenceViewer({
findingId,
@@ -71,9 +72,9 @@ export function TrafficEvidenceViewer({
>
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-4xl">
<DialogHeader>
<DialogTitle>Traffic evidence #{bindingId}</DialogTitle>
<DialogTitle>{t("Traffic evidence #{id}", { id: bindingId ?? "" })}</DialogTitle>
<DialogDescription className="break-all">
{detail?.binding.snapshot.url ?? "View the request and response saved at binding time"}
{detail?.binding.snapshot.url ?? t("View the request and response saved at binding time")}
</DialogDescription>
</DialogHeader>
{error ? (
@@ -83,14 +84,15 @@ export function TrafficEvidenceViewer({
) : detail ? (
<Tabs defaultValue="request">
<TabsList>
<TabsTrigger value="request">Request</TabsTrigger>
<TabsTrigger value="response">Response</TabsTrigger>
<TabsTrigger value="request">{t("Request")}</TabsTrigger>
<TabsTrigger value="response">{t("Response")}</TabsTrigger>
</TabsList>
{(["request", "response"] as const).map((side) => (
<TabsContent key={side} value={side}>
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-xs text-muted-foreground">
Body {detail[side].total.toLocaleString()} bytes{detail[side].truncated ? " · preview" : ""}
{t("Body {size} bytes", { size: detail[side].total.toLocaleString(intlLocale) })}
{detail[side].truncated ? ` · ${t("preview")}` : ""}
</span>
<Button
variant="outline"
@@ -101,7 +103,7 @@ export function TrafficEvidenceViewer({
.catch((e: Error) => toast.error(e.message))
}
>
Download full {side === "request" ? "request" : "response"} body
{side === "request" ? t("Download full request body") : t("Download full response body")}
</Button>
</div>
<HttpCodeBlock
@@ -109,7 +111,7 @@ export function TrafficEvidenceViewer({
/>
{detail[side].truncated && !detail[side].binary ? (
<Button variant="outline" size="sm" disabled={busy} onClick={() => void more(side)}>
Load more body
{t("Load more body")}
</Button>
) : null}
</TabsContent>
@@ -152,8 +154,8 @@ export function CapturedTrafficViewer({ id, onClose }: { id: string | null; onCl
>
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-4xl">
<DialogHeader>
<DialogTitle>Traffic preview</DialogTitle>
<DialogDescription>Traffic ID: {id}. The full body is saved when binding.</DialogDescription>
<DialogTitle>{t("Traffic preview")}</DialogTitle>
<DialogDescription>{t("Traffic ID: {id}. The full body is saved when binding.", { id: id ?? "" })}</DialogDescription>
</DialogHeader>
{error ? (
<Alert variant="destructive">
@@ -162,8 +164,8 @@ export function CapturedTrafficViewer({ id, onClose }: { id: string | null; onCl
) : detail ? (
<Tabs defaultValue="request">
<TabsList>
<TabsTrigger value="request">Request</TabsTrigger>
<TabsTrigger value="response">Response</TabsTrigger>
<TabsTrigger value="request">{t("Request")}</TabsTrigger>
<TabsTrigger value="response">{t("Response")}</TabsTrigger>
</TabsList>
<TabsContent value="request">
<HttpCodeBlock raw={detail.req} />
+26 -25
View File
@@ -23,6 +23,7 @@ import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectVa
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { api } from "@/lib/api";
import type { FindingTrafficBinding, TrafficResp } from "@/lib/types";
import { intlLocale, t } from "@/i18n";
const METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
@@ -92,7 +93,7 @@ export function TrafficPickerDialog({
[...selected].map((traffic_id) => ({ traffic_id })),
contextTask,
);
toast.success(`Bound ${selected.size} traffic records`);
toast.success(t("Bound {count} traffic records", { count: selected.size }));
onBound();
onClose();
} catch (e) {
@@ -112,18 +113,18 @@ export function TrafficPickerDialog({
>
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-5xl">
<DialogHeader>
<DialogTitle>Bind traffic</DialogTitle>
<DialogTitle>{t("Bind traffic")}</DialogTitle>
<DialogDescription>
Filter and multi-select requests/responses; selections persist across pages. After binding you can set purpose, notes, and order.
{t("Filter and multi-select requests/responses; selections persist across pages. After binding you can set purpose, notes, and order.")}
</DialogDescription>
</DialogHeader>
<FieldGroup className="flex flex-col gap-3 sm:flex-row">
<Field>
<FieldLabel htmlFor="evidence-host">Target host</FieldLabel>
<FieldLabel htmlFor="evidence-host">{t("Target host")}</FieldLabel>
<Input
id="evidence-host"
value={host}
placeholder="Domain or IP"
placeholder={t("Domain or IP")}
onChange={(e) => {
setHost(e.target.value);
setPage(0);
@@ -131,7 +132,7 @@ export function TrafficPickerDialog({
/>
</Field>
<Field>
<FieldLabel htmlFor="evidence-method">Request method</FieldLabel>
<FieldLabel htmlFor="evidence-method">{t("Request method")}</FieldLabel>
<Select
value={method}
onValueChange={(v) => {
@@ -144,7 +145,7 @@ export function TrafficPickerDialog({
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="all">All methods</SelectItem>
<SelectItem value="all">{t("All methods")}</SelectItem>
{METHODS.map((m) => (
<SelectItem key={m} value={m}>
{m}
@@ -155,11 +156,11 @@ export function TrafficPickerDialog({
</Select>
</Field>
<Field>
<FieldLabel htmlFor="evidence-query">Keyword</FieldLabel>
<FieldLabel htmlFor="evidence-query">{t("Keyword")}</FieldLabel>
<Input
id="evidence-query"
value={query}
placeholder="URL / body keyword"
placeholder={t("URL / body keyword")}
onChange={(e) => {
setQuery(e.target.value);
setPage(0);
@@ -178,7 +179,7 @@ export function TrafficPickerDialog({
<TableRow>
<TableHead>
<Checkbox
aria-label="Select unbound traffic on this page"
aria-label={t("Select unbound traffic on this page")}
disabled={loading || busy || selectable.length === 0}
checked={selectable.length > 0 && selectable.every((e) => selected.has(e.id))}
onCheckedChange={(checked) =>
@@ -193,10 +194,10 @@ export function TrafficPickerDialog({
}
/>
</TableHead>
<TableHead>Method / URL</TableHead>
<TableHead>Time</TableHead>
<TableHead>Status code</TableHead>
<TableHead>Actions</TableHead>
<TableHead>{t("Method / URL")}</TableHead>
<TableHead>{t("Time")}</TableHead>
<TableHead>{t("Status code")}</TableHead>
<TableHead>{t("Actions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -204,7 +205,7 @@ export function TrafficPickerDialog({
<TableRow key={e.id}>
<TableCell>
<Checkbox
aria-label={`Select traffic ${e.id}`}
aria-label={t("Select traffic {id}", { id: e.id })}
checked={selected.has(e.id) || alreadyBound.has(e.id)}
disabled={busy || loading || alreadyBound.has(e.id)}
onCheckedChange={(checked) => toggle(e.id, checked === true)}
@@ -214,15 +215,15 @@ export function TrafficPickerDialog({
<span className="font-mono text-xs">
{e.method} {e.url}
</span>
{alreadyBound.has(e.id) ? <Badge variant="secondary">Bound</Badge> : null}
{alreadyBound.has(e.id) ? <Badge variant="secondary">{t("Bound")}</Badge> : null}
</TableCell>
<TableCell className="whitespace-nowrap text-xs">
{new Date(e.ts).toLocaleString("zh-CN")}
{new Date(e.ts).toLocaleString(intlLocale)}
</TableCell>
<TableCell>{e.status}</TableCell>
<TableCell>
<Button variant="ghost" size="sm" onClick={() => setPreview(e.id)}>
Preview
{t("Preview")}
</Button>
</TableCell>
</TableRow>
@@ -230,7 +231,7 @@ export function TrafficPickerDialog({
{!rows.length ? (
<TableRow>
<TableCell colSpan={5} className="py-8 text-center">
{loading ? "Loading…" : "No matching traffic"}
{loading ? t("Loading…") : t("No matching traffic")}
</TableCell>
</TableRow>
) : null}
@@ -239,7 +240,7 @@ export function TrafficPickerDialog({
</div>
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-sm">
{selected.size} selected · {data?.total ?? 0} total
{t("{selected} selected · {total} total", { selected: selected.size, total: data?.total ?? 0 })}
</span>
<div className="flex items-center gap-2">
<Button
@@ -248,25 +249,25 @@ export function TrafficPickerDialog({
disabled={loading || page === 0}
onClick={() => setPage((p) => p - 1)}
>
Previous
{t("Previous")}
</Button>
<span className="text-xs">Page {page + 1}</span>
<span className="text-xs">{t("Page {page}", { page: page + 1 })}</span>
<Button
variant="outline"
size="sm"
disabled={loading || (page + 1) * 25 >= (data?.total ?? 0)}
onClick={() => setPage((p) => p + 1)}
>
Next
{t("Next")}
</Button>
</div>
</div>
<DialogFooter>
<Button variant="outline" disabled={busy} onClick={onClose}>
Cancel
{t("Cancel")}
</Button>
<Button disabled={busy || selected.size === 0} onClick={() => void save()}>
{busy ? "Saving…" : `Bind ${selected.size} traffic records`}
{busy ? t("Saving…") : t("Bind {count} traffic records", { count: selected.size })}
</Button>
</DialogFooter>
</DialogContent>
+36 -31
View File
@@ -17,6 +17,7 @@ import {
} from "lucide-react";
import { toast } from "sonner";
import { api } from "@/lib/api";
import { intlLocale, t } from "@/i18n";
import { Markdown } from "@/components/markdown";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -90,7 +91,7 @@ function groupSteps(steps: Activity[], chat: boolean): Group[] {
for (const s of steps) {
if (s.kind === "usage") continue; // live token-usage marker — not a rendered step
if (s.kind === "round") {
out.push({ type: "round", key: s.seq, label: s.summary || "New round" }); // planner round boundary
out.push({ type: "round", key: s.seq, label: s.summary || t("New round") }); // planner round boundary
continue;
}
if (s.kind === "intercept_request") {
@@ -129,7 +130,7 @@ function groupSteps(steps: Activity[], chat: boolean): Group[] {
return out;
}
const kindLabel = (k: string) => (k === "thinking" ? "Thinking" : k === "result" ? "Summary" : "Note");
const kindLabel = (k: string) => (k === "thinking" ? t("Thinking") : k === "result" ? t("Summary") : t("Note"));
function ActivityTime({ ts }: { ts: string }) {
const date = new Date(ts);
@@ -137,11 +138,11 @@ function ActivityTime({ ts }: { ts: string }) {
return (
<time
dateTime={date.toISOString()}
title={date.toLocaleString("zh-CN")}
title={date.toLocaleString(intlLocale)}
className="text-[10px] text-muted-foreground tabular-nums"
suppressHydrationWarning
>
{date.toLocaleString("zh-CN", {
{date.toLocaleString(intlLocale, {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
@@ -234,7 +235,7 @@ function InterceptCard({
setStatusError("");
if (p.status !== "pending") setDecided(p.status as "allowed" | "denied" | "timeout");
})
.catch((error) => { if (live) setStatusError((error as Error).message || "Failed to load approval details"); });
.catch((error) => { if (live) setStatusError((error as Error).message || t("Failed to load approval details")); });
return () => { live = false; };
}, [pendingId, retry]);
@@ -244,7 +245,7 @@ function InterceptCard({
try {
await api.interceptDecide(pendingId, decision);
setDecided(decision);
toast.success(decision === "allowed" ? "Execution allowed" : "Execution denied");
toast.success(decision === "allowed" ? t("Execution allowed") : t("Execution denied"));
} catch (e) {
toast.error((e as Error).message);
} finally {
@@ -265,7 +266,7 @@ function InterceptCard({
<ShieldAlertIcon className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-500" />
<div className="min-w-0 space-y-0.5">
<div className="flex items-center gap-1.5 font-medium">
<span className="text-amber-700 dark:text-amber-400">Approval request</span>
<span className="text-amber-700 dark:text-amber-400">{t("Approval request")}</span>
<code className="rounded bg-amber-100 dark:bg-amber-900/50 px-1 font-mono text-amber-800 dark:text-amber-300">
{toolName}
</code>
@@ -280,7 +281,7 @@ function InterceptCard({
</div>
{step.inherited ? (
<Badge variant="outline">History · Read-only</Badge>
<Badge variant="outline">{t("History · Read-only")}</Badge>
) : decided ? (
<span className={
"shrink-0 rounded px-2 py-0.5 text-[11px] font-medium " +
@@ -290,7 +291,7 @@ function InterceptCard({
? "bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400"
: "bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-400")
}>
{decided === "allowed" ? "Allowed" : decided === "timeout" ? "Timed out" : "Denied"}
{decided === "allowed" ? t("Allowed") : decided === "timeout" ? t("Timed out") : t("Denied")}
</span>
) : (
<div className="flex shrink-0 gap-1.5">
@@ -301,7 +302,7 @@ function InterceptCard({
onClick={() => decide("allowed")}
>
<CheckIcon className="h-3 w-3" />
Allow
{t("Allow")}
</Button>
<Button
size="sm"
@@ -311,7 +312,7 @@ function InterceptCard({
onClick={() => decide("denied")}
>
<XIcon className="h-3 w-3" />
Deny
{t("Deny")}
</Button>
</div>
)}
@@ -319,9 +320,10 @@ function InterceptCard({
{pendingId ? (
<Collapsible open={expanded} onOpenChange={setExpanded} className="mt-2 min-w-0">
<CollapsibleTrigger asChild>
<Button variant="ghost" size="sm" aria-label={expanded ? "Collapse approval details" : "Expand approval details"}>
<Button variant="ghost" size="sm" aria-label={expanded ? t("Collapse approval details") : t("Expand approval details")}
>
{expanded ? <ChevronDown data-icon="inline-start" /> : <ChevronRight data-icon="inline-start" />}
{expanded ? "Collapse approval details" : "Expand approval details"}
{expanded ? t("Collapse approval details") : t("Expand approval details")}
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
@@ -338,9 +340,11 @@ function InterceptCard({
) : statusError ? (
<div className="flex flex-wrap items-center gap-2 p-3" role="alert">
<span>{statusError}</span>
<Button variant="outline" size="sm" onClick={() => setRetry((value) => value + 1)}>Retry details</Button>
<Button variant="outline" size="sm" onClick={() => setRetry((value) => value + 1)}>
{t("Retry details")}
</Button>
</div>
) : <p className="p-3 text-muted-foreground">Loading approval details…</p>}
) : <p className="p-3 text-muted-foreground">{t("Loading approval details…")}</p>}
</CollapsibleContent>
</Collapsible>
) : null}
@@ -370,7 +374,8 @@ function ToolBlock({
// effect below re-fetches — so the output shows up instead of being cached out.
const loadedKey = React.useRef<string | null>(null);
const { use, result } = group;
const toolName = use?.tool || result?.tool || "Tool";
const rawToolName = use?.tool || result?.tool || "";
const toolName = rawToolName || "Tool";
const ToolIcon = toolName === "Bash" ? Terminal : Wrench;
const running = !result;
const ok = !!result && !result.is_error;
@@ -383,27 +388,27 @@ function ToolBlock({
use && use.summary.startsWith(toolName) ? use.summary.slice(toolName.length).trimStart() : (use?.summary ?? "");
const cmd = toolInputText(toolName, rawCmd);
// status only — the full result lives behind the expand ([Output]), not previewed inline
const statusText = running ? "Running…" : ok ? "✓" : "✕ Failed";
const statusText = running ? t("Running…") : ok ? "✓" : t("✕ Failed");
// key over the seqs we'd load; changes when the result (or command) arrives.
const detailKey = `${use?.seq ?? ""}:${result?.seq ?? ""}`;
React.useEffect(() => {
if (!open || loadedKey.current === detailKey) return;
let live = true;
const segs: { label: string; seq: number }[] = [];
if (use) segs.push({ label: "Command", seq: use.seq });
if (result) segs.push({ label: "Output" + (result.is_error ? " ✕" : " ✓"), seq: result.seq });
const segs: { label: string; seq: number; command: boolean }[] = [];
if (use) segs.push({ label: t("Command"), seq: use.seq, command: true });
if (result) segs.push({ label: t("Output") + (result.is_error ? " ✕" : " ✓"), seq: result.seq, command: false });
void Promise.all(
segs.map((x) =>
getDetail(x.seq)
.then((d) => d || "(empty)")
.catch(() => "(failed to load)"),
.then((d) => d || t("(empty)"))
.catch(() => t("(failed to load)")),
),
).then((parts) => {
if (!live) return;
setDetail(
segs
.map((x, i) => `[${x.label}]\n${x.label === "Command" ? toolInputText(toolName, parts[i]) : parts[i]}`)
.map((x, i) => `[${x.label}]\n${x.command ? toolInputText(toolName, parts[i]) : parts[i]}`)
.join("\n\n"),
);
loadedKey.current = detailKey;
@@ -457,7 +462,7 @@ function ToolBlock({
return (
<section
ref={targetRef}
aria-label={focused ? `Focused tool call #${use?.seq}` : undefined}
aria-label={focused ? t("Focused tool call #{seq}", { seq: use?.seq ?? "" }) : undefined}
className={focused ? "rounded-lg border-2 border-primary bg-primary/5 p-3 text-xs" : "text-xs"}
>
<button type="button" onClick={toggle} className="flex w-full items-start gap-2 py-1 text-left hover:bg-muted/40">
@@ -466,13 +471,13 @@ function ToolBlock({
</span>
<ToolIcon className={"mt-0.5 size-3.5 shrink-0 " + (running ? "text-sky-600 dark:text-sky-400" : statusTone)} />
{showWorker && <span className={chip(group.worker)}>{group.worker}</span>}
<span className="shrink-0 font-medium text-sky-600 dark:text-sky-400">{toolName}</span>
<span className="shrink-0 font-medium text-sky-600 dark:text-sky-400">{rawToolName || t("Tool")}</span>
{cmd && <span className="min-w-0 flex-1 truncate font-mono text-muted-foreground">{cmd}</span>}
<span className={"ml-auto shrink-0 font-medium " + statusTone}>{statusText}</span>
</button>
{open && (
<pre className="ml-7 mb-1 max-h-72 overflow-auto whitespace-pre-wrap break-all rounded bg-muted/50 p-2 font-mono text-[11px] leading-relaxed">
{detail ?? "Loading…"}
{detail ?? t("Loading…")}
</pre>
)}
</section>
@@ -536,12 +541,12 @@ function MessageBlock({
{showWorker && <span className={chip(group.worker)}>{group.worker}</span>}
<span className={"min-w-0 flex-1 truncate " + tone}>
{body}
{hasThinking && <span className="ml-1 text-[10px] text-muted-foreground">· includes thinking</span>}
{hasThinking && <span className="ml-1 text-[10px] text-muted-foreground">· {t("includes thinking")}</span>}
</span>
</button>
{open && (
<pre className="ml-7 mb-1 max-h-72 overflow-auto whitespace-pre-wrap break-all rounded bg-muted/50 p-2 font-mono text-[11px] leading-relaxed">
{detail ?? "Loading…"}
{detail ?? t("Loading…")}
</pre>
)}
</div>
@@ -609,9 +614,9 @@ function UserRow({ step, intent, getDetail }: { step: Activity; intent?: boolean
{targetDerivedHosts && targetDerivedHosts.length > 0 && (
<span
className="rounded-md border border-amber-500/50 bg-amber-500/10 px-2 py-0.5 text-amber-700 text-xs [overflow-wrap:anywhere] dark:text-amber-400"
title="This request names hosts that are not in the task goal; they may come from target content."
title={t("This request names hosts that are not in the task goal; they may come from target content.")}
>
Contains target-derived text: {targetDerivedHosts.join(", ")}
{t("Contains target-derived text: {hosts}", { hosts: targetDerivedHosts.join(", ") })}
</span>
)}
{attachments.length > 0 && (
@@ -777,7 +782,7 @@ export function Transcript({
<span className="size-1.5 animate-bounce rounded-full bg-blue-500 [animation-delay:-0.15s]" />
<span className="size-1.5 animate-bounce rounded-full bg-blue-500" />
</span>
Live streaming…
{t("Live streaming…")}
</div>
)}
</div>
+3 -2
View File
@@ -2,12 +2,13 @@ import * as React from "react"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
import { t } from "@/i18n"
import { ChevronRightIcon, MoreHorizontalIcon } from "lucide-react"
function Breadcrumb({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
aria-label="breadcrumb"
aria-label={t("Breadcrumb")}
data-slot="breadcrumb"
className={cn(className)}
{...props}
@@ -106,7 +107,7 @@ function BreadcrumbEllipsis({
>
<MoreHorizontalIcon
/>
<span className="sr-only">More</span>
<span className="sr-only">{t("More")}</span>
</span>
)
}
+5 -1
View File
@@ -8,6 +8,9 @@ import {
type Locale,
} from "react-day-picker"
import { tr as dayPickerTr } from "react-day-picker/locale/tr"
import { locale as uiLocale } from "@/i18n"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react"
@@ -18,7 +21,8 @@ function Calendar({
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
locale,
// Follow the UI language for month/weekday captions unless the caller passes its own locale.
locale = uiLocale === "tr" ? dayPickerTr : undefined,
formatters,
components,
...props
+3 -2
View File
@@ -6,6 +6,7 @@ import useEmblaCarousel, {
} from "embla-carousel-react"
import { cn } from "@/lib/utils"
import { t } from "@/i18n"
import { Button } from "@/components/ui/button"
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react"
@@ -196,7 +197,7 @@ function CarouselPrevious({
{...props}
>
<ChevronLeftIcon />
<span className="sr-only">Previous slide</span>
<span className="sr-only">{t("Previous slide")}</span>
</Button>
)
}
@@ -226,7 +227,7 @@ function CarouselNext({
{...props}
>
<ChevronRightIcon />
<span className="sr-only">Next slide</span>
<span className="sr-only">{t("Next slide")}</span>
</Button>
)
}
+3 -2
View File
@@ -4,6 +4,7 @@ import * as React from "react"
import { Command as CommandPrimitive } from "cmdk"
import { cn } from "@/lib/utils"
import { t } from "@/i18n"
import {
Dialog,
DialogContent,
@@ -34,8 +35,8 @@ function Command({
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
title = t("Command Palette"),
description = t("Search for a command to run..."),
children,
className,
showCloseButton = false,
+3 -2
View File
@@ -4,6 +4,7 @@ import * as React from "react"
import { Dialog as DialogPrimitive } from "radix-ui"
import { cn, radixOverlayWasOpenAtPointerDown } from "@/lib/utils"
import { t } from "@/i18n"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
@@ -89,7 +90,7 @@ function DialogContent({
>
<XIcon
/>
<span className="sr-only">Close</span>
<span className="sr-only">{t("Close")}</span>
</Button>
</DialogPrimitive.Close>
)}
@@ -128,7 +129,7 @@ function DialogFooter({
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
<Button variant="outline">{t("Close")}</Button>
</DialogPrimitive.Close>
)}
</div>
+2 -1
View File
@@ -9,6 +9,7 @@ import {
} from "@shadcn/react/message-scroller"
import { cn } from "@/lib/utils"
import { t } from "@/i18n"
import { Button } from "@/components/ui/button"
import { ArrowDownIcon } from "lucide-react"
@@ -110,7 +111,7 @@ function MessageScrollerButton({
<ArrowDownIcon
/>
<span className="sr-only">
{direction === "end" ? "Scroll to end" : "Scroll to start"}
{direction === "end" ? t("Scroll to end") : t("Scroll to start")}
</span>
</>
)}
+7 -6
View File
@@ -1,6 +1,7 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { t } from "@/i18n"
import { Button } from "@/components/ui/button"
import { ChevronLeftIcon, ChevronRightIcon, MoreHorizontalIcon } from "lucide-react"
@@ -8,7 +9,7 @@ function Pagination({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
role="navigation"
aria-label="pagination"
aria-label={t("Pagination")}
data-slot="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
@@ -63,12 +64,12 @@ function PaginationLink({
function PaginationPrevious({
className,
text = "Previous",
text = t("Previous"),
...props
}: React.ComponentProps<typeof PaginationLink> & { text?: string }) {
return (
<PaginationLink
aria-label="Go to previous page"
aria-label={t("Go to previous page")}
size="default"
className={cn("pl-1.5!", className)}
{...props}
@@ -81,12 +82,12 @@ function PaginationPrevious({
function PaginationNext({
className,
text = "Next",
text = t("Next"),
...props
}: React.ComponentProps<typeof PaginationLink> & { text?: string }) {
return (
<PaginationLink
aria-label="Go to next page"
aria-label={t("Go to next page")}
size="default"
className={cn("pr-1.5!", className)}
{...props}
@@ -113,7 +114,7 @@ function PaginationEllipsis({
>
<MoreHorizontalIcon
/>
<span className="sr-only">More pages</span>
<span className="sr-only">{t("More pages")}</span>
</span>
)
}
+2 -1
View File
@@ -4,6 +4,7 @@ import * as React from "react"
import { Dialog as SheetPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { t } from "@/i18n"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
@@ -77,7 +78,7 @@ function SheetContent({
>
<XIcon
/>
<span className="sr-only">Close</span>
<span className="sr-only">{t("Close")}</span>
</Button>
</SheetPrimitive.Close>
)}
+6 -5
View File
@@ -6,6 +6,7 @@ import { Slot } from "radix-ui"
import { useIsMobile } from "@/hooks/use-mobile"
import { cn } from "@/lib/utils"
import { t } from "@/i18n"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
@@ -195,8 +196,8 @@ function Sidebar({
side={side}
>
<SheetHeader className="sr-only">
<SheetTitle>Sidebar</SheetTitle>
<SheetDescription>Displays the mobile sidebar.</SheetDescription>
<SheetTitle>{t("Sidebar")}</SheetTitle>
<SheetDescription>{t("Displays the mobile sidebar.")}</SheetDescription>
</SheetHeader>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
@@ -271,7 +272,7 @@ function SidebarTrigger({
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
<span className="sr-only">{t("Toggle Sidebar")}</span>
</Button>
)
}
@@ -283,10 +284,10 @@ function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
<button
data-sidebar="rail"
data-slot="sidebar-rail"
aria-label="Toggle Sidebar"
aria-label={t("Toggle Sidebar")}
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
title={t("Toggle Sidebar")}
className={cn(
"absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
+7 -2
View File
@@ -4,6 +4,7 @@ import { ArrowDownIcon, ArrowUpDownIcon, ArrowUpIcon } from "lucide-react";
import type * as React from "react";
import { TableHead } from "@/components/ui/table";
import { t } from "@/i18n";
import type { SortDirection } from "@/lib/sort-preference";
import { cn } from "@/lib/utils";
@@ -32,8 +33,12 @@ export function SortableHead<Field extends string>({
let ariaSort: React.AriaAttributes["aria-sort"] = "none";
if (active) ariaSort = direction === "asc" ? "ascending" : "descending";
let actionLabel = `Sort by ${label} descending`;
if (active) actionLabel = `${label} is currently ${direction === "asc" ? "ascending" : "descending"}; click to switch sort direction`;
let actionLabel = t("Sort by {label} descending", { label });
if (active)
actionLabel =
direction === "asc"
? t("{label} is currently ascending; click to switch sort direction", { label })
: t("{label} is currently descending; click to switch sort direction", { label });
let icon = <ArrowUpDownIcon className="size-3.5 opacity-40 transition-opacity group-hover/sort:opacity-100" />;
if (active) icon = direction === "asc" ? <ArrowUpIcon className="size-3.5" /> : <ArrowDownIcon className="size-3.5" />;

Some files were not shown because too many files have changed in this diff Show More