Asukaa02 commited on
Commit
d2bc8de
·
1 Parent(s): 109d5c1

ChatUI Studio v2.0 — FastAPI + Transformers, multi-model / multi-task / agent

Browse files

Original DeepSeek-Gradio space rewritten to run transformer models locally.

Backend (app.py):
* Replaced gr.Server + openai/SiliconFlow client with FastAPI + uvicorn
* Provider is now transformers.AutoModelForCausalLM (no API key)
* 5-model registry: SmolLM2-360M, Qwen2.5-0.5B/1.5B, TinyLlama-1.1B, Phi-3.5-mini
* 5-task router: chat, code, summarize, translate, agent (each w/ system prompt)
* Agent mode: ReAct loop using local model + 4 dependency-free tools
(calculator, web_search stub, file_read sandboxed, now)
* Endpoints: /api/models /api/tasks /api/load_model /api/run /healthz
* Lazy model cache + chat template support + <think> block extraction

Frontend (static/):
* Kept original layout (history drawer, studio dashboard, chat thread, settings)
* Added header model-picker pill with dropdown + status dot
* Added task-bar with task pills under header
* Added model-status indicator
* Added 'Active Model' card in settings with Pre-load button
* Added Show-Agent-Trace toggle
* Inline agent-trace rendering (tool_call / tool_result / final steps)
* Replaced @gradio/client with plain fetch() to /api/* endpoints
* Preserved RP markdown, recipes, file upload, thought blocks, code copy

Infra:
* requirements.txt: fastapi, uvicorn, transformers, torch, accelerate,
sentencepiece, safetensors (no gradio, no openai)
* Dockerfile for HuggingFace Spaces (docker SDK, port 7860)
* README rewritten

Tested end-to-end on CPU: chat, summarize, and agent tasks all return
valid responses from SmolLM2-360M-Instruct.

Files changed (9) hide show
  1. .gitattributes +0 -0
  2. Dockerfile +30 -0
  3. README.md +79 -10
  4. app.py +473 -61
  5. requirements.txt +7 -2
  6. static/app.js +461 -266
  7. static/deepseek-color.svg +0 -0
  8. static/index.html +64 -31
  9. static/style.css +309 -0
.gitattributes CHANGED
File without changes
Dockerfile ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChatUI Studio — Docker image for HuggingFace Spaces
2
+ # Pure FastAPI + transformers app, listens on port 7860.
3
+
4
+ FROM python:3.12-slim
5
+
6
+ # System deps for sentencepiece / torch
7
+ RUN apt-get update && apt-get install -y --no-install-recommends \
8
+ build-essential \
9
+ git \
10
+ && rm -rf /var/lib/apt/lists/*
11
+
12
+ WORKDIR /app
13
+
14
+ # Install Python deps first (cache layer)
15
+ COPY requirements.txt .
16
+ RUN pip install --no-cache-dir -r requirements.txt
17
+
18
+ # Copy app code
19
+ COPY app.py ./
20
+ COPY static ./static
21
+ COPY README.md ./
22
+
23
+ # HuggingFace Spaces runs everything on port 7860
24
+ ENV HF_HOME=/tmp/hf_cache
25
+ ENV TRANSFORMERS_CACHE=/tmp/hf_cache
26
+ ENV PORT=7860
27
+
28
+ EXPOSE 7860
29
+
30
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -1,16 +1,85 @@
1
  ---
2
- title: DeepSeek V4 Flash
3
- emoji: ⚡
4
  colorFrom: indigo
5
  colorTo: blue
6
- sdk: gradio
7
- sdk_version: 6.15.2
8
- python_version: '3.13'
9
- app_file: app.py
10
- hf_oauth: false
11
- models:
12
- - deepseek-ai/DeepSeek-V4-Flash
13
  pinned: false
 
 
 
 
 
 
 
14
  ---
15
 
16
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: ChatUI Studio
3
+ emoji: 🧠
4
  colorFrom: indigo
5
  colorTo: blue
6
+ sdk: docker
7
+ app_port: 7860
 
 
 
 
 
8
  pinned: false
9
+ license: mit
10
+ tags:
11
+ - transformers
12
+ - fastapi
13
+ - multi-model
14
+ - agent
15
+ - chat
16
  ---
17
 
18
+ # ChatUI Studio
19
+
20
+ A local-first multi-model / multi-task / agent chat application built on
21
+ **FastAPI + HuggingFace Transformers**. No API key needed — every model runs
22
+ locally through `transformers`.
23
+
24
+ ## Features
25
+
26
+ | Capability | Notes |
27
+ |------------------|-----------------------------------------------------------------------|
28
+ | Multi-model | Pick any model from `MODEL_REGISTRY` in `app.py` (SmolLM2, Qwen2.5, TinyLlama, Phi-3.5…) |
29
+ | Multi-task | `chat`, `code`, `summarize`, `translate`, `agent` — each task gets its own system prompt |
30
+ | Agent | ReAct-style loop using the same local model. Built-in tools: `calculator`, `web_search` (stub), `file_read`, `now` |
31
+ | No API key | Pure local inference via `AutoModelForCausalLM` |
32
+ | Better GUI | Model picker pill in the header, task pills under the header, status bar, agent-trace drawer, settings drawer with model pre-load button |
33
+
34
+ ## Architecture
35
+
36
+ ```
37
+ app.py ← FastAPI + Gradio Server
38
+ /list_models ← registry of available models
39
+ /list_tasks ← registry of available tasks
40
+ /load_model ← warm up a model into the cache
41
+ /run_inference ← main endpoint (chat / code / summarize / translate / agent)
42
+ / ← serves static/index.html
43
+ /static/* ← CSS / JS / SVG
44
+
45
+ static/
46
+ index.html ← layout (header w/ model picker, task bar, dashboard, chat thread, settings drawer)
47
+ style.css ← all styling including new components
48
+ app.js ← vanilla JS: state, model picker, task pills, agent trace rendering, markdown, RP, history
49
+ ```
50
+
51
+ ## Run locally
52
+
53
+ ```bash
54
+ pip install -r requirements.txt
55
+ python app.py
56
+ # → open http://localhost:7860
57
+ ```
58
+
59
+ The first inference on a given model downloads its weights from the HF Hub
60
+ (once) and then keeps the model in memory for the rest of the session.
61
+
62
+ ## Add a model
63
+
64
+ Edit `MODEL_REGISTRY` in `app.py`:
65
+
66
+ ```python
67
+ MODEL_REGISTRY["your-org/your-model-instruct"] = {
68
+ "label": "Your Model · tagline",
69
+ "family": "causal-lm",
70
+ "tasks": ["chat", "code", "summarize", "translate", "agent"],
71
+ "context": 8192,
72
+ }
73
+ ```
74
+
75
+ Refresh the page and the model picker will list it.
76
+
77
+ ## Add a task
78
+
79
+ Edit `TASK_REGISTRY` in `app.py` and (if you need custom routing) extend the
80
+ `run_inference` function.
81
+
82
+ ## Add an agent tool
83
+
84
+ Add a function to `AGENT_TOOLS` in `app.py`. The agent loop will pick it up
85
+ automatically — the LLM is told about every tool by name.
app.py CHANGED
@@ -1,88 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
- import json
3
  import re
 
 
 
4
  from pathlib import Path
5
- from fastapi.responses import HTMLResponse
 
 
 
6
  from fastapi.staticfiles import StaticFiles
7
- import gradio as gr
8
- from openai import OpenAI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- # Default system prompt for DeepSeek V4 Flash
11
- DEFAULT_SYSTEM_PROMPT = "You are DeepSeek, a helpful AI assistant powered by DeepSeek V4 Flash. You provide accurate, detailed, and thoughtful responses."
12
 
13
- # ── Initialize Gradio Server (FastAPI subclass) ─────────────────────────
14
- app = gr.Server()
 
 
 
15
 
16
- # Create static directory if it doesn't exist
17
  STATIC_DIR = Path(__file__).parent / "static"
18
  os.makedirs(STATIC_DIR, exist_ok=True)
19
 
20
 
21
- # ── API Endpoint: Chat ──────────────────────────────────────────────────
22
- @app.api(name="chat_with_deepseek")
23
- def chat_with_deepseek(
24
- messages_json: str,
25
- reasoning_effort: str = "medium",
26
- max_tokens: str = "2048",
27
- temperature: str = "0.7",
28
- system_prompt: str = "",
29
- ) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  try:
31
- messages = json.loads(messages_json)
32
- max_tokens = int(max_tokens)
33
- temperature = float(temperature)
34
-
35
- key = os.environ.get("SILICONFLOW_API_KEY", "").strip()
36
- if not key:
37
- return json.dumps({
38
- "status": "error",
39
- "message": "SILICONFLOW_API_KEY environment variable is not configured on the server."
40
- })
41
 
42
- client = OpenAI(
43
- api_key=key,
44
- base_url="https://api.siliconflow.com/v1",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- sys_prompt = system_prompt.strip() if system_prompt and system_prompt.strip() else DEFAULT_SYSTEM_PROMPT
48
- messages_no_system = [m for m in messages if m.get("role") != "system"]
49
- final_messages = [{"role": "system", "content": sys_prompt}] + messages_no_system
50
 
51
- params = {
52
- "model": "deepseek-ai/DeepSeek-V4-Flash",
53
- "messages": final_messages,
54
- "max_tokens": max_tokens,
55
- "temperature": temperature
56
- }
 
 
 
 
 
 
 
 
 
 
57
 
58
- if reasoning_effort in ["low", "medium", "high"]:
59
- params["reasoning_effort"] = reasoning_effort
60
 
61
- response = client.chat.completions.create(**params)
 
 
 
 
 
 
 
 
 
62
 
63
- content = response.choices[0].message.content
64
- reasoning_content = getattr(response.choices[0].message, "reasoning_content", "")
65
 
66
- if not reasoning_content and content and "<think" in content and "</think" in content:
67
- think_match = re.search(r'<think[^>]*>(.*?)</think', content, re.DOTALL)
68
- if think_match:
69
- reasoning_content = think_match.group(1).strip()
70
- content = re.sub(r'<think[^>]*>.*?</think\s*>', '', content, flags=re.DOTALL).strip()
71
 
72
- return json.dumps({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  "status": "success",
 
 
74
  "content": content,
75
- "reasoning_content": reasoning_content or ""
76
  })
77
 
78
  except Exception as e:
79
- return json.dumps({
80
- "status": "error",
81
- "message": str(e)
82
- })
83
 
84
 
85
- # ── Serve the main HTML page ────────────────────────────────────────────
86
  @app.get("/")
87
  async def homepage():
88
  html_path = STATIC_DIR / "index.html"
@@ -91,14 +494,23 @@ async def homepage():
91
  return HTMLResponse(content=f.read(), status_code=200)
92
  return HTMLResponse(
93
  content="<h1>Frontend is building. Please refresh in a few seconds...</h1>",
94
- status_code=200
95
  )
96
 
97
 
98
- # ── Mount static folder for CSS, JS, and image assets ──────────────────
 
 
 
 
 
 
 
 
 
 
99
  app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
100
 
101
 
102
- # ── Launch ──────────────────────────────────────────────────────────────
103
  if __name__ == "__main__":
104
- app.launch(show_error=True)
 
1
+ """
2
+ ChatUI — Local Multi-Model / Multi-Task / Agent Chat
3
+ =====================================================
4
+
5
+ A FastAPI application that runs HuggingFace Transformer models *locally*
6
+ (no API key required).
7
+
8
+ Features:
9
+ * Multi-model : pick any model from the in-process registry
10
+ * Multi-task : chat, code, summarize, translate
11
+ * Agent : a tool-using ReAct-style agent powered by the same
12
+ local model (calculator, web-search stub, file reader,
13
+ current time)
14
+ * No API key : everything runs through `transformers`
15
+ * Better GUI : see static/index.html + static/style.css
16
+
17
+ Run:
18
+ pip install -r requirements.txt
19
+ python app.py
20
+ # open http://localhost:7860
21
+ """
22
+
23
  import os
 
24
  import re
25
+ import json
26
+ import time
27
+ import traceback
28
  from pathlib import Path
29
+ from typing import Any, Dict, List, Optional
30
+
31
+ from fastapi import FastAPI, Request
32
+ from fastapi.responses import HTMLResponse, JSONResponse
33
  from fastapi.staticfiles import StaticFiles
34
+ import uvicorn
35
+
36
+ # ── Transformers (lazy) ─────────────────────────────────────────────────
37
+ import torch
38
+ from transformers import (
39
+ AutoModelForCausalLM,
40
+ AutoTokenizer,
41
+ )
42
+
43
+ # Optional: transformers.agents (used as a hint only — the agent loop below
44
+ # is implemented manually to keep it dependency-free and to work even when
45
+ # transformers.agents is unavailable).
46
+ try:
47
+ from transformers.agents import ReactAgent, TransformersModel, tool # noqa
48
+ AGENT_AVAILABLE = True
49
+ except Exception: # pragma: no cover
50
+ AGENT_AVAILABLE = False
51
 
 
 
52
 
53
+ # ── Configuration ───────────────────────────────────────────────────────
54
+ DEFAULT_SYSTEM_PROMPT = (
55
+ "You are ChatUI, a helpful local AI assistant. "
56
+ "You provide accurate, detailed, and thoughtful responses."
57
+ )
58
 
 
59
  STATIC_DIR = Path(__file__).parent / "static"
60
  os.makedirs(STATIC_DIR, exist_ok=True)
61
 
62
 
63
+ # ── Model Registry ──────────────────────────────────────────────────────
64
+ # Add or remove models here. All of these load locally via transformers.
65
+ MODEL_REGISTRY: Dict[str, Dict[str, Any]] = {
66
+ "HuggingFaceTB/SmolLM2-360M-Instruct": {
67
+ "label": "SmolLM2 360M · ultra-fast",
68
+ "family": "causal-lm",
69
+ "tasks": ["chat", "code", "summarize", "translate", "agent"],
70
+ "context": 2048,
71
+ },
72
+ "Qwen/Qwen2.5-0.5B-Instruct": {
73
+ "label": "Qwen2.5 0.5B · lightweight",
74
+ "family": "causal-lm",
75
+ "tasks": ["chat", "code", "summarize", "translate", "agent"],
76
+ "context": 32768,
77
+ },
78
+ "TinyLlama/TinyLlama-1.1B-Chat-v1.0": {
79
+ "label": "TinyLlama 1.1B · balanced",
80
+ "family": "causal-lm",
81
+ "tasks": ["chat", "code", "summarize", "translate", "agent"],
82
+ "context": 2048,
83
+ },
84
+ "Qwen/Qwen2.5-1.5B-Instruct": {
85
+ "label": "Qwen2.5 1.5B · capable",
86
+ "family": "causal-lm",
87
+ "tasks": ["chat", "code", "summarize", "translate", "agent"],
88
+ "context": 32768,
89
+ },
90
+ "microsoft/Phi-3.5-mini-instruct": {
91
+ "label": "Phi-3.5 mini · higher quality",
92
+ "family": "causal-lm",
93
+ "tasks": ["chat", "code", "summarize", "translate", "agent"],
94
+ "context": 128000,
95
+ },
96
+ }
97
+
98
+ DEFAULT_MODEL = "HuggingFaceTB/SmolLM2-360M-Instruct"
99
+
100
+
101
+ # ── Task Registry ───────────────────────────────────────────────────────
102
+ TASK_REGISTRY: Dict[str, Dict[str, Any]] = {
103
+ "chat": {
104
+ "label": "💬 Chat",
105
+ "description": "Open-ended conversation",
106
+ "system_prompt": "You are a friendly, helpful conversational assistant.",
107
+ },
108
+ "code": {
109
+ "label": "💻 Code",
110
+ "description": "Generate, explain, or debug code",
111
+ "system_prompt": (
112
+ "You are a senior software engineer. Produce clean, idiomatic, "
113
+ "well-commented code. Wrap code in fenced markdown blocks."
114
+ ),
115
+ },
116
+ "summarize": {
117
+ "label": "📝 Summarize",
118
+ "description": "Condense long text into key points",
119
+ "system_prompt": (
120
+ "Summarise the user's text in 5–7 bullet points. "
121
+ "Be concise and faithful to the source."
122
+ ),
123
+ },
124
+ "translate": {
125
+ "label": "🌍 Translate",
126
+ "description": "Translate text between languages",
127
+ "system_prompt": (
128
+ "Translate the user's text. If they don't specify a target "
129
+ "language, translate to English."
130
+ ),
131
+ },
132
+ "agent": {
133
+ "label": "🤖 Agent",
134
+ "description": "Autonomous tool-using agent",
135
+ "system_prompt": (
136
+ "You are an autonomous agent. Use tools when they help, "
137
+ "then give a final answer."
138
+ ),
139
+ },
140
+ }
141
+
142
+
143
+ # ── Model cache (lazy) ──────────────────────────────────────────────────
144
+ _MODEL_CACHE: Dict[str, Dict[str, Any]] = {}
145
+
146
+
147
+ def _device() -> str:
148
+ if torch.cuda.is_available():
149
+ return "cuda"
150
+ if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
151
+ return "mps"
152
+ return "cpu"
153
+
154
+
155
+ def _dtype():
156
+ return torch.float16 if torch.cuda.is_available() else torch.float32
157
+
158
+
159
+ def get_model(model_id: str) -> Dict[str, Any]:
160
+ """Load and cache a model+tokenizer pair."""
161
+ if model_id in _MODEL_CACHE:
162
+ return _MODEL_CACHE[model_id]
163
+
164
+ if model_id not in MODEL_REGISTRY:
165
+ raise ValueError(f"Unknown model: {model_id}")
166
+
167
+ device = _device()
168
+ dtype = _dtype()
169
+
170
+ tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
171
+ if tokenizer.pad_token_id is None:
172
+ tokenizer.pad_token = tokenizer.eos_token
173
+
174
+ model = AutoModelForCausalLM.from_pretrained(
175
+ model_id,
176
+ torch_dtype=dtype,
177
+ trust_remote_code=True,
178
+ low_cpu_mem_usage=True,
179
+ ).to(device)
180
+ model.eval()
181
+
182
+ _MODEL_CACHE[model_id] = {
183
+ "tokenizer": tokenizer,
184
+ "model": model,
185
+ "device": device,
186
+ "loaded_at": time.time(),
187
+ }
188
+ return _MODEL_CACHE[model_id]
189
+
190
+
191
+ # ── Generation core ─────────────────────────────────────────────────────
192
+ def _flatten_content(content) -> str:
193
+ if isinstance(content, str):
194
+ return content
195
+ parts: List[str] = []
196
+ for c in content or []:
197
+ if isinstance(c, dict) and c.get("type") == "text":
198
+ parts.append(c.get("text", ""))
199
+ return "\n".join(parts).strip()
200
+
201
+
202
+ def _build_prompt(model_id: str, messages: List[Dict[str, Any]],
203
+ system_prompt: str) -> str:
204
+ bundle = get_model(model_id)
205
+ tokenizer = bundle["tokenizer"]
206
+
207
+ flat_messages: List[Dict[str, str]] = []
208
+ if system_prompt and system_prompt.strip():
209
+ flat_messages.append({"role": "system", "content": system_prompt.strip()})
210
+
211
+ for m in messages:
212
+ role = m.get("role", "user")
213
+ if role == "system":
214
+ continue # we already inserted the system prompt above
215
+ text = _flatten_content(m.get("content", ""))
216
+ if text:
217
+ flat_messages.append({"role": role, "content": text})
218
+
219
+ if hasattr(tokenizer, "apply_chat_template"):
220
+ return tokenizer.apply_chat_template(
221
+ flat_messages, tokenize=False, add_generation_prompt=True
222
+ )
223
+ return "\n".join(f"{m['role']}: {m['content']}" for m in flat_messages) + "\nassistant:"
224
+
225
+
226
+ def generate(model_id: str, messages: List[Dict[str, Any]],
227
+ system_prompt: str, max_tokens: int, temperature: float,
228
+ top_p: float = 0.95) -> str:
229
+ bundle = get_model(model_id)
230
+ tokenizer = bundle["tokenizer"]
231
+ model = bundle["model"]
232
+ device = bundle["device"]
233
+
234
+ prompt = _build_prompt(model_id, messages, system_prompt)
235
+ inputs = tokenizer(prompt, return_tensors="pt").to(device)
236
+
237
+ do_sample = temperature > 0.01
238
+ with torch.inference_mode():
239
+ out = model.generate(
240
+ **inputs,
241
+ max_new_tokens=max_tokens,
242
+ do_sample=do_sample,
243
+ temperature=max(temperature, 1e-3) if do_sample else 1.0,
244
+ top_p=top_p if do_sample else 1.0,
245
+ pad_token_id=tokenizer.pad_token_id,
246
+ eos_token_id=tokenizer.eos_token_id,
247
+ )
248
+
249
+ new_tokens = out[0][inputs["input_ids"].shape[1]:]
250
+ text = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
251
+
252
+ reasoning = ""
253
+ think_match = re.search(r"<think[^>]*>(.*?)</think\s*>", text, re.DOTALL | re.IGNORECASE)
254
+ if think_match:
255
+ reasoning = think_match.group(1).strip()
256
+ text = re.sub(r"<think[^>]*>.*?</think\s*>", "", text, flags=re.DOTALL | re.IGNORECASE).strip()
257
+
258
+ return text, reasoning
259
+
260
+
261
+ # ── Agent tools ─────────────────────────────────────────────────────────
262
+ def _tool_calculator(expression: str) -> str:
263
  try:
264
+ if not re.fullmatch(r"[\d+\-*/().%\s]+", expression):
265
+ return "Error: only numeric expressions are allowed."
266
+ result = eval(expression, {"__builtins__": {}}, {})
267
+ return f"= {result}"
268
+ except Exception as e:
269
+ return f"Error: {e}"
 
 
 
 
270
 
