mirror of
https://github.com/open-webui/computer.git
synced 2026-11-22 21:50:43 -05:00
refac
This commit is contained in:
1 parent
332d783fdc
commit
12b16a4885
6 files changed
+164
-5
No files matched your search
@@ -4,6 +4,7 @@
|
||||
import CodeBlock from './CodeBlock.svelte';
|
||||
import MermaidBlock from './MermaidBlock.svelte';
|
||||
import InlineRenderer from './InlineRenderer.svelte';
|
||||
import KatexRenderer from './KatexRenderer.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
@@ -14,7 +15,9 @@
|
||||
</script>
|
||||
|
||||
{#each tokens as token}
|
||||
{#if token.type === 'heading'}
|
||||
{#if token.type === 'mathBlock'}
|
||||
<KatexRenderer text={token.text} displayMode />
|
||||
{:else if token.type === 'heading'}
|
||||
{@const h = token as Tokens.Heading}
|
||||
<svelte:element this={`h${h.depth}`}>
|
||||
<InlineRenderer items={h.tokens} />
|
||||
@@ -24,6 +27,8 @@
|
||||
{:else if token.type === 'code'}
|
||||
{#if (token as Tokens.Code).lang === 'mermaid'}
|
||||
<MermaidBlock code={(token as Tokens.Code).text} />
|
||||
{:else if (token as Tokens.Code).lang === 'math'}
|
||||
<KatexRenderer text={(token as Tokens.Code).text} displayMode />
|
||||
{:else}
|
||||
<CodeBlock language={(token as Tokens.Code).lang ?? ''} code={(token as Tokens.Code).text} />
|
||||
{/if}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import type { Token } from 'marked';
|
||||
import KatexRenderer from './KatexRenderer.svelte';
|
||||
import { openFileTab, setFileBrowserCwd, setActiveTab } from '$lib/stores';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
@@ -28,7 +29,9 @@
|
||||
</script>
|
||||
|
||||
{#each items as item}
|
||||
{#if item.type === 'text'}
|
||||
{#if item.type === 'mathInline'}
|
||||
<KatexRenderer text={item.text} displayMode={item.displayMode} />
|
||||
{:else if item.type === 'text'}
|
||||
{#if 'tokens' in item && item.tokens}
|
||||
<svelte:self items={item.tokens} />
|
||||
{:else}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import type { renderToString as katexRenderToString } from 'katex';
|
||||
import 'katex/dist/katex.min.css';
|
||||
|
||||
let { text, displayMode = false }: { text: string; displayMode?: boolean } = $props();
|
||||
let renderToString = $state<typeof katexRenderToString | null>(null);
|
||||
|
||||
onMount(async () => {
|
||||
renderToString = (await import('katex')).renderToString;
|
||||
});
|
||||
|
||||
let html = $derived.by(() => {
|
||||
try {
|
||||
return renderToString?.(text, { displayMode, throwOnError: false, trust: false });
|
||||
} catch {
|
||||
// Non-parse errors (e.g. excessive nesting) still need an escaped text fallback.
|
||||
return null;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<span class="not-prose" class:display-math={displayMode}>
|
||||
{#if html != null}{@html html}{:else}{text}{/if}
|
||||
</span>
|
||||
|
||||
<style>
|
||||
.display-math {
|
||||
display: block;
|
||||
overflow-x: auto;
|
||||
max-width: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -10,7 +10,7 @@
|
||||
* Styled entirely via Tailwind prose. No custom CSS.
|
||||
*/
|
||||
|
||||
import { Lexer } from 'marked';
|
||||
import { mathMarkdown } from './math';
|
||||
import BlockRenderer from './BlockRenderer.svelte';
|
||||
|
||||
interface Props {
|
||||
@@ -34,7 +34,7 @@
|
||||
if (!content) return [];
|
||||
try {
|
||||
const processed = preprocessWikilinks(content);
|
||||
return new Lexer().lex(processed);
|
||||
return mathMarkdown.lexer(processed);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Marked, type TokenizerExtension } from 'marked';
|
||||
|
||||
// Tokenize before Markdown can consume TeX backslashes, underscores or asterisks.
|
||||
// Code spans and ordinary code fences continue to use Marked's code tokens.
|
||||
function escaped(source: string, index: number): boolean {
|
||||
let slashes = 0;
|
||||
while (index > 0 && source[--index] === '\\') slashes++;
|
||||
return slashes % 2 === 1;
|
||||
}
|
||||
|
||||
function mathToken(source: string, block: boolean) {
|
||||
const pairs = block
|
||||
? [
|
||||
['$$', '$$'],
|
||||
['\\[', '\\]']
|
||||
]
|
||||
: [
|
||||
['$$', '$$'],
|
||||
['\\[', '\\]'],
|
||||
['\\(', '\\)'],
|
||||
['$', '$']
|
||||
];
|
||||
for (const [open, close] of pairs) {
|
||||
if (!source.startsWith(open)) continue;
|
||||
const singleDollar = open === '$';
|
||||
if (singleDollar && (source.startsWith('$$') || /\s/.test(source[1] ?? ''))) continue;
|
||||
let end = open.length;
|
||||
while ((end = source.indexOf(close, end)) !== -1) {
|
||||
if (escaped(source, end)) {
|
||||
end += close.length;
|
||||
continue;
|
||||
}
|
||||
if (singleDollar && (/\s/.test(source[end - 1]) || /[\d$]/.test(source[end + 1] ?? ''))) {
|
||||
return;
|
||||
}
|
||||
const text = source.slice(open.length, end);
|
||||
if (!text.trim() || (singleDollar && /[\n`]/.test(text))) return;
|
||||
const raw = source.slice(0, end + close.length);
|
||||
if (block && !/^[ \t]*(?:\n|$)/.test(source.slice(raw.length))) return;
|
||||
return {
|
||||
type: block ? 'mathBlock' : 'mathInline',
|
||||
raw,
|
||||
text,
|
||||
displayMode: open === '$$' || open === '\\['
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const blockMath: TokenizerExtension = {
|
||||
name: 'mathBlock',
|
||||
level: 'block',
|
||||
start(source) {
|
||||
return source.match(/(?:^|\n)(?=\$\$|\\\[)/)?.index;
|
||||
},
|
||||
tokenizer(source) {
|
||||
return mathToken(source, true);
|
||||
}
|
||||
};
|
||||
|
||||
const inlineMath: TokenizerExtension = {
|
||||
name: 'mathInline',
|
||||
level: 'inline',
|
||||
start(source) {
|
||||
return source.match(/\$|\\[([]/)?.index;
|
||||
},
|
||||
tokenizer(source) {
|
||||
return mathToken(source, false);
|
||||
}
|
||||
};
|
||||
|
||||
export const mathMarkdown = new Marked({ extensions: [blockMath, inlineMath] });
|
||||
@@ -7,6 +7,7 @@ import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import socket
|
||||
from contextlib import suppress
|
||||
@@ -192,6 +193,7 @@ async def detect_profile(profile: dict[str, Any]) -> AgentDetection:
|
||||
"Python package claude-agent-sdk is not installed",
|
||||
models,
|
||||
)
|
||||
models = await _probe_claude_models(command, profile) or models
|
||||
return AgentDetection("ready", command, version, None, models)
|
||||
|
||||
if profile.get("agent") == "codex":
|
||||
@@ -325,6 +327,49 @@ def _claude_models_for_version(version: str | None) -> list[str]:
|
||||
return models
|
||||
|
||||
|
||||
async def _probe_claude_models(command: str, profile: dict[str, Any]) -> list[str] | None:
|
||||
async def probe() -> list[str]:
|
||||
from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient
|
||||
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
launch_args = shlex.split(str(profile.get("launch_args") or ""))
|
||||
options = ClaudeAgentOptions(
|
||||
cli_path=command,
|
||||
cwd=os.getcwd(),
|
||||
env=env,
|
||||
extra_args={arg: None for arg in launch_args},
|
||||
)
|
||||
client = ClaudeSDKClient(options)
|
||||
try:
|
||||
await client.connect()
|
||||
info = await client.get_server_info()
|
||||
finally:
|
||||
await client.disconnect()
|
||||
|
||||
data = info.get("models") if isinstance(info, dict) else None
|
||||
models: list[str] = []
|
||||
for item in data if isinstance(data, list) else []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
model = item.get("resolvedModel")
|
||||
if not isinstance(model, str) or not model.strip():
|
||||
model = item.get("value")
|
||||
if not isinstance(model, str) or not model.strip():
|
||||
continue
|
||||
model = model.strip()
|
||||
if model not in models:
|
||||
models.append(model)
|
||||
return models
|
||||
|
||||
try:
|
||||
# The SDK's AnyIO task group must connect and disconnect in the same task.
|
||||
return await asyncio.wait_for(probe(), timeout=5) or None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
async def _probe_codex_models(command: str, profile: dict[str, Any]) -> list[str] | None:
|
||||
from cptr.utils.agents.codex import CodexAppServer
|
||||
|
||||
@@ -698,7 +743,7 @@ async def get_available_agent_model_entries(app_state=None) -> list[dict[str, st
|
||||
entries.append(
|
||||
{
|
||||
"id": model_id,
|
||||
"name": model_id,
|
||||
"name": model if config["agent"] == "claude_code" else model_id,
|
||||
"provider": "agent",
|
||||
"connection_id": f"agent:{config['id']}",
|
||||
"agent_id": config["agent"],
|
||||
|
||||
Reference in new issue
Block a user