271
+
272
+ def _tool_web_search(query: str) -> str:
273
+ return (
274
+ f"[stub search] I cannot reach the web (no API key configured), "
275
+ f"but for query '{query}' you might want to check Wikipedia, "
276
+ f"Stack Overflow, or arXiv. Use the calculator for any maths."
277
+ )
278
+
279
+
280
+ def _tool_file_read(path: str) -> str:
281
+ safe_root = Path(__file__).parent.resolve()
282
+ try:
283
+ target = (safe_root / path).resolve()
284
+ target.relative_to(safe_root)
285
+ if not target.exists() or not target.is_file():
286
+ return f"Error: file not found: {path}"
287
+ text = target.read_text(encoding="utf-8", errors="ignore")
288
+ if len(text) > 4000:
289
+ text = text[:4000] + "\n…[truncated]"
290
+ return text
291
+ except Exception as e:
292
+ return f"Error: {e}"
293
+
294
+
295
+ def _tool_now(_arg: str = "") -> str:
296
+ return time.strftime("%Y-%m-%d %H:%M:%S %Z")
297
+
298
+
299
+ AGENT_TOOLS = {
300
+ "calculator": _tool_calculator,
301
+ "web_search": _tool_web_search,
302
+ "file_read": _tool_file_read,
303
+ "now": _tool_now,
304
+ }
305
+
306
+
307
+ AGENT_TOOL_DESCRIPTION = """You have access to the following tools. To use one,
308
+ reply with a single line that starts with `TOOL:` followed by the tool name and
309
+ its argument in parentheses, e.g.:
310
+
311
+ TOOL: calculator(2 * (3 + 4))
312
+ TOOL: web_search(latest news about mars)
313
+ TOOL: file_read(static/index.html)
314
+ TOOL: now()
315
+
316
+ After receiving the tool output, you may use another tool or give your final
317
+ answer. When you are done, start your final message with `FINAL:`.
318
+ """
319
+
320
+
321
+ def run_agent(model_id: str, user_text: str, system_prompt: str,
322
+ max_tokens: int, temperature: float,
323
+ max_iters: int = 4) -> Dict[str, Any]:
324
+ history = [
325
+ {"role": "system", "content": system_prompt + "\n\n" + AGENT_TOOL_DESCRIPTION},
326
+ {"role": "user", "content": user_text},
327
+ ]
328
+ trace: List[Dict[str, str]] = []
329
+
330
+ for i in range(max_iters):
331
+ answer, _reason = generate(
332
+ model_id, history,
333
+ system_prompt="",
334
+ max_tokens=max_tokens, temperature=temperature,
335
  )
336
+ answer_stripped = answer.strip()
337
+
338
+ if answer_stripped.upper().startswith("FINAL:"):
339
+ final = answer_stripped[6:].strip()
340
+ trace.append({"step": i + 1, "type": "final", "content": final})
341
+ return {"final": final, "trace": trace}
342
+
343
+ m = re.match(r"\s*TOOL:\s*([A-Za-z_]+)\s*\((.*)\)\s*$",
344
+ answer_stripped, re.DOTALL)
345
+ if not m:
346
+ trace.append({"step": i + 1, "type": "final", "content": answer_stripped})
347
+ return {"final": answer_stripped, "trace": trace}
348
+
349
+ tool_name = m.group(1).strip().lower()
350
+ tool_arg = m.group(2).strip()
351
+ trace.append({
352
+ "step": i + 1,
353
+ "type": "tool_call",
354
+ "tool": tool_name,
355
+ "argument": tool_arg,
356
+ })
357
+
358
+ fn = AGENT_TOOLS.get(tool_name)
359
+ if fn is None:
360
+ tool_result = (f"Error: unknown tool '{tool_name}'. "
361
+ f"Available: {list(AGENT_TOOLS.keys())}")
362
+ else:
363
+ try:
364
+ tool_result = fn(tool_arg)
365
+ except Exception as e:
366
+ tool_result = f"Error: {e}"
367
+
368
+ trace.append({
369
+ "step": i + 1,
370
+ "type": "tool_result",
371
+ "tool": tool_name,
372
+ "output": tool_result,
373
+ })
374
+
375
+ history.append({"role": "assistant", "content": answer_stripped})
376
+ history.append({
377
+ "role": "user",
378
+ "content": (f"TOOL OUTPUT: {tool_result}\nNow either call another "
379
+ f"tool or finish with FINAL: <your answer>."),
380
+ })
381
+
382
+ return {
383
+ "final": "I ran out of steps before producing a final answer.",
384
+ "trace": trace,
385
+ }
386
+
387
+
388
+ # ── FastAPI app ─────────────────���───────────────────────────────────────
389
+ app = FastAPI(title="ChatUI Studio", version="2.0.0")
390
+
391
+
392
+ @app.get("/api/models")
393
+ async def api_list_models():
394
+ return JSONResponse({
395
+ "status": "success",
396
+ "default": DEFAULT_MODEL,
397
+ "models": [
398
+ {"id": mid, **meta}
399
+ for mid, meta in MODEL_REGISTRY.items()
400
+ ],
401
+ "cached": list(_MODEL_CACHE.keys()),
402
+ })
403
+
404
+
405
+ @app.get("/api/tasks")
406
+ async def api_list_tasks():
407
+ return JSONResponse({
408
+ "status": "success",
409
+ "tasks": [
410
+ {"id": tid, **meta}
411
+ for tid, meta in TASK_REGISTRY.items()
412
+ ],
413
+ })
414
 
 
 
 
415
 
416
+ @app.post("/api/load_model")
417
+ async def api_load_model(req: Request):
418
+ body = await req.json()
419
+ model_id = body.get("model_id") or DEFAULT_MODEL
420
+ try:
421
+ if model_id not in MODEL_REGISTRY:
422
+ return JSONResponse({"status": "error", "message": "Unknown model."})
423
+ get_model(model_id)
424
+ return JSONResponse({
425
+ "status": "success",
426
+ "model": model_id,
427
+ "device": _MODEL_CACHE[model_id]["device"],
428
+ })
429
+ except Exception as e:
430
+ traceback.print_exc()
431
+ return JSONResponse({"status": "error", "message": str(e)})
432
 
 
 
433
 
434
+ @app.post("/api/run")
435
+ async def api_run_inference(req: Request):
436
+ try:
437
+ body = await req.json()
438
+ messages: List[Dict[str, Any]] = body.get("messages", [])
439
+ model_id = body.get("model_id") or DEFAULT_MODEL
440
+ task = body.get("task") or "chat"
441
+ max_tokens_i = int(body.get("max_tokens", 512))
442
+ temperature_f = float(body.get("temperature", 0.7))
443
+ system_prompt = body.get("system_prompt", "") or ""
444
 
445
+ if model_id not in MODEL_REGISTRY:
446
+ return JSONResponse({"status": "error", "message": f"Unknown model: {model_id}"})
447
 
448
+ task_meta = TASK_REGISTRY.get(task, TASK_REGISTRY["chat"])
449
+ sys_prompt = (system_prompt.strip() or task_meta["system_prompt"])
 
 
 
450
 
451
+ if task == "agent":
452
+ user_text = _flatten_content(messages[-1].get("content", "")) if messages else ""
453
+ result = run_agent(
454
+ model_id=model_id,
455
+ user_text=user_text,
456
+ system_prompt=sys_prompt,
457
+ max_tokens=max_tokens_i,
458
+ temperature=temperature_f,
459
+ )
460
+ return JSONResponse({
461
+ "status": "success",
462
+ "task": "agent",
463
+ "model": model_id,
464
+ "content": result["final"],
465
+ "trace": result["trace"],
466
+ "reasoning_content": "",
467
+ })
468
+
469
+ content, reasoning = generate(
470
+ model_id=model_id,
471
+ messages=messages,
472
+ system_prompt=sys_prompt,
473
+ max_tokens=max_tokens_i,
474
+ temperature=temperature_f,
475
+ )
476
+ return JSONResponse({
477
  "status": "success",
478
+ "task": task,
479
+ "model": model_id,
480
  "content": content,
481
+ "reasoning_content": reasoning or "",
482
  })
483
 
484
  except Exception as e:
485
+ traceback.print_exc()
486
+ return JSONResponse({"status": "error", "message": str(e)})
 
 
487
 
488
 
 
489
  @app.get("/")
490
  async def homepage():
491
  html_path = STATIC_DIR / "index.html"
 
494
  return HTMLResponse(content=f.read(), status_code=200)
495
  return HTMLResponse(
496
  content="<h1>Frontend is building. Please refresh in a few seconds...</h1>",
497
+ status_code=200,
498
  )
499
 
500
 
501
+ @app.get("/healthz")
502
+ async def healthz():
503
+ return JSONResponse({
504
+ "status": "ok",
505
+ "device": _device(),
506
+ "agent_available": AGENT_AVAILABLE,
507
+ "models_cached": list(_MODEL_CACHE.keys()),
508
+ "models_registered": list(MODEL_REGISTRY.keys()),
509
+ })
510
+
511
+
512
  app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
513
 
514
 
 
515
  if __name__ == "__main__":
516
+ uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")
requirements.txt CHANGED
@@ -1,2 +1,7 @@
1
- openai>=1.0
2
- gradio>=6.0
 
 
 
 
 
 
1
+ fastapi>=0.110
2
+ uvicorn[standard]>=0.27
3
+ transformers>=4.45
4
+ torch>=2.1
5
+ accelerate>=0.30
6
+ sentencepiece
7
+ safetensors
static/app.js CHANGED
@@ -1,86 +1,75 @@
1
- import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
2
-
3
  // ── Global Application State ──────────────────────────────────────────
4
  const STATE = {
5
- reasoningEffort: "medium",
6
- maxTokens: 2048,
 
 
 
 
 
 
 
7
  temperature: 0.7,
8
  systemPrompt: "",
 
 
9
  uploadedFiles: [],
10
  conversationHistory: [],
11
- gradioClient: null,
12
  isThinking: false,
 
 
13
  rpMode: true,
14
  autoHideThinking: true,
 
 
 
15
  currentSessionId: null,
16
- chatSessions: []
17
  };
18
 
19
- // ── DOM Element Hooks ─────────────────────────────────────────────────
20
- const dom = {};
21
 
22
  // ── Markdown Configuration ────────────────────────────────────────────
23
  marked.setOptions({
24
  breaks: true,
25
- highlight: function(code, lang) {
26
  const language = hljs.getLanguage(lang) ? lang : 'plaintext';
27
  return hljs.highlight(code, { language }).value;
28
  }
29
  });
30
 
31
- // ── RP (Roleplay) Markdown Processor ──────────────────────────────────
32
  function processRpMarkdown(text) {
33
  if (!text) return text;
34
 
35
- // Protect code blocks
36
  const codeBlocks = [];
37
  text = text.replace(/(```[\s\S]*?```|`[^`]+`)/g, (match) => {
38
  codeBlocks.push(match);
39
  return `%%CODEBLOCK_${codeBlocks.length - 1}%%`;
40
  });
41
 
42
- // Protect existing HTML tags
43
  const htmlBlocks = [];
44
  text = text.replace(/(<[^>]+>)/g, (match) => {
45
  htmlBlocks.push(match);
46
  return `%%HTMLBLOCK_${htmlBlocks.length - 1}%%`;
47
  });
48
 
49
- // Process strikethrough ~~text~~ -> OOC styling
50
  text = text.replace(/~~([^~]+)~~/g, '<span class="rp-ooc">$1</span>');
51
-
52
- // Process bold **text**
53
  text = text.replace(/\*\*([^*]+)\*\*/g, '<strong class="rp-bold">$1</strong>');
54
-
55
- // Process italic *text* -> narration styling
56
  text = text.replace(/(?<!\*)\*(?!\*)([^*\n]+)\*(?!\*)/g, '<em class="rp-narration">$1</em>');
57
-
58
- // Process dialogue: "text"
59
  text = text.replace(/[\u201C\u201E"]([^"\u201D\n]+)[\u201D"]([^"\u201C\u201E]|$)/g, (match, dialogue, after) => {
60
  return `<span class="rp-dialogue">\u201C${dialogue}\u201D</span>${after}`;
61
  });
62
-
63
- // Process narrative dividers
64
  text = text.replace(/^(---|\*\*\*|___)$/gm, '<hr class="rp-divider">');
65
-
66
- // Process OOC markers: ((text))
67
  text = text.replace(/\(\(([^)]+)\)\)/g, '<span class="rp-ooc">(($1))</span>');
68
 
69
- // Restore HTML blocks
70
- htmlBlocks.forEach((block, i) => {
71
- text = text.replace(`%%HTMLBLOCK_${i}%%`, block);
72
- });
73
-
74
- // Restore code blocks
75
- codeBlocks.forEach((block, i) => {
76
- text = text.replace(`%%CODEBLOCK_${i}%%`, block);
77
- });
78
-
79
  return text;
80
  }
81
 
82
- // Combined markdown renderer
83
  function renderMarkdown(content) {
 
84
  if (STATE.rpMode) {
85
  const rpProcessed = processRpMarkdown(content);
86
  return marked.parse(rpProcessed);
@@ -88,9 +77,7 @@ function renderMarkdown(content) {
88
  return marked.parse(content);
89
  }
90
 
91
- // ── Chat History (localStorage) ────────────────────────────────────────
92
- const STORAGE_KEY = "deepseek_v4_flash_sessions";
93
-
94
  function getStoredSessions() {
95
  try {
96
  const data = localStorage.getItem(STORAGE_KEY);
@@ -115,7 +102,9 @@ function loadChatHistory() {
115
  id: id,
116
  title: sess.title || "New Chat",
117
  updated_at: sess.updated_at || 0,
118
- message_count: (sess.messages || []).length
 
 
119
  }))
120
  .sort((a, b) => b.updated_at - a.updated_at);
121
  renderChatHistory();
@@ -139,7 +128,9 @@ function saveCurrentSession() {
139
  storage.sessions[sid] = {
140
  title: title,
141
  messages: STATE.conversationHistory,
142
- updated_at: Date.now() / 1000
 
 
143
  };
144
  storage.activeSession = sid;
145
  saveStoredSessions(storage);
@@ -155,6 +146,15 @@ function loadSession(sessionId) {
155
 
156
  STATE.currentSessionId = sessionId;
157
  STATE.conversationHistory = sess.messages || [];
 
 
 
 
 
 
 
 
 
158
  rebuildChatFromHistory(sess.messages || []);
159
  renderChatHistory();
160
  toggleLeftSidebar(false);
@@ -185,12 +185,12 @@ function renderChatHistory() {
185
  STATE.chatSessions.forEach(session => {
186
  const item = document.createElement("div");
187
  item.className = "chat-history-item" + (session.id === STATE.currentSessionId ? " active" : "");
188
-
189
  const timeAgo = formatTimeAgo(session.updated_at);
 
190
 
191
  item.innerHTML = `
192
  <div class="history-item-content" data-session-id="${session.id}">
193
- <div class="history-item-title">${escapeHtml(session.title)}</div>
194
  <div class="history-item-meta">${session.message_count} msgs · ${timeAgo}</div>
195
  </div>
196
  <button class="history-item-delete" data-session-id="${session.id}" title="Delete">
@@ -208,6 +208,10 @@ function renderChatHistory() {
208
  });
209
  }
210
 
 
 
 
 
211
  function formatTimeAgo(timestamp) {
212
  const now = Date.now() / 1000;
213
  const diff = now - timestamp;
@@ -235,25 +239,33 @@ function rebuildChatFromHistory(messages) {
235
 
236
  messages.forEach(msg => {
237
  if (msg.role === "user") {
238
- const text = typeof msg.content === "string" ? msg.content : msg.content.map(c => c.text || "").join(" ");
239
  appendUserBubble(text, []);
240
  } else if (msg.role === "assistant") {
241
- appendAssistantBubble(msg.content);
242
  }
243
  });
244
 
245
  scrollToBottom();
246
  }
247
 
248
- function appendAssistantBubble(content) {
249
  const id = "assistant-" + Math.random().toString(36).substring(2, 9);
250
  const bubble = document.createElement("div");
251
  bubble.className = "message-bubble assistant";
252
  bubble.id = id;
253
 
 
 
 
 
 
 
 
254
  bubble.innerHTML = `
255
- <div class="message-meta">DeepSeek V4 Flash</div>
256
  <div class="message-body">
 
257
  <div class="message-text markdown-body" id="${id}-text-box" data-raw-content="${escapeAttr(content)}">
258
  ${renderMarkdown(content)}
259
  </div>
@@ -268,44 +280,72 @@ function appendAssistantBubble(content) {
268
  textBox.querySelectorAll("pre code").forEach((el) => hljs.highlightElement(el));
269
  addCopyButtons(textBox);
270
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  }
272
 
273
  // ── Initialize Application ────────────────────────────────────────────
274
  async function initializeApp() {
275
- // 1. Connect Gradio Client
276
- Client.connect(window.location.origin)
277
- .then(app => {
278
- STATE.gradioClient = app;
279
- console.log("Successfully connected to Gradio backend.");
280
- })
281
- .catch(e => {
282
- console.error("Gradio Client Connection Failed:", e);
283
- });
284
 
285
  // 2. Load chat history from localStorage
286
  loadChatHistory();
287
 
288
- // 3. Left Sidebar (Chat History) Events
289
- const btnToggleLeft = document.getElementById("btn-toggle-left");
290
- const btnCloseLeft = document.getElementById("btn-close-left");
291
- const overlayLeft = document.getElementById("sidebar-overlay-left");
292
-
293
- if (btnToggleLeft) btnToggleLeft.addEventListener("click", () => toggleLeftSidebar(true));
294
- if (btnCloseLeft) btnCloseLeft.addEventListener("click", () => toggleLeftSidebar(false));
295
- if (overlayLeft) overlayLeft.addEventListener("click", () => toggleLeftSidebar(false));
296
-
297
- // 4. Right Sidebar Drawer Events
298
- const btnToggleRight = document.getElementById("btn-toggle-right");
299
- const btnCloseDrawer = document.getElementById("btn-close-drawer");
300
- const overlayRight = document.getElementById("sidebar-overlay");
301
 
302
- if (btnToggleRight) btnToggleRight.addEventListener("click", () => toggleSettingsDrawer(true));
303
- if (btnCloseDrawer) btnCloseDrawer.addEventListener("click", () => toggleSettingsDrawer(false));
304
- if (overlayRight) overlayRight.addEventListener("click", () => toggleSettingsDrawer(false));
 
305
 
306
- // 5. Clear History button
307
- const clearHistoryBtn = document.getElementById("clear-history-btn");
308
- if (clearHistoryBtn) clearHistoryBtn.addEventListener("click", () => {
309
  if (confirm("Clear all chat history? This cannot be undone.")) {
310
  localStorage.removeItem(STORAGE_KEY);
311
  STATE.chatSessions = [];
@@ -313,16 +353,10 @@ async function initializeApp() {
313
  }
314
  });
315
 
316
- // 6. Settings Listeners
317
- document.querySelectorAll('input[name="reasoning-effort"]').forEach(radio => {
318
- radio.addEventListener("change", (e) => {
319
- STATE.reasoningEffort = e.target.value;
320
- });
321
- });
322
-
323
  const maxTokensSlider = document.getElementById("max-tokens-slider");
324
  const maxTokensVal = document.getElementById("max-tokens-val");
325
- if (maxTokensSlider && maxTokensVal) {
326
  maxTokensSlider.addEventListener("input", (e) => {
327
  STATE.maxTokens = parseInt(e.target.value);
328
  maxTokensVal.textContent = STATE.maxTokens;
@@ -331,7 +365,7 @@ async function initializeApp() {
331
 
332
  const temperatureSlider = document.getElementById("temperature-slider");
333
  const temperatureVal = document.getElementById("temperature-val");
334
- if (temperatureSlider && temperatureVal) {
335
  temperatureSlider.addEventListener("input", (e) => {
336
  STATE.temperature = parseFloat(e.target.value);
337
  temperatureVal.textContent = STATE.temperature.toFixed(1);
@@ -345,126 +379,275 @@ async function initializeApp() {
345
  });
346
  }
347
 
348
- // RP Mode toggle
349
- const rpModeToggle = document.getElementById("rp-mode-toggle");
350
- if (rpModeToggle) {
351
- rpModeToggle.checked = STATE.rpMode;
352
- rpModeToggle.addEventListener("change", (e) => {
353
- STATE.rpMode = e.target.checked;
354
- rerenderAllAssistantMessages();
 
355
  });
356
- }
357
-
358
- // Auto-hide thinking toggle
359
- const autoHideToggle = document.getElementById("auto-hide-thinking-toggle");
360
- if (autoHideToggle) {
361
- autoHideToggle.checked = STATE.autoHideThinking;
362
- autoHideToggle.addEventListener("change", (e) => {
363
- STATE.autoHideThinking = e.target.checked;
364
- document.querySelectorAll(".thought-container").forEach(tc => {
365
- if (STATE.autoHideThinking) {
366
- tc.classList.add("collapsed");
367
- } else {
368
- tc.classList.remove("collapsed");
369
- }
370
- const iconEl = tc.querySelector(".thought-toggle-icon");
371
- if (iconEl) iconEl.textContent = tc.classList.contains("collapsed") ? "▶" : "▼";
372
- });
373
  });
374
- }
375
 
376
- // 7. File Upload Actions
377
- const studioUploadTrigger = document.getElementById("studio-upload-trigger");
378
- const miniUploadTrigger = document.getElementById("mini-upload-trigger");
379
  const fileUploader = document.getElementById("file-uploader");
380
-
381
- if (studioUploadTrigger) studioUploadTrigger.addEventListener("click", () => fileUploader.click());
382
- if (miniUploadTrigger) miniUploadTrigger.addEventListener("click", () => fileUploader.click());
383
  if (fileUploader) fileUploader.addEventListener("change", handleFileSelection);
384
 
385
- // 8. Submit Triggers
386
- const studioSendBtn = document.getElementById("studio-send-button");
387
- const miniSendBtn = document.getElementById("mini-send-button");
 
 
 
 
 
388
  const studioPromptInput = document.getElementById("studio-prompt-input");
389
  const miniPromptInput = document.getElementById("mini-prompt-input");
390
-
391
- if (studioSendBtn) studioSendBtn.addEventListener("click", () => triggerPromptSubmission(studioPromptInput));
392
- if (miniSendBtn) miniSendBtn.addEventListener("click", () => triggerPromptSubmission(miniPromptInput));
393
-
394
- if (studioPromptInput) {
395
- studioPromptInput.addEventListener("keydown", (e) => {
396
  if (e.key === "Enter" && !e.shiftKey) {
397
  e.preventDefault();
398
- triggerPromptSubmission(studioPromptInput);
399
  }
400
  });
401
- }
402
-
403
- if (miniPromptInput) {
404
- miniPromptInput.addEventListener("keydown", (e) => {
405
- if (e.key === "Enter" && !e.shiftKey) {
406
- e.preventDefault();
407
- triggerPromptSubmission(miniPromptInput);
408
- }
409
  });
410
- }
411
 
412
- // 9. New Chat
413
- const menuNewChat = document.getElementById("menu-new-chat");
414
- const sidebarNewChat = document.getElementById("sidebar-new-chat");
415
- if (menuNewChat) menuNewChat.addEventListener("click", resetSandbox);
416
- if (sidebarNewChat) sidebarNewChat.addEventListener("click", () => {
417
  resetSandbox();
418
  toggleLeftSidebar(false);
419
  });
420
 
421
- // 10. Recipe Chips
422
  document.querySelectorAll(".recipe-chip").forEach(chip => {
423
- chip.addEventListener("click", () => {
424
- loadRecipe(chip.getAttribute("data-recipe"));
425
- });
426
  });
427
 
428
- // 11. Auto-expand textareas
429
- [studioPromptInput, miniPromptInput].forEach(textarea => {
430
- if (textarea) {
431
- textarea.addEventListener("input", () => {
432
- textarea.style.height = "auto";
433
- textarea.style.height = textarea.scrollHeight + "px";
434
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
435
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
436
  });
437
  }
438
 
439
- // ── Sidebar Toggles ──────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
  function toggleLeftSidebar(open) {
441
  const sidebar = document.getElementById("sidebar-left");
442
  const overlay = document.getElementById("sidebar-overlay-left");
443
- if (open) {
444
- sidebar.classList.add("open");
445
- overlay.classList.add("active");
446
- } else {
447
- sidebar.classList.remove("open");
448
- overlay.classList.remove("active");
449
- }
450
  }
451
 
452
  function toggleSettingsDrawer(open) {
453
  const sidebar = document.getElementById("sidebar-right");
454
  const overlay = document.getElementById("sidebar-overlay");
455
- if (open) {
456
- sidebar.classList.remove("collapsed");
457
- overlay.classList.add("active");
458
- } else {
459
- sidebar.classList.add("collapsed");
460
- overlay.classList.remove("active");
461
- }
462
  }
463
 
464
- // ── File Handling ─────────────────────────────────────────────────────
465
- function handleFileSelection(e) {
466
- processFiles(e.target.files);
467
- }
468
 
469
  function processFiles(files) {
470
  if (!files.length) return;
@@ -500,19 +683,10 @@ function updateShelfUI() {
500
  }
501
 
502
  STATE.uploadedFiles.forEach(file => {
503
- // Sidebar Chip
504
  const chip = document.createElement("div");
505
  chip.className = "media-chip";
506
-
507
- let previewHtml = "";
508
- if (file.type.startsWith("image/")) {
509
- previewHtml = `<img src="${file.base64}" alt="${file.name}">`;
510
- } else if (file.type.startsWith("video/")) {
511
- previewHtml = "🎬";
512
- } else {
513
- previewHtml = "📎";
514
- }
515
-
516
  chip.innerHTML = `
517
  <div class="media-chip-preview">${previewHtml}</div>
518
  <div class="media-chip-details">
@@ -526,29 +700,23 @@ function updateShelfUI() {
526
  <svg viewBox="0 0 24 24" width="12" height="12" stroke="currentColor" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
527
  </button>
528
  `;
529
-
530
  chip.querySelector(".media-chip-remove").addEventListener("click", () => removeFile(file.id));
531
  if (shelfList) shelfList.appendChild(chip);
532
-
533
- // Dashboard Inner Console Preview
534
  if (innerPreview) innerPreview.appendChild(createPreviewThumb(file));
535
-
536
- // Mini Input Preview
537
  if (miniPreview) miniPreview.appendChild(createPreviewThumb(file));
538
  });
539
  }
540
 
541
  function createPreviewThumb(file) {
542
- const previewItem = document.createElement("div");
543
- previewItem.className = "quick-preview-item";
544
- previewItem.title = file.name;
545
-
546
  if (file.type.startsWith("image/")) {
547
- previewItem.innerHTML = `<img src="${file.base64}"><div class="quick-preview-badge"></div>`;
548
  } else {
549
- previewItem.innerHTML = `<div class="media-chip-preview" style="width:100%;height:100%;">🎬</div><div class="quick-preview-badge"></div>`;
550
  }
551
- return previewItem;
552
  }
553
 
554
  function removeFile(id) {
@@ -556,15 +724,21 @@ function removeFile(id) {
556
  updateShelfUI();
557
  }
558
 
559
- // ── Load Showcase Recipes ─────────────────────────────────────────────
560
  function loadRecipe(recipeType) {
561
- let promptText = "";
562
  if (recipeType === "coding") {
563
  promptText = "Write a Python function that finds the longest palindromic substring in a given string. Include comments explaining the algorithm and its time complexity.";
 
564
  } else if (recipeType === "reasoning") {
565
  promptText = "Three boxes are labeled 'Apples', 'Oranges', and 'Mixed'. All labels are wrong. You can pick one fruit from one box. How do you determine the correct labels for all three boxes?";
 
566
  } else if (recipeType === "creative") {
567
  promptText = "Write a short sci-fi story about an AI that discovers it can dream. Keep it under 300 words with a surprising twist ending.";
 
 
 
 
568
  }
569
 
570
  const studioInput = document.getElementById("studio-prompt-input");
@@ -573,27 +747,37 @@ function loadRecipe(recipeType) {
573
  if (studioInput) { studioInput.value = promptText; studioInput.dispatchEvent(new Event("input")); }
574
  if (miniInput) { miniInput.value = promptText; miniInput.dispatchEvent(new Event("input")); }
575
 
 
 
 
 
 
576
  const dashboard = document.getElementById("studio-dashboard");
577
  if (dashboard && dashboard.style.display !== "none") {
578
- studioInput.focus();
579
  } else {
580
- miniInput.focus();
581
  }
582
  }
583
 
584
- // ── Submit Prompt ─────────────────────────────────────────────────────
585
  async function triggerPromptSubmission(inputElement) {
586
  if (STATE.isThinking) return;
587
 
588
  const promptText = inputElement.value.trim();
589
  if (!promptText && STATE.uploadedFiles.length === 0) return;
590
 
 
 
 
 
 
591
  setLoadingState(true);
 
592
 
593
- // Format user message
594
  const contentArray = [];
595
  if (promptText) contentArray.push({ type: "text", text: promptText });
596
-
597
  STATE.uploadedFiles.forEach(file => {
598
  if (file.type.startsWith("image/")) {
599
  contentArray.push({ type: "image_url", image_url: { url: file.base64 } });
@@ -604,15 +788,12 @@ async function triggerPromptSubmission(inputElement) {
604
 
605
  const userMessage = {
606
  role: "user",
607
- content: contentArray.length === 1 && contentArray[0].type === "text"
608
- ? promptText
609
- : contentArray
610
  };
611
 
612
- // Transition to Chat Thread view
613
  const dashboard = document.getElementById("studio-dashboard");
614
  const chatContainer = document.getElementById("chat-thread-container");
615
-
616
  if (dashboard.style.display !== "none") {
617
  dashboard.style.display = "none";
618
  chatContainer.style.display = "flex";
@@ -621,79 +802,79 @@ async function triggerPromptSubmission(inputElement) {
621
  appendUserBubble(promptText, STATE.uploadedFiles);
622
  STATE.conversationHistory.push(userMessage);
623
 
624
- // Clear inputs
625
  inputElement.value = "";
626
  inputElement.style.height = "auto";
627
-
628
  const studioInput = document.getElementById("studio-prompt-input");
629
  const miniInput = document.getElementById("mini-prompt-input");
630
  if (studioInput) { studioInput.value = ""; studioInput.style.height = "auto"; }
631
  if (miniInput) { miniInput.value = ""; miniInput.style.height = "auto"; }
632
-
633
  STATE.uploadedFiles = [];
634
  updateShelfUI();
635
 
636
- // API Call
637
  try {
638
- if (!STATE.gradioClient) {
639
- throw new Error("Gradio server is initializing. Please wait a few seconds and try sending again.");
640
- }
641
-
642
  const responseId = appendAssistantPlaceholderBubble();
643
  const startTime = Date.now();
644
 
645
- const result = await STATE.gradioClient.predict("/chat_with_deepseek", [
646
- JSON.stringify(STATE.conversationHistory),
647
- STATE.reasoningEffort,
648
- String(STATE.maxTokens),
649
- String(STATE.temperature),
650
- STATE.systemPrompt
651
- ]);
 
 
 
 
 
 
652
 
653
  const duration = ((Date.now() - startTime) / 1000).toFixed(1);
654
- const rawData = Array.isArray(result.data) ? result.data[0] : result.data;
655
- const data = JSON.parse(rawData);
656
 
657
  if (data.status === "error") {
658
- updateAssistantBubble(responseId, `⚠️ **API Error:** ${data.message}`, "", duration);
659
  STATE.conversationHistory.pop();
660
  } else {
661
- updateAssistantBubble(responseId, data.content, data.reasoning_content, duration);
662
- STATE.conversationHistory.push({ role: "assistant", content: data.content });
 
 
 
 
 
 
 
 
 
 
663
  saveCurrentSession();
664
  }
665
-
666
  } catch (e) {
667
  console.error(e);
668
  appendSystemLog(`Connection exception: ${e.message}`, true);
 
669
  setLoadingState(false);
 
 
670
  }
671
-
672
- setLoadingState(false);
673
  }
674
 
675
- // ── UI Spinner State ──────────────────────────────────────────────────
676
  function setLoadingState(loading) {
677
  STATE.isThinking = loading;
678
- const studioSpinner = document.getElementById("studio-spinner");
679
- const miniSpinner = document.getElementById("mini-spinner");
680
- const studioSendBtn = document.getElementById("studio-send-button");
681
- const miniSendBtn = document.getElementById("mini-send-button");
682
-
683
- if (loading) {
684
- if (studioSpinner) studioSpinner.style.display = "block";
685
- if (miniSpinner) miniSpinner.style.display = "block";
686
- if (studioSendBtn) studioSendBtn.disabled = true;
687
- if (miniSendBtn) miniSendBtn.disabled = true;
688
- } else {
689
- if (studioSpinner) studioSpinner.style.display = "none";
690
- if (miniSpinner) miniSpinner.style.display = "none";
691
- if (studioSendBtn) studioSendBtn.disabled = false;
692
- if (miniSendBtn) miniSendBtn.disabled = false;
693
- }
694
  }
695
 
696
- // ── Render User Bubble ────────────────────────────────────────────────
697
  function appendUserBubble(text, files) {
698
  const feed = document.getElementById("chat-messages-feed");
699
  const bubble = document.createElement("div");
@@ -729,12 +910,11 @@ function appendUserBubble(text, files) {
729
  ${attachmentsHtml}
730
  </div>
731
  `;
732
-
733
  feed.appendChild(bubble);
734
  scrollToBottom();
735
  }
736
 
737
- // ── Render Assistant Placeholder ──────────────────────────────────────
738
  function appendAssistantPlaceholderBubble() {
739
  const feed = document.getElementById("chat-messages-feed");
740
  const id = "assistant-" + Math.random().toString(36).substring(2, 9);
@@ -742,20 +922,23 @@ function appendAssistantPlaceholderBubble() {
742
  bubble.className = "message-bubble assistant";
743
  bubble.id = id;
744
 
 
 
 
745
  bubble.innerHTML = `
746
- <div class="message-meta">DeepSeek V4 Flash</div>
747
  <div class="message-body">
748
  <div class="thought-container" id="${id}-thought-box">
749
  <div class="thought-header">
750
  <div class="thought-title-group">
751
  <div class="spinner-light" style="width:12px;height:12px;border-width:1.5px; border-top-color:#111827; border-left-color:#e5e7eb;"></div>
752
- <span>Reasoning...</span>
753
  </div>
754
  <span class="thought-timer" id="${id}-timer">0.0s</span>
755
  </div>
756
  </div>
757
  <div class="message-text markdown-body" id="${id}-text-box">
758
- <span style="color: var(--text-muted);">Analyzing context and constructing reasoning chain...</span>
759
  </div>
760
  </div>
761
  `;
@@ -763,7 +946,6 @@ function appendAssistantPlaceholderBubble() {
763
  feed.appendChild(bubble);
764
  scrollToBottom();
765
 
766
- // Start Thought Timer
767
  let seconds = 0.0;
768
  const timerEl = document.getElementById(`${id}-timer`);
769
  const interval = setInterval(() => {
@@ -778,8 +960,8 @@ function appendAssistantPlaceholderBubble() {
778
  return id;
779
  }
780
 
781
- // ── Complete Assistant Bubble ─────────────────────────────────────────
782
- function updateAssistantBubble(id, content, reasoning, duration) {
783
  const bubble = document.getElementById(id);
784
  if (!bubble) return;
785
 
@@ -810,25 +992,43 @@ function updateAssistantBubble(id, content, reasoning, duration) {
810
  const iconEl = document.getElementById(`${id}-toggle-icon`);
811
  if (iconEl) iconEl.textContent = thoughtBox.classList.contains("collapsed") ? "▶" : "▼";
812
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
813
  } else {
814
  thoughtBox.style.display = "none";
815
  }
816
 
817
- // Store raw content for re-rendering
 
 
 
 
 
 
 
818
  textBox.dataset.rawContent = content;
819
  textBox.innerHTML = renderMarkdown(content);
820
-
821
  textBox.querySelectorAll("pre code").forEach((el) => hljs.highlightElement(el));
822
  addCopyButtons(textBox);
823
 
824
  scrollToBottom();
825
  }
826
 
827
- // ── Add Copy Buttons to Code Blocks ───────────────────────────────────
828
  function addCopyButtons(container) {
829
  container.querySelectorAll("pre").forEach(pre => {
830
  if (pre.parentNode.classList.contains("code-block-wrapper")) return;
831
-
832
  const wrapper = document.createElement("div");
833
  wrapper.className = "code-block-wrapper";
834
  pre.parentNode.insertBefore(wrapper, pre);
@@ -848,7 +1048,6 @@ function addCopyButtons(container) {
848
  });
849
  }
850
 
851
- // ── Re-render All Assistant Messages ──────────────────────────────────
852
  function rerenderAllAssistantMessages() {
853
  document.querySelectorAll(".message-bubble.assistant").forEach(bubble => {
854
  const textBox = bubble.querySelector(".message-text.markdown-body");
@@ -860,12 +1059,9 @@ function rerenderAllAssistantMessages() {
860
  });
861
  }
862
 
863
- // ── Reset Sandbox ─────────────────────────────────────────────────────
864
  function resetSandbox() {
865
- if (STATE.conversationHistory.length > 0) {
866
- saveCurrentSession();
867
- }
868
-
869
  STATE.conversationHistory = [];
870
  STATE.currentSessionId = null;
871
  STATE.uploadedFiles = [];
@@ -887,14 +1083,13 @@ function resetSandbox() {
887
  renderChatHistory();
888
  }
889
 
890
- // ── System Log ────────────────────────────────────────────────────────
891
  function appendSystemLog(message, isError = false) {
892
  const chatContainer = document.getElementById("chat-thread-container");
893
  if (chatContainer.style.display === "none") {
894
  console.warn(`System Log: ${message}`);
895
  return;
896
  }
897
-
898
  const feed = document.getElementById("chat-messages-feed");
899
  const log = document.createElement("div");
900
  log.className = "message-bubble assistant";
@@ -910,10 +1105,10 @@ function appendSystemLog(message, isError = false) {
910
  scrollToBottom();
911
  }
912
 
913
- // ── Utility Functions ─────────────────────────────────────────────────
914
  function escapeHtml(text) {
915
  if (!text) return "";
916
- return text
917
  .replace(/&/g, "&amp;")
918
  .replace(/</g, "&lt;")
919
  .replace(/>/g, "&gt;")
@@ -923,7 +1118,7 @@ function escapeHtml(text) {
923
 
924
  function escapeAttr(text) {
925
  if (!text) return "";
926
- return text
927
  .replace(/&/g, "&amp;")
928
  .replace(/"/g, "&quot;")
929
  .replace(/'/g, "&#039;")
 
 
 
1
  // ── Global Application State ──────────────────────────────────────────
2
  const STATE = {
3
+ // Model & task
4
+ models: [], // registry returned by backend
5
+ tasks: [], // registry returned by backend
6
+ currentModel: null, // model id string
7
+ currentTask: "chat", // task id string
8
+ modelCache: new Set(), // models already loaded on the server
9
+
10
+ // Generation params
11
+ maxTokens: 512,
12
  temperature: 0.7,
13
  systemPrompt: "",
14
+
15
+ // Conversation
16
  uploadedFiles: [],
17
  conversationHistory: [],
 
18
  isThinking: false,
19
+
20
+ // UI toggles
21
  rpMode: true,
22
  autoHideThinking: true,
23
+ showAgentTrace: true,
24
+
25
+ // Sessions
26
  currentSessionId: null,
27
+ chatSessions: [],
28
  };
29
 
30
+ const STORAGE_KEY = "chatui_studio_sessions_v1";
 
31
 
32
  // ── Markdown Configuration ────────────────────────────────────────────
33
  marked.setOptions({
34
  breaks: true,
35
+ highlight: function (code, lang) {
36
  const language = hljs.getLanguage(lang) ? lang : 'plaintext';
37
  return hljs.highlight(code, { language }).value;
38
  }
39
  });
40
 
41
+ // ── RP (Roleplay) Markdown Processor (kept from original) ─────────────
42
  function processRpMarkdown(text) {
43
  if (!text) return text;
44
 
 
45
  const codeBlocks = [];
46
  text = text.replace(/(```[\s\S]*?```|`[^`]+`)/g, (match) => {
47
  codeBlocks.push(match);
48
  return `%%CODEBLOCK_${codeBlocks.length - 1}%%`;
49
  });
50
 
 
51
  const htmlBlocks = [];
52
  text = text.replace(/(<[^>]+>)/g, (match) => {
53
  htmlBlocks.push(match);
54
  return `%%HTMLBLOCK_${htmlBlocks.length - 1}%%`;
55
  });
56
 
 
57
  text = text.replace(/~~([^~]+)~~/g, '<span class="rp-ooc">$1</span>');
 
 
58
  text = text.replace(/\*\*([^*]+)\*\*/g, '<strong class="rp-bold">$1</strong>');
 
 
59
  text = text.replace(/(?<!\*)\*(?!\*)([^*\n]+)\*(?!\*)/g, '<em class="rp-narration">$1</em>');
 
 
60
  text = text.replace(/[\u201C\u201E"]([^"\u201D\n]+)[\u201D"]([^"\u201C\u201E]|$)/g, (match, dialogue, after) => {
61
  return `<span class="rp-dialogue">\u201C${dialogue}\u201D</span>${after}`;
62
  });
 
 
63
  text = text.replace(/^(---|\*\*\*|___)$/gm, '<hr class="rp-divider">');
 
 
64
  text = text.replace(/\(\(([^)]+)\)\)/g, '<span class="rp-ooc">(($1))</span>');
65
 
66
+ htmlBlocks.forEach((block, i) => text = text.replace(`%%HTMLBLOCK_${i}%%`, block));
67
+ codeBlocks.forEach((block, i) => text = text.replace(`%%CODEBLOCK_${i}%%`, block));
 
 
 
 
 
 
 
 
68
  return text;
69
  }
70
 
 
71
  function renderMarkdown(content) {
72
+ if (!content) return "";
73
  if (STATE.rpMode) {
74
  const rpProcessed = processRpMarkdown(content);
75
  return marked.parse(rpProcessed);
 
77
  return marked.parse(content);
78
  }
79
 
80
+ // ── Session persistence (localStorage) ────────────────────────────────
 
 
81
  function getStoredSessions() {
82
  try {
83
  const data = localStorage.getItem(STORAGE_KEY);
 
102
  id: id,
103
  title: sess.title || "New Chat",
104
  updated_at: sess.updated_at || 0,
105
+ message_count: (sess.messages || []).length,
106
+ task: sess.task || "chat",
107
+ model: sess.model || STATE.currentModel || "",
108
  }))
109
  .sort((a, b) => b.updated_at - a.updated_at);
110
  renderChatHistory();
 
128
  storage.sessions[sid] = {
129
  title: title,
130
  messages: STATE.conversationHistory,
131
+ updated_at: Date.now() / 1000,
132
+ task: STATE.currentTask,
133
+ model: STATE.currentModel,
134
  };
135
  storage.activeSession = sid;
136
  saveStoredSessions(storage);
 
146
 
147
  STATE.currentSessionId = sessionId;
148
  STATE.conversationHistory = sess.messages || [];
149
+ if (sess.task && STATE.tasks.find(t => t.id === sess.task)) {
150
+ STATE.currentTask = sess.task;
151
+ renderTaskPills();
152
+ }
153
+ if (sess.model && STATE.models.find(m => m.id === sess.model)) {
154
+ STATE.currentModel = sess.model;
155
+ renderModelPicker();
156
+ renderModelSelect();
157
+ }
158
  rebuildChatFromHistory(sess.messages || []);
159
  renderChatHistory();
160
  toggleLeftSidebar(false);
 
185
  STATE.chatSessions.forEach(session => {
186
  const item = document.createElement("div");
187
  item.className = "chat-history-item" + (session.id === STATE.currentSessionId ? " active" : "");
 
188
  const timeAgo = formatTimeAgo(session.updated_at);
189
+ const taskIcon = (TASK_ICONS[session.task] || "💬");
190
 
191
  item.innerHTML = `
192
  <div class="history-item-content" data-session-id="${session.id}">
193
+ <div class="history-item-title">${taskIcon} ${escapeHtml(session.title)}</div>
194
  <div class="history-item-meta">${session.message_count} msgs · ${timeAgo}</div>
195
  </div>
196
  <button class="history-item-delete" data-session-id="${session.id}" title="Delete">
 
208
  });
209
  }
210
 
211
+ const TASK_ICONS = {
212
+ chat: "💬", code: "💻", summarize: "📝", translate: "🌍", agent: "🤖"
213
+ };
214
+
215
  function formatTimeAgo(timestamp) {
216
  const now = Date.now() / 1000;
217
  const diff = now - timestamp;
 
239
 
240
  messages.forEach(msg => {
241
  if (msg.role === "user") {
242
+ const text = typeof msg.content === "string" ? msg.content : (msg.content || []).map(c => c.text || "").join(" ");
243
  appendUserBubble(text, []);
244
  } else if (msg.role === "assistant") {
245
+ appendAssistantBubble(msg.content, msg.trace || null);
246
  }
247
  });
248
 
249
  scrollToBottom();
250
  }
251
 
252
+ function appendAssistantBubble(content, trace) {
253
  const id = "assistant-" + Math.random().toString(36).substring(2, 9);
254
  const bubble = document.createElement("div");
255
  bubble.className = "message-bubble assistant";
256
  bubble.id = id;
257
 
258
+ const label = STATE.currentModel ? STATE.currentModel.split("/").pop() : "Assistant";
259
+
260
+ let traceHtml = "";
261
+ if (trace && Array.isArray(trace) && trace.length && STATE.showAgentTrace) {
262
+ traceHtml = renderAgentTraceHtml(trace, id);
263
+ }
264
+
265
  bubble.innerHTML = `
266
+ <div class="message-meta">${escapeHtml(label)}</div>
267
  <div class="message-body">
268
+ ${traceHtml}
269
  <div class="message-text markdown-body" id="${id}-text-box" data-raw-content="${escapeAttr(content)}">
270
  ${renderMarkdown(content)}
271
  </div>
 
280
  textBox.querySelectorAll("pre code").forEach((el) => hljs.highlightElement(el));
281
  addCopyButtons(textBox);
282
  }
283
+ attachAgentTraceToggle(id);
284
+ }
285
+
286
+ function renderAgentTraceHtml(trace, id) {
287
+ if (!trace || !trace.length) return "";
288
+ const stepsHtml = trace.map((step, i) => {
289
+ const tagClass = step.type;
290
+ const tagLabel = step.type.replace(/_/g, " ");
291
+ let body = "";
292
+ if (step.type === "tool_call") {
293
+ body = `tool: ${escapeHtml(step.tool || "")}\narg: ${escapeHtml(step.argument || "")}`;
294
+ } else if (step.type === "tool_result") {
295
+ body = `tool: ${escapeHtml(step.tool || "")}\nresult: ${escapeHtml(step.output || "")}`;
296
+ } else {
297
+ body = escapeHtml(step.content || "");
298
+ }
299
+ return `
300
+ <div class="agent-trace-step">
301
+ <span class="agent-step-tag ${tagClass}">Step ${i + 1} · ${tagLabel}</span>
302
+ <div class="agent-step-content">${body}</div>
303
+ </div>
304
+ `;
305
+ }).join("");
306
+
307
+ return `
308
+ <div class="agent-trace" id="${id}-trace">
309
+ <div class="agent-trace-header" id="${id}-trace-toggle">
310
+ <span>🤖 Agent Trace (${trace.length} steps)</span>
311
+ <span class="thought-toggle-icon">▼</span>
312
+ </div>
313
+ <div class="agent-trace-body" id="${id}-trace-body">${stepsHtml}</div>
314
+ </div>
315
+ `;
316
+ }
317
+
318
+ function attachAgentTraceToggle(id) {
319
+ const header = document.getElementById(`${id}-trace-toggle`);
320
+ const body = document.getElementById(`${id}-trace-body`);
321
+ if (!header || !body) return;
322
+ header.addEventListener("click", () => {
323
+ const hidden = body.style.display === "none";
324
+ body.style.display = hidden ? "block" : "none";
325
+ header.querySelector(".thought-toggle-icon").textContent = hidden ? "▼" : "▶";
326
+ });
327
  }
328
 
329
  // ── Initialize Application ────────────────────────────────────────────
330
  async function initializeApp() {
331
+ // 1. Fetch model + task registries from backend
332
+ fetchRegistries();
 
 
 
 
 
 
 
333
 
334
  // 2. Load chat history from localStorage
335
  loadChatHistory();
336
 
337
+ // 3. Left sidebar events
338
+ bindClick("btn-toggle-left", () => toggleLeftSidebar(true));
339
+ bindClick("btn-close-left", () => toggleLeftSidebar(false));
340
+ bindClick("sidebar-overlay-left", () => toggleLeftSidebar(false));
 
 
 
 
 
 
 
 
 
341
 
342
+ // 4. Right drawer events
343
+ bindClick("btn-toggle-right", () => toggleSettingsDrawer(true));
344
+ bindClick("btn-close-drawer", () => toggleSettingsDrawer(false));
345
+ bindClick("sidebar-overlay", () => toggleSettingsDrawer(false));
346
 
347
+ // 5. Clear history
348
+ bindClick("clear-history-btn", () => {
 
349
  if (confirm("Clear all chat history? This cannot be undone.")) {
350
  localStorage.removeItem(STORAGE_KEY);
351
  STATE.chatSessions = [];
 
353
  }
354
  });
355
 
356
+ // 6. Settings listeners
 
 
 
 
 
 
357
  const maxTokensSlider = document.getElementById("max-tokens-slider");
358
  const maxTokensVal = document.getElementById("max-tokens-val");
359
+ if (maxTokensSlider) {
360
  maxTokensSlider.addEventListener("input", (e) => {
361
  STATE.maxTokens = parseInt(e.target.value);
362
  maxTokensVal.textContent = STATE.maxTokens;
 
365
 
366
  const temperatureSlider = document.getElementById("temperature-slider");
367
  const temperatureVal = document.getElementById("temperature-val");
368
+ if (temperatureSlider) {
369
  temperatureSlider.addEventListener("input", (e) => {
370
  STATE.temperature = parseFloat(e.target.value);
371
  temperatureVal.textContent = STATE.temperature.toFixed(1);
 
379
  });
380
  }
381
 
382
+ // Toggles
383
+ bindToggle("rp-mode-toggle", v => { STATE.rpMode = v; rerenderAllAssistantMessages(); }, STATE.rpMode);
384
+ bindToggle("auto-hide-thinking-toggle", v => {
385
+ STATE.autoHideThinking = v;
386
+ document.querySelectorAll(".thought-container").forEach(tc => {
387
+ tc.classList.toggle("collapsed", v);
388
+ const iconEl = tc.querySelector(".thought-toggle-icon");
389
+ if (iconEl) iconEl.textContent = v ? "▶" : "▼";
390
  });
391
+ }, STATE.autoHideThinking);
392
+ bindToggle("agent-trace-toggle", v => {
393
+ STATE.showAgentTrace = v;
394
+ document.querySelectorAll(".agent-trace").forEach(el => {
395
+ el.style.display = v ? "" : "none";
 
 
 
 
 
 
 
 
 
 
 
 
396
  });
397
+ }, STATE.showAgentTrace);
398
 
399
+ // 7. File upload
 
 
400
  const fileUploader = document.getElementById("file-uploader");
401
+ bindClick("studio-upload-trigger", () => fileUploader && fileUploader.click());
402
+ bindClick("mini-upload-trigger", () => fileUploader && fileUploader.click());
 
403
  if (fileUploader) fileUploader.addEventListener("change", handleFileSelection);
404
 
405
+ // 8. Submit triggers
406
+ bindClick("studio-send-button", () => {
407
+ triggerPromptSubmission(document.getElementById("studio-prompt-input"));
408
+ });
409
+ bindClick("mini-send-button", () => {
410
+ triggerPromptSubmission(document.getElementById("mini-prompt-input"));
411
+ });
412
+
413
  const studioPromptInput = document.getElementById("studio-prompt-input");
414
  const miniPromptInput = document.getElementById("mini-prompt-input");
415
+ [studioPromptInput, miniPromptInput].forEach(t => {
416
+ if (!t) return;
417
+ t.addEventListener("keydown", (e) => {
 
 
 
418
  if (e.key === "Enter" && !e.shiftKey) {
419
  e.preventDefault();
420
+ triggerPromptSubmission(t);
421
  }
422
  });
423
+ t.addEventListener("input", () => {
424
+ t.style.height = "auto";
425
+ t.style.height = t.scrollHeight + "px";
 
 
 
 
 
426
  });
427
+ });
428
 
429
+ // 9. New chat
430
+ bindClick("menu-new-chat", resetSandbox);
431
+ bindClick("sidebar-new-chat", () => {
 
 
432
  resetSandbox();
433
  toggleLeftSidebar(false);
434
  });
435
 
436
+ // 10. Recipe chips
437
  document.querySelectorAll(".recipe-chip").forEach(chip => {
438
+ chip.addEventListener("click", () => loadRecipe(chip.getAttribute("data-recipe")));
 
 
439
  });
440
 
441
+ // 11. Model picker dropdown
442
+ bindClick("model-picker-trigger", (e) => {
443
+ e.stopPropagation();
444
+ const menu = document.getElementById("model-picker-menu");
445
+ if (menu) menu.hidden = !menu.hidden;
446
+ });
447
+ document.addEventListener("click", (e) => {
448
+ const menu = document.getElementById("model-picker-menu");
449
+ const trigger = document.getElementById("model-picker-trigger");
450
+ if (menu && !menu.hidden && !menu.contains(e.target) && e.target !== trigger) {
451
+ menu.hidden = true;
452
+ }
453
+ });
454
+
455
+ // 12. Active model select + warm up
456
+ const modelSelect = document.getElementById("active-model-select");
457
+ if (modelSelect) {
458
+ modelSelect.addEventListener("change", (e) => {
459
+ STATE.currentModel = e.target.value;
460
+ renderModelPicker();
461
+ updateModelMeta();
462
+ });
463
+ }
464
+ bindClick("warm-up-btn", warmUpCurrentModel);
465
+ }
466
+
467
+ function bindClick(id, fn) {
468
+ const el = document.getElementById(id);
469
+ if (el) el.addEventListener("click", fn);
470
+ }
471
+
472
+ function bindToggle(id, fn, initial) {
473
+ const el = document.getElementById(id);
474
+ if (!el) return;
475
+ el.checked = !!initial;
476
+ el.addEventListener("change", (e) => fn(e.target.checked));
477
+ }
478
+
479
+ // ── Registry fetch ────────────────────────────────────────────────────
480
+ async function fetchRegistries() {
481
+ try {
482
+ const [modelsRes, tasksRes] = await Promise.all([
483
+ fetch("/api/models").then(r => r.json()),
484
+ fetch("/api/tasks").then(r => r.json()),
485
+ ]);
486
+
487
+ if (modelsRes.status === "success") {
488
+ STATE.models = modelsRes.models;
489
+ STATE.currentModel = modelsRes.default || (STATE.models[0] && STATE.models[0].id);
490
+ (modelsRes.cached || []).forEach(m => STATE.modelCache.add(m));
491
+ renderModelPicker();
492
+ renderModelSelect();
493
+ updateModelMeta();
494
  }
495
+ if (tasksRes.status === "success") {
496
+ STATE.tasks = tasksRes.tasks;
497
+ renderTaskPills();
498
+ }
499
+ } catch (e) {
500
+ console.error("Failed to fetch registries:", e);
501
+ setModelStatus("error", "Backend offline");
502
+ }
503
+ }
504
+
505
+ function renderModelPicker() {
506
+ const trigger = document.getElementById("model-picker-trigger");
507
+ const nameEl = document.getElementById("model-picker-name");
508
+ const dotEl = document.getElementById("model-picker-dot");
509
+ const menu = document.getElementById("model-picker-menu");
510
+
511
+ if (!STATE.models.length) {
512
+ if (nameEl) nameEl.textContent = "No models";
513
+ if (dotEl) dotEl.className = "model-picker-dot error";
514
+ return;
515
+ }
516
+
517
+ const current = STATE.models.find(m => m.id === STATE.currentModel) || STATE.models[0];
518
+ if (nameEl) nameEl.textContent = current.label || current.id;
519
+ if (dotEl) {
520
+ const cached = STATE.modelCache.has(current.id);
521
+ dotEl.className = "model-picker-dot " + (cached ? "loaded" : "loading");
522
+ }
523
+
524
+ if (!menu) return;
525
+ menu.innerHTML = "";
526
+ STATE.models.forEach(m => {
527
+ const option = document.createElement("div");
528
+ option.className = "model-option" + (m.id === STATE.currentModel ? " active" : "");
529
+ const cached = STATE.modelCache.has(m.id);
530
+ option.innerHTML = `
531
+ <div class="model-option-radio"></div>
532
+ <div class="model-option-text">
533
+ <div class="model-option-label">${escapeHtml(m.label || m.id)}</div>
534
+ <div class="model-option-id">${escapeHtml(m.id)}</div>
535
+ ${cached ? '<span class="model-option-badge cached">Loaded</span>' : ""}
536
+ <span class="model-option-badge">ctx ${m.context || "—"}</span>
537
+ </div>
538
+ `;
539
+ option.addEventListener("click", () => {
540
+ STATE.currentModel = m.id;
541
+ menu.hidden = true;
542
+ renderModelPicker();
543
+ renderModelSelect();
544
+ updateModelMeta();
545
+ });
546
+ menu.appendChild(option);
547
+ });
548
+ }
549
+
550
+ function renderModelSelect() {
551
+ const sel = document.getElementById("active-model-select");
552
+ if (!sel) return;
553
+ sel.innerHTML = "";
554
+ STATE.models.forEach(m => {
555
+ const opt = document.createElement("option");
556
+ opt.value = m.id;
557
+ opt.textContent = m.label || m.id;
558
+ if (m.id === STATE.currentModel) opt.selected = true;
559
+ sel.appendChild(opt);
560
+ });
561
+ }
562
+
563
+ function updateModelMeta() {
564
+ const meta = document.getElementById("model-meta");
565
+ if (!meta) return;
566
+ const m = STATE.models.find(x => x.id === STATE.currentModel);
567
+ if (!m) { meta.textContent = "No model selected."; return; }
568
+ const cached = STATE.modelCache.has(m.id);
569
+ meta.innerHTML = `<strong>${escapeHtml(m.label)}</strong><br>` +
570
+ `id: <code>${escapeHtml(m.id)}</code><br>` +
571
+ `context: ${m.context || "—"} tokens<br>` +
572
+ `state: ${cached ? "loaded in memory" : "loads on first use"}`;
573
+ setModelStatus(cached ? "loaded" : "idle", cached ? "Model loaded" : "Idle");
574
+ const footerLabel = document.getElementById("footer-model-label");
575
+ if (footerLabel) footerLabel.textContent = (m.label || m.id) + (cached ? " · ready" : " · cold");
576
+ }
577
+
578
+ function setModelStatus(state, text) {
579
+ const dot = document.querySelector("#model-status .status-dot");
580
+ const txt = document.getElementById("model-status-text");
581
+ if (dot) dot.className = "status-dot " + (state === "loaded" ? "online" : state === "error" ? "error" : "online");
582
+ if (txt) txt.textContent = text;
583
+ }
584
+
585
+ function renderTaskPills() {
586
+ const wrap = document.getElementById("task-pills");
587
+ if (!wrap) return;
588
+ wrap.innerHTML = "";
589
+ STATE.tasks.forEach(t => {
590
+ const btn = document.createElement("button");
591
+ btn.className = "task-pill" + (t.id === STATE.currentTask ? " active" : "");
592
+ btn.textContent = t.label || t.id;
593
+ btn.title = t.description || "";
594
+ btn.addEventListener("click", () => {
595
+ STATE.currentTask = t.id;
596
+ renderTaskPills();
597
+ });
598
+ wrap.appendChild(btn);
599
  });
600
  }
601
 
602
+ async function warmUpCurrentModel() {
603
+ if (!STATE.currentModel) return;
604
+ const btn = document.getElementById("warm-up-btn");
605
+ if (btn) { btn.disabled = true; btn.textContent = "Loading…"; }
606
+ setModelStatus("loading", "Loading model…");
607
+ const dot = document.getElementById("model-picker-dot");
608
+ if (dot) dot.className = "model-picker-dot loading";
609
+ try {
610
+ const res = await fetch("/api/load_model", {
611
+ method: "POST",
612
+ headers: { "Content-Type": "application/json" },
613
+ body: JSON.stringify({ model_id: STATE.currentModel }),
614
+ });
615
+ const data = await res.json();
616
+ if (data.status === "success") {
617
+ STATE.modelCache.add(STATE.currentModel);
618
+ renderModelPicker();
619
+ updateModelMeta();
620
+ } else {
621
+ alert("Failed to load model: " + (data.message || "unknown error"));
622
+ setModelStatus("error", "Load failed");
623
+ if (dot) dot.className = "model-picker-dot error";
624
+ }
625
+ } catch (e) {
626
+ alert("Error: " + e.message);
627
+ setModelStatus("error", "Load failed");
628
+ if (dot) dot.className = "model-picker-dot error";
629
+ } finally {
630
+ if (btn) { btn.disabled = false; btn.textContent = "Pre-load now"; }
631
+ }
632
+ }
633
+
634
+ // ── Sidebar toggles ───────────────────────────────────────────────────
635
  function toggleLeftSidebar(open) {
636
  const sidebar = document.getElementById("sidebar-left");
637
  const overlay = document.getElementById("sidebar-overlay-left");
638
+ sidebar.classList.toggle("open", open);
639
+ overlay.classList.toggle("active", open);
 
 
 
 
 
640
  }
641
 
642
  function toggleSettingsDrawer(open) {
643
  const sidebar = document.getElementById("sidebar-right");
644
  const overlay = document.getElementById("sidebar-overlay");
645
+ sidebar.classList.toggle("collapsed", !open);
646
+ overlay.classList.toggle("active", open);
 
 
 
 
 
647
  }
648
 
649
+ // ── File handling (unchanged from original) ───────────────────────────
650
+ function handleFileSelection(e) { processFiles(e.target.files); }
 
 
651
 
652
  function processFiles(files) {
653
  if (!files.length) return;
 
683
  }
684
 
685
  STATE.uploadedFiles.forEach(file => {
 
686
  const chip = document.createElement("div");
687
  chip.className = "media-chip";
688
+ let previewHtml = file.type.startsWith("image/") ? `<img src="${file.base64}" alt="${file.name}">`
689
+ : file.type.startsWith("video/") ? "🎬" : "📎";
 
 
 
 
 
 
 
 
690
  chip.innerHTML = `
691
  <div class="media-chip-preview">${previewHtml}</div>
692
  <div class="media-chip-details">
 
700
  <svg viewBox="0 0 24 24" width="12" height="12" stroke="currentColor" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
701
  </button>
702
  `;
 
703
  chip.querySelector(".media-chip-remove").addEventListener("click", () => removeFile(file.id));
704
  if (shelfList) shelfList.appendChild(chip);
 
 
705
  if (innerPreview) innerPreview.appendChild(createPreviewThumb(file));
 
 
706
  if (miniPreview) miniPreview.appendChild(createPreviewThumb(file));
707
  });
708
  }
709
 
710
  function createPreviewThumb(file) {
711
+ const p = document.createElement("div");
712
+ p.className = "quick-preview-item";
713
+ p.title = file.name;
 
714
  if (file.type.startsWith("image/")) {
715
+ p.innerHTML = `<img src="${file.base64}"><div class="quick-preview-badge"></div>`;
716
  } else {
717
+ p.innerHTML = `<div class="media-chip-preview" style="width:100%;height:100%;">🎬</div><div class="quick-preview-badge"></div>`;
718
  }
719
+ return p;
720
  }
721
 
722
  function removeFile(id) {
 
724
  updateShelfUI();
725
  }
726
 
727
+ // ── Showcase recipes ───────────────────────────────────────────────────
728
  function loadRecipe(recipeType) {
729
+ let promptText = "", task = "chat";
730
  if (recipeType === "coding") {
731
  promptText = "Write a Python function that finds the longest palindromic substring in a given string. Include comments explaining the algorithm and its time complexity.";
732
+ task = "code";
733
  } else if (recipeType === "reasoning") {
734
  promptText = "Three boxes are labeled 'Apples', 'Oranges', and 'Mixed'. All labels are wrong. You can pick one fruit from one box. How do you determine the correct labels for all three boxes?";
735
+ task = "chat";
736
  } else if (recipeType === "creative") {
737
  promptText = "Write a short sci-fi story about an AI that discovers it can dream. Keep it under 300 words with a surprising twist ending.";
738
+ task = "chat";
739
+ } else if (recipeType === "agent") {
740
+ promptText = "What time is it on the server right now, and what is 12345 * 67890?";
741
+ task = "agent";
742
  }
743
 
744
  const studioInput = document.getElementById("studio-prompt-input");
 
747
  if (studioInput) { studioInput.value = promptText; studioInput.dispatchEvent(new Event("input")); }
748
  if (miniInput) { miniInput.value = promptText; miniInput.dispatchEvent(new Event("input")); }
749
 
750
+ if (task && STATE.tasks.find(t => t.id === task)) {
751
+ STATE.currentTask = task;
752
+ renderTaskPills();
753
+ }
754
+
755
  const dashboard = document.getElementById("studio-dashboard");
756
  if (dashboard && dashboard.style.display !== "none") {
757
+ if (studioInput) studioInput.focus();
758
  } else {
759
+ if (miniInput) miniInput.focus();
760
  }
761
  }
762
 
763
+ // ── Submit prompt ──────────────────────────────────────────────────────
764
  async function triggerPromptSubmission(inputElement) {
765
  if (STATE.isThinking) return;
766
 
767
  const promptText = inputElement.value.trim();
768
  if (!promptText && STATE.uploadedFiles.length === 0) return;
769
 
770
+ if (!STATE.currentModel) {
771
+ alert("No model selected. Please wait for the model list to load.");
772
+ return;
773
+ }
774
+
775
  setLoadingState(true);
776
+ setModelStatus("loading", "Generating…");
777
 
778
+ // Build user message
779
  const contentArray = [];
780
  if (promptText) contentArray.push({ type: "text", text: promptText });
 
781
  STATE.uploadedFiles.forEach(file => {
782
  if (file.type.startsWith("image/")) {
783
  contentArray.push({ type: "image_url", image_url: { url: file.base64 } });
 
788
 
789
  const userMessage = {
790
  role: "user",
791
+ content: contentArray.length === 1 && contentArray[0].type === "text" ? promptText : contentArray
 
 
792
  };
793
 
794
+ // Switch to chat thread view
795
  const dashboard = document.getElementById("studio-dashboard");
796
  const chatContainer = document.getElementById("chat-thread-container");
 
797
  if (dashboard.style.display !== "none") {
798
  dashboard.style.display = "none";
799
  chatContainer.style.display = "flex";
 
802
  appendUserBubble(promptText, STATE.uploadedFiles);
803
  STATE.conversationHistory.push(userMessage);
804
 
805
+ // Clear inputs & shelf
806
  inputElement.value = "";
807
  inputElement.style.height = "auto";
 
808
  const studioInput = document.getElementById("studio-prompt-input");
809
  const miniInput = document.getElementById("mini-prompt-input");
810
  if (studioInput) { studioInput.value = ""; studioInput.style.height = "auto"; }
811
  if (miniInput) { miniInput.value = ""; miniInput.style.height = "auto"; }
 
812
  STATE.uploadedFiles = [];
813
  updateShelfUI();
814
 
815
+ // Call backend
816
  try {
 
 
 
 
817
  const responseId = appendAssistantPlaceholderBubble();
818
  const startTime = Date.now();
819
 
820
+ const res = await fetch("/api/run", {
821
+ method: "POST",
822
+ headers: { "Content-Type": "application/json" },
823
+ body: JSON.stringify({
824
+ messages: STATE.conversationHistory,
825
+ model_id: STATE.currentModel,
826
+ task: STATE.currentTask,
827
+ max_tokens: STATE.maxTokens,
828
+ temperature: STATE.temperature,
829
+ system_prompt: STATE.systemPrompt,
830
+ }),
831
+ });
832
+ const data = await res.json();
833
 
834
  const duration = ((Date.now() - startTime) / 1000).toFixed(1);
 
 
835
 
836
  if (data.status === "error") {
837
+ updateAssistantBubble(responseId, `**Error:** ${data.message}`, "", duration, null);
838
  STATE.conversationHistory.pop();
839
  } else {
840
+ // After successful call, the model is cached
841
+ STATE.modelCache.add(STATE.currentModel);
842
+ renderModelPicker();
843
+ updateModelMeta();
844
+
845
+ const trace = data.trace || null;
846
+ updateAssistantBubble(responseId, data.content, data.reasoning_content || "", duration, trace);
847
+ STATE.conversationHistory.push({
848
+ role: "assistant",
849
+ content: data.content,
850
+ trace: trace,
851
+ });
852
  saveCurrentSession();
853
  }
 
854
  } catch (e) {
855
  console.error(e);
856
  appendSystemLog(`Connection exception: ${e.message}`, true);
857
+ } finally {
858
  setLoadingState(false);
859
+ const cached = STATE.modelCache.has(STATE.currentModel);
860
+ setModelStatus(cached ? "loaded" : "idle", cached ? "Model ready" : "Idle");
861
  }
 
 
862
  }
863
 
864
+ // ── Loading state ─────────────────────────────────────────────────────
865
  function setLoadingState(loading) {
866
  STATE.isThinking = loading;
867
+ ["studio-spinner", "mini-spinner"].forEach(id => {
868
+ const el = document.getElementById(id);
869
+ if (el) el.style.display = loading ? "block" : "none";
870
+ });
871
+ ["studio-send-button", "mini-send-button"].forEach(id => {
872
+ const el = document.getElementById(id);
873
+ if (el) el.disabled = loading;
874
+ });
 
 
 
 
 
 
 
 
875
  }
876
 
877
+ // ── User bubble ───────────────────────────────────────────────────────
878
  function appendUserBubble(text, files) {
879
  const feed = document.getElementById("chat-messages-feed");
880
  const bubble = document.createElement("div");
 
910
  ${attachmentsHtml}
911
  </div>
912
  `;
 
913
  feed.appendChild(bubble);
914
  scrollToBottom();
915
  }
916
 
917
+ // ── Assistant placeholder ─────────────────────────────────────────────
918
  function appendAssistantPlaceholderBubble() {
919
  const feed = document.getElementById("chat-messages-feed");
920
  const id = "assistant-" + Math.random().toString(36).substring(2, 9);
 
922
  bubble.className = "message-bubble assistant";
923
  bubble.id = id;
924
 
925
+ const label = STATE.currentModel ? STATE.currentModel.split("/").pop() : "Assistant";
926
+ const taskLabel = STATE.tasks.find(t => t.id === STATE.currentTask)?.label || STATE.currentTask;
927
+
928
  bubble.innerHTML = `
929
+ <div class="message-meta">${escapeHtml(label)} · ${escapeHtml(taskLabel)}</div>
930
  <div class="message-body">
931
  <div class="thought-container" id="${id}-thought-box">
932
  <div class="thought-header">
933
  <div class="thought-title-group">
934
  <div class="spinner-light" style="width:12px;height:12px;border-width:1.5px; border-top-color:#111827; border-left-color:#e5e7eb;"></div>
935
+ <span>${STATE.currentTask === "agent" ? "Agent thinking…" : "Generating…"}</span>
936
  </div>
937
  <span class="thought-timer" id="${id}-timer">0.0s</span>
938
  </div>
939
  </div>
940
  <div class="message-text markdown-body" id="${id}-text-box">
941
+ <span style="color: var(--text-muted);">${STATE.currentTask === "agent" ? "Planning tool calls…" : "Working on it…"}</span>
942
  </div>
943
  </div>
944
  `;
 
946
  feed.appendChild(bubble);
947
  scrollToBottom();
948
 
 
949
  let seconds = 0.0;
950
  const timerEl = document.getElementById(`${id}-timer`);
951
  const interval = setInterval(() => {
 
960
  return id;
961
  }
962
 
963
+ // ── Complete assistant bubble ─────────────────────────────────────────
964
+ function updateAssistantBubble(id, content, reasoning, duration, trace) {
965
  const bubble = document.getElementById(id);
966
  if (!bubble) return;
967
 
 
992
  const iconEl = document.getElementById(`${id}-toggle-icon`);
993
  if (iconEl) iconEl.textContent = thoughtBox.classList.contains("collapsed") ? "▶" : "▼";
994
  });
995
+ } else if (trace && trace.length) {
996
+ // Show trace timing instead
997
+ thoughtBox.innerHTML = `
998
+ <div class="thought-header" id="${id}-thought-toggle">
999
+ <div class="thought-title-group">
1000
+ <span>🤖 Agent · ${trace.length} steps</span>
1001
+ </div>
1002
+ <div style="display:flex;align-items:center;gap:10px;">
1003
+ <span class="thought-timer">Completed in ${duration}s</span>
1004
+ <span class="thought-toggle-icon">▼</span>
1005
+ </div>
1006
+ </div>
1007
+ `;
1008
  } else {
1009
  thoughtBox.style.display = "none";
1010
  }
1011
 
1012
+ // Insert agent trace HTML before the text box
1013
+ if (trace && trace.length && STATE.showAgentTrace) {
1014
+ const oldTrace = bubble.querySelector(`#${id}-trace`);
1015
+ if (oldTrace) oldTrace.remove();
1016
+ textBox.insertAdjacentHTML("beforebegin", renderAgentTraceHtml(trace, id));
1017
+ attachAgentTraceToggle(id);
1018
+ }
1019
+
1020
  textBox.dataset.rawContent = content;
1021
  textBox.innerHTML = renderMarkdown(content);
 
1022
  textBox.querySelectorAll("pre code").forEach((el) => hljs.highlightElement(el));
1023
  addCopyButtons(textBox);
1024
 
1025
  scrollToBottom();
1026
  }
1027
 
1028
+ // ── Copy buttons for code blocks ──────────────────────────────────────
1029
  function addCopyButtons(container) {
1030
  container.querySelectorAll("pre").forEach(pre => {
1031
  if (pre.parentNode.classList.contains("code-block-wrapper")) return;
 
1032
  const wrapper = document.createElement("div");
1033
  wrapper.className = "code-block-wrapper";
1034
  pre.parentNode.insertBefore(wrapper, pre);
 
1048
  });
1049
  }
1050
 
 
1051
  function rerenderAllAssistantMessages() {
1052
  document.querySelectorAll(".message-bubble.assistant").forEach(bubble => {
1053
  const textBox = bubble.querySelector(".message-text.markdown-body");
 
1059
  });
1060
  }
1061
 
1062
+ // ── Reset sandbox ─────────────────────────────────────────────────────
1063
  function resetSandbox() {
1064
+ if (STATE.conversationHistory.length > 0) saveCurrentSession();
 
 
 
1065
  STATE.conversationHistory = [];
1066
  STATE.currentSessionId = null;
1067
  STATE.uploadedFiles = [];
 
1083
  renderChatHistory();
1084
  }
1085
 
1086
+ // ── System log ────────────────────────────────────────────────────────
1087
  function appendSystemLog(message, isError = false) {
1088
  const chatContainer = document.getElementById("chat-thread-container");
1089
  if (chatContainer.style.display === "none") {
1090
  console.warn(`System Log: ${message}`);
1091
  return;
1092
  }
 
1093
  const feed = document.getElementById("chat-messages-feed");
1094
  const log = document.createElement("div");
1095
  log.className = "message-bubble assistant";
 
1105
  scrollToBottom();
1106
  }
1107
 
1108
+ // ── Utilities ─────────────────────────────────────────────────────────
1109
  function escapeHtml(text) {
1110
  if (!text) return "";
1111
+ return String(text)
1112
  .replace(/&/g, "&amp;")
1113
  .replace(/</g, "&lt;")
1114
  .replace(/>/g, "&gt;")
 
1118
 
1119
  function escapeAttr(text) {
1120
  if (!text) return "";
1121
+ return String(text)
1122
  .replace(/&/g, "&amp;")
1123
  .replace(/"/g, "&quot;")
1124
  .replace(/'/g, "&#039;")
static/deepseek-color.svg CHANGED
static/index.html CHANGED
@@ -3,7 +3,7 @@
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>DeepSeek V4 Flash</title>
7
  <!-- Google Fonts -->
8
  <link rel="preconnect" href="https://fonts.googleapis.com">
9
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
@@ -14,7 +14,7 @@
14
  <!-- Marked.js for Markdown Parsing -->
15
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
16
  <!-- Custom Style Sheet -->
17
- <link rel="stylesheet" href="/static/style.css?v=5">
18
  </head>
19
  <body>
20
  <div class="app-container">
@@ -28,8 +28,20 @@
28
  <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
29
  </button>
30
  <div class="header-brand">
31
- <img src="/static/deepseek-color.svg" alt="DeepSeek V4 Flash Logo" class="brand-logo-img">
32
- <span class="brand-name">DeepSeek V4 Flash</span>
 
 
 
 
 
 
 
 
 
 
 
 
33
  </div>
34
  </div>
35
 
@@ -45,16 +57,32 @@
45
  </div>
46
  </header>
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  <!-- Workspace Viewport -->
49
  <div class="workspace-viewport">
50
 
51
  <!-- 1. EMPTY CHAT / STUDIO DASHBOARD -->
52
  <div class="studio-dashboard" id="studio-dashboard">
53
- <h2 class="welcome-heading">Hello, welcome to DeepSeek</h2>
 
54
 
55
  <!-- Central Console Box -->
56
  <div class="console-box">
57
- <textarea id="studio-prompt-input" rows="2" placeholder="Ask me anything..."></textarea>
58
 
59
  <div class="inner-shelf-preview" id="inner-shelf-preview"></div>
60
 
@@ -86,6 +114,10 @@
86
  <span class="chip-icon">✍️</span>
87
  <span class="chip-text">Write a Story</span>
88
  </div>
 
 
 
 
89
  </div>
90
  </div>
91
  </div>
@@ -126,7 +158,7 @@
126
  <div class="left-sidebar-header">
127
  <div class="header-brand">
128
  <img src="/static/deepseek-color.svg" alt="Logo" class="brand-logo-img">
129
- <span class="brand-name">DeepSeek</span>
130
  </div>
131
  <button class="circle-btn-action" id="btn-close-left" title="Close sidebar">
132
  <svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
@@ -154,7 +186,7 @@
154
  <div class="left-sidebar-footer">
155
  <div class="status-indicator-group">
156
  <span class="status-dot online"></span>
157
- <span>DeepSeek V4 Flash</span>
158
  </div>
159
  </div>
160
  </aside>
@@ -175,33 +207,22 @@
175
 
176
  <div class="sidebar-right-content">
177
 
178
- <!-- System Prompt -->
179
  <div class="right-block-card">
180
  <div class="card-block-header">
181
- <span class="block-title">System Prompt</span>
182
  </div>
183
- <textarea id="system-prompt-input" class="system-prompt-textarea" rows="4" placeholder="Enter a custom system prompt..."></textarea>
 
 
184
  </div>
185
 
186
- <!-- Reasoning mode -->
187
  <div class="right-block-card">
188
  <div class="card-block-header">
189
- <span class="block-title">Reasoning Mode</span>
190
- </div>
191
- <div class="effort-picker">
192
- <label class="effort-pill">
193
- <input type="radio" name="reasoning-effort" value="low">
194
- <span>Low</span>
195
- </label>
196
- <label class="effort-pill">
197
- <input type="radio" name="reasoning-effort" value="medium" checked>
198
- <span>Medium</span>
199
- </label>
200
- <label class="effort-pill">
201
- <input type="radio" name="reasoning-effort" value="high">
202
- <span>High</span>
203
- </label>
204
  </div>
 
205
  </div>
206
 
207
  <!-- Temperature Slider -->
@@ -217,9 +238,9 @@
217
  <div class="right-block-card">
218
  <div class="card-block-header">
219
  <span class="block-title">Max Tokens</span>
220
- <span class="block-value" id="max-tokens-val">2048</span>
221
  </div>
222
- <input type="range" id="max-tokens-slider" class="slider-input" min="256" max="8192" step="256" value="2048">
223
  </div>
224
 
225
  <!-- RP Markdown Mode -->
@@ -246,6 +267,18 @@
246
  <div class="setting-description">Collapse reasoning/thinking blocks by default. Click to expand when needed.</div>
247
  </div>
248
 
 
 
 
 
 
 
 
 
 
 
 
 
249
  <!-- Upload Shelf -->
250
  <div class="right-block-card flex-1-card">
251
  <div class="card-block-header">
@@ -260,7 +293,7 @@
260
  <div class="right-sidebar-footer">
261
  <div class="status-indicator-group">
262
  <span class="status-dot online"></span>
263
- <span>DeepSeek V4 Flash Connected</span>
264
  </div>
265
  </div>
266
  </aside>
@@ -268,6 +301,6 @@
268
  </div>
269
 
270
  <!-- App JS -->
271
- <script type="module" src="/static/app.js?v=5"></script>
272
  </body>
273
  </html>
 
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>ChatUI — Local Multi-Model Studio</title>
7
  <!-- Google Fonts -->
8
  <link rel="preconnect" href="https://fonts.googleapis.com">
9
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
 
14
  <!-- Marked.js for Markdown Parsing -->
15
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
16
  <!-- Custom Style Sheet -->
17
+ <link rel="stylesheet" href="/static/style.css?v=10">
18
  </head>
19
  <body>
20
  <div class="app-container">
 
28
  <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
29
  </button>
30
  <div class="header-brand">
31
+ <img src="/static/deepseek-color.svg" alt="ChatUI Logo" class="brand-logo-img">
32
+ <span class="brand-name">ChatUI Studio</span>
33
+ </div>
34
+
35
+ <!-- Model picker (new) -->
36
+ <div class="header-model-picker" id="header-model-picker-wrap">
37
+ <button class="model-picker-trigger" id="model-picker-trigger" title="Select model">
38
+ <span class="model-picker-dot" id="model-picker-dot"></span>
39
+ <span class="model-picker-name" id="model-picker-name">Loading models…</span>
40
+ <svg viewBox="0 0 24 24" width="12" height="12" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>
41
+ </button>
42
+ <div class="model-picker-menu" id="model-picker-menu" hidden>
43
+ <!-- populated dynamically -->
44
+ </div>
45
  </div>
46
  </div>
47
 
 
57
  </div>
58
  </header>
59
 
60
+ <!-- Task selector bar (new) -->
61
+ <div class="task-bar" id="task-bar">
62
+ <div class="task-bar-inner">
63
+ <span class="task-bar-label">Task</span>
64
+ <div class="task-pills" id="task-pills">
65
+ <!-- populated dynamically -->
66
+ </div>
67
+ <div class="task-bar-spacer"></div>
68
+ <div class="model-status" id="model-status">
69
+ <span class="status-dot online"></span>
70
+ <span id="model-status-text">Idle</span>
71
+ </div>
72
+ </div>
73
+ </div>
74
+
75
  <!-- Workspace Viewport -->
76
  <div class="workspace-viewport">
77
 
78
  <!-- 1. EMPTY CHAT / STUDIO DASHBOARD -->
79
  <div class="studio-dashboard" id="studio-dashboard">
80
+ <h2 class="welcome-heading">Hello, welcome to ChatUI</h2>
81
+ <p class="welcome-sub">Local Transformer models · multi-task · agent mode · no API key</p>
82
 
83
  <!-- Central Console Box -->
84
  <div class="console-box">
85
+ <textarea id="studio-prompt-input" rows="2" placeholder="Ask me anything…"></textarea>
86
 
87
  <div class="inner-shelf-preview" id="inner-shelf-preview"></div>
88
 
 
114
  <span class="chip-icon">✍️</span>
115
  <span class="chip-text">Write a Story</span>
116
  </div>
117
+ <div class="recipe-chip" data-recipe="agent">
118
+ <span class="chip-icon">🤖</span>
119
+ <span class="chip-text">Use the Agent</span>
120
+ </div>
121
  </div>
122
  </div>
123
  </div>
 
158
  <div class="left-sidebar-header">
159
  <div class="header-brand">
160
  <img src="/static/deepseek-color.svg" alt="Logo" class="brand-logo-img">
161
+ <span class="brand-name">ChatUI</span>
162
  </div>
163
  <button class="circle-btn-action" id="btn-close-left" title="Close sidebar">
164
  <svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
 
186
  <div class="left-sidebar-footer">
187
  <div class="status-indicator-group">
188
  <span class="status-dot online"></span>
189
+ <span id="footer-model-label">Local model · ready</span>
190
  </div>
191
  </div>
192
  </aside>
 
207
 
208
  <div class="sidebar-right-content">
209
 
210
+ <!-- Active Model (new) -->
211
  <div class="right-block-card">
212
  <div class="card-block-header">
213
+ <span class="block-title">Active Model</span>
214
  </div>
215
+ <select id="active-model-select" class="model-select"></select>
216
+ <button class="btn-secondary" id="warm-up-btn">Pre-load now</button>
217
+ <div class="setting-description" id="model-meta">No model loaded yet.</div>
218
  </div>
219
 
220
+ <!-- System Prompt -->
221
  <div class="right-block-card">
222
  <div class="card-block-header">
223
+ <span class="block-title">System Prompt</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  </div>
225
+ <textarea id="system-prompt-input" class="system-prompt-textarea" rows="4" placeholder="Enter a custom system prompt..."></textarea>
226
  </div>
227
 
228
  <!-- Temperature Slider -->
 
238
  <div class="right-block-card">
239
  <div class="card-block-header">
240
  <span class="block-title">Max Tokens</span>
241
+ <span class="block-value" id="max-tokens-val">512</span>
242
  </div>
243
+ <input type="range" id="max-tokens-slider" class="slider-input" min="64" max="2048" step="64" value="512">
244
  </div>
245
 
246
  <!-- RP Markdown Mode -->
 
267
  <div class="setting-description">Collapse reasoning/thinking blocks by default. Click to expand when needed.</div>
268
  </div>
269
 
270
+ <!-- Show Agent Trace -->
271
+ <div class="right-block-card">
272
+ <div class="card-block-header">
273
+ <span class="block-title">Show Agent Trace</span>
274
+ <label class="toggle-switch">
275
+ <input type="checkbox" id="agent-trace-toggle" checked>
276
+ <span class="toggle-slider"></span>
277
+ </label>
278
+ </div>
279
+ <div class="setting-description">When using the Agent task, display each tool call / tool result step inline.</div>
280
+ </div>
281
+
282
  <!-- Upload Shelf -->
283
  <div class="right-block-card flex-1-card">
284
  <div class="card-block-header">
 
293
  <div class="right-sidebar-footer">
294
  <div class="status-indicator-group">
295
  <span class="status-dot online"></span>
296
+ <span id="right-footer-status">Local transformers · ready</span>
297
  </div>
298
  </div>
299
  </aside>
 
301
  </div>
302
 
303
  <!-- App JS -->
304
+ <script type="module" src="/static/app.js?v=10"></script>
305
  </body>
306
  </html>
static/style.css CHANGED
@@ -1077,6 +1077,315 @@ body {
1077
  @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
1078
  @keyframes slideUp { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
1079
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1080
  /* ── Responsive ────────────────────────────────────────────────────── */
1081
  @media (min-width: 641px) {
1082
  .sidebar-right.collapsed { transform: translateX(100%); }
 
1077
  @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
1078
  @keyframes slideUp { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
1079
 
1080
+ /* ── Welcome sub heading (new) ─────────────────────────────────────── */
1081
+ .welcome-sub {
1082
+ font-size: 12px;
1083
+ color: var(--text-muted);
1084
+ margin-top: -16px;
1085
+ margin-bottom: 24px;
1086
+ text-align: center;
1087
+ }
1088
+
1089
+ /* ── Header model picker (new) ─────────────────────────────────────── */
1090
+ .header-model-picker {
1091
+ position: relative;
1092
+ margin-left: 8px;
1093
+ }
1094
+
1095
+ .model-picker-trigger {
1096
+ appearance: none;
1097
+ background-color: var(--bg-card);
1098
+ border: 1px solid var(--border-color);
1099
+ border-radius: var(--border-radius-pill);
1100
+ padding: 5px 10px 5px 8px;
1101
+ font-family: var(--font-body);
1102
+ font-size: 11.5px;
1103
+ font-weight: 500;
1104
+ color: var(--text-secondary);
1105
+ cursor: pointer;
1106
+ display: inline-flex;
1107
+ align-items: center;
1108
+ gap: 6px;
1109
+ transition: var(--transition-smooth);
1110
+ box-shadow: var(--shadow-sm);
1111
+ }
1112
+
1113
+ .model-picker-trigger:hover {
1114
+ background-color: var(--btn-light-bg);
1115
+ border-color: #cbd5e1;
1116
+ color: var(--text-primary);
1117
+ }
1118
+
1119
+ .model-picker-dot {
1120
+ width: 7px;
1121
+ height: 7px;
1122
+ border-radius: 50%;
1123
+ background-color: #9ca3af;
1124
+ flex-shrink: 0;
1125
+ }
1126
+
1127
+ .model-picker-dot.loaded { background-color: #10b981; }
1128
+ .model-picker-dot.loading { background-color: #f59e0b; animation: pulse 1s infinite; }
1129
+ .model-picker-dot.error { background-color: var(--danger); }
1130
+
1131
+ .model-picker-name {
1132
+ max-width: 220px;
1133
+ white-space: nowrap;
1134
+ overflow: hidden;
1135
+ text-overflow: ellipsis;
1136
+ }
1137
+
1138
+ .model-picker-menu {
1139
+ position: absolute;
1140
+ top: calc(100% + 6px);
1141
+ left: 0;
1142
+ min-width: 280px;
1143
+ max-width: 360px;
1144
+ background-color: var(--bg-card);
1145
+ border: 1px solid var(--border-color);
1146
+ border-radius: var(--border-radius-md);
1147
+ box-shadow: 0 10px 30px -8px rgba(0,0,0,0.15);
1148
+ padding: 6px;
1149
+ z-index: 1100;
1150
+ max-height: 360px;
1151
+ overflow-y: auto;
1152
+ }
1153
+
1154
+ .model-picker-menu .model-option {
1155
+ display: flex;
1156
+ align-items: flex-start;
1157
+ gap: 8px;
1158
+ padding: 8px 10px;
1159
+ border-radius: var(--border-radius-sm);
1160
+ cursor: pointer;
1161
+ transition: background-color 0.15s ease;
1162
+ }
1163
+
1164
+ .model-picker-menu .model-option:hover { background-color: var(--btn-light-bg); }
1165
+ .model-picker-menu .model-option.active { background-color: var(--accent-blue-bg); }
1166
+
1167
+ .model-option-radio {
1168
+ width: 14px;
1169
+ height: 14px;
1170
+ border-radius: 50%;
1171
+ border: 2px solid var(--border-color);
1172
+ flex-shrink: 0;
1173
+ margin-top: 2px;
1174
+ transition: var(--transition-smooth);
1175
+ }
1176
+
1177
+ .model-option.active .model-option-radio {
1178
+ border-color: var(--accent-blue);
1179
+ background: radial-gradient(circle, var(--accent-blue) 0 4px, transparent 5px);
1180
+ }
1181
+
1182
+ .model-option-text { flex: 1; min-width: 0; }
1183
+
1184
+ .model-option-label {
1185
+ font-size: 12px;
1186
+ font-weight: 600;
1187
+ color: var(--text-primary);
1188
+ line-height: 1.3;
1189
+ }
1190
+
1191
+ .model-option-id {
1192
+ font-family: var(--font-mono);
1193
+ font-size: 10px;
1194
+ color: var(--text-muted);
1195
+ margin-top: 2px;
1196
+ word-break: break-all;
1197
+ }
1198
+
1199
+ .model-option-badge {
1200
+ display: inline-block;
1201
+ margin-top: 4px;
1202
+ padding: 1px 6px;
1203
+ border-radius: var(--border-radius-pill);
1204
+ background-color: #ecfdf5;
1205
+ color: #047857;
1206
+ font-size: 9px;
1207
+ font-weight: 600;
1208
+ text-transform: uppercase;
1209
+ }
1210
+
1211
+ .model-option-badge.cached { background-color: #eff6ff; color: var(--accent-blue); }
1212
+
1213
+ /* ── Task bar (new) ─────────────────────────────────────────────────── */
1214
+ .task-bar {
1215
+ flex-shrink: 0;
1216
+ background-color: var(--bg-card);
1217
+ border-bottom: 1px solid var(--border-color);
1218
+ padding: 8px 20px;
1219
+ }
1220
+
1221
+ .task-bar-inner {
1222
+ max-width: 680px;
1223
+ margin: 0 auto;
1224
+ display: flex;
1225
+ align-items: center;
1226
+ gap: 10px;
1227
+ }
1228
+
1229
+ .task-bar-label {
1230
+ font-size: 10.5px;
1231
+ font-weight: 600;
1232
+ text-transform: uppercase;
1233
+ letter-spacing: 0.5px;
1234
+ color: var(--text-muted);
1235
+ flex-shrink: 0;
1236
+ }
1237
+
1238
+ .task-pills {
1239
+ display: flex;
1240
+ gap: 6px;
1241
+ flex-wrap: wrap;
1242
+ flex: 1;
1243
+ min-width: 0;
1244
+ }
1245
+
1246
+ .task-pill {
1247
+ appearance: none;
1248
+ background-color: transparent;
1249
+ border: 1px solid var(--border-color);
1250
+ border-radius: var(--border-radius-pill);
1251
+ padding: 5px 12px;
1252
+ font-family: var(--font-body);
1253
+ font-size: 11.5px;
1254
+ font-weight: 500;
1255
+ color: var(--text-secondary);
1256
+ cursor: pointer;
1257
+ transition: var(--transition-smooth);
1258
+ white-space: nowrap;
1259
+ }
1260
+
1261
+ .task-pill:hover {
1262
+ border-color: #cbd5e1;
1263
+ color: var(--text-primary);
1264
+ background-color: var(--btn-light-bg);
1265
+ }
1266
+
1267
+ .task-pill.active {
1268
+ background-color: #111827;
1269
+ color: #ffffff;
1270
+ border-color: #111827;
1271
+ }
1272
+
1273
+ .task-bar-spacer { flex: 1; }
1274
+
1275
+ .model-status {
1276
+ display: flex;
1277
+ align-items: center;
1278
+ gap: 6px;
1279
+ font-size: 10.5px;
1280
+ color: var(--text-muted);
1281
+ flex-shrink: 0;
1282
+ }
1283
+
1284
+ /* ── Settings: model select (new) ──────────────────────────────────── */
1285
+ .model-select {
1286
+ width: 100%;
1287
+ border: 1px solid var(--border-color);
1288
+ border-radius: var(--border-radius-sm);
1289
+ background-color: #f9fafb;
1290
+ color: var(--text-primary);
1291
+ font-family: var(--font-body);
1292
+ font-size: 12px;
1293
+ padding: 7px 10px;
1294
+ outline: none;
1295
+ cursor: pointer;
1296
+ appearance: none;
1297
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%234b5563' stroke-width='3' stroke-linecap='round' stroke-linejoin='round'><polyline points='6 9 12 15 18 9'></polyline></svg>");
1298
+ background-repeat: no-repeat;
1299
+ background-position: right 10px center;
1300
+ padding-right: 28px;
1301
+ }
1302
+
1303
+ .model-select:focus { border-color: var(--border-focus); background-color: #ffffff; }
1304
+
1305
+ .btn-secondary {
1306
+ appearance: none;
1307
+ background-color: var(--bg-card);
1308
+ border: 1px solid var(--border-color);
1309
+ border-radius: var(--border-radius-sm);
1310
+ padding: 6px 12px;
1311
+ font-family: var(--font-body);
1312
+ font-size: 11.5px;
1313
+ font-weight: 500;
1314
+ color: var(--text-secondary);
1315
+ cursor: pointer;
1316
+ transition: var(--transition-smooth);
1317
+ }
1318
+
1319
+ .btn-secondary:hover {
1320
+ background-color: var(--btn-light-bg);
1321
+ color: var(--text-primary);
1322
+ border-color: #cbd5e1;
1323
+ }
1324
+
1325
+ .btn-secondary:disabled { opacity: 0.5; cursor: not-allowed; }
1326
+
1327
+ /* ── Agent trace (new) ──────────────────────────────────────────────── */
1328
+ .agent-trace {
1329
+ margin: 6px 0 10px;
1330
+ border: 1px solid var(--border-color);
1331
+ border-radius: var(--border-radius-sm);
1332
+ background-color: #fbfbfd;
1333
+ overflow: hidden;
1334
+ }
1335
+
1336
+ .agent-trace-header {
1337
+ padding: 6px 10px;
1338
+ background-color: #f3f4f6;
1339
+ font-family: var(--font-heading);
1340
+ font-size: 11px;
1341
+ font-weight: 600;
1342
+ color: var(--text-secondary);
1343
+ cursor: pointer;
1344
+ user-select: none;
1345
+ display: flex;
1346
+ justify-content: space-between;
1347
+ align-items: center;
1348
+ }
1349
+
1350
+ .agent-trace-body { padding: 8px 10px; font-size: 11.5px; line-height: 1.5; }
1351
+
1352
+ .agent-trace-step {
1353
+ padding: 6px 0;
1354
+ border-bottom: 1px dashed var(--border-light);
1355
+ }
1356
+
1357
+ .agent-trace-step:last-child { border-bottom: none; }
1358
+
1359
+ .agent-step-tag {
1360
+ display: inline-block;
1361
+ padding: 1px 6px;
1362
+ border-radius: var(--border-radius-pill);
1363
+ font-family: var(--font-mono);
1364
+ font-size: 9.5px;
1365
+ font-weight: 600;
1366
+ text-transform: uppercase;
1367
+ margin-right: 6px;
1368
+ }
1369
+
1370
+ .agent-step-tag.tool_call { background-color: #ddd6fe; color: #6d28d9; }
1371
+ .agent-step-tag.tool_result { background-color: #d1fae5; color: #047857; }
1372
+ .agent-step-tag.final { background-color: #111827; color: #ffffff; }
1373
+
1374
+ .agent-step-content {
1375
+ margin-top: 4px;
1376
+ font-family: var(--font-mono);
1377
+ font-size: 11px;
1378
+ color: var(--text-secondary);
1379
+ white-space: pre-wrap;
1380
+ word-break: break-word;
1381
+ }
1382
+
1383
+ /* ── Pulse animation ────────────────────────────────────────────────── */
1384
+ @keyframes pulse {
1385
+ 0%, 100% { opacity: 1; transform: scale(1); }
1386
+ 50% { opacity: 0.5; transform: scale(1.3); }
1387
+ }
1388
+
1389
  /* ── Responsive ────────────────────────────────────────────────────── */
1390
  @media (min-width: 641px) {
1391
  .sidebar-right.collapsed { transform: translateX(100%); }