Build AI Studio 1.1 for macOS #1
+106
@@ -0,0 +1,106 @@
|
|||||||
|
# Programming custom MCP servers for AI Studio
|
||||||
|
|
||||||
|
## Connect an existing server
|
||||||
|
|
||||||
|
Open **Toolbox** beside the composer. Choose **Use LM Studio Config** to read
|
||||||
|
`~/.lmstudio/mcp.json`, or **Import mcp.json** to choose another file. Select
|
||||||
|
a named server. For stdio, review and confirm process startup. For a URL,
|
||||||
|
choose **Discover Tools**. The composer shows the connected toolset and its tool
|
||||||
|
count. The connection stays active when you close Toolbox. Use **Disconnect**
|
||||||
|
to end it. AI Studio remembers the configuration file and the selected
|
||||||
|
profile. The source file remains your editable configuration.
|
||||||
|
|
||||||
|
A local profile accepts `command`, an `args` array, `env`, and an optional
|
||||||
|
absolute `cwd`. Each argument stays a separate string. No shell interprets the
|
||||||
|
config. Named commands resolve against PATH and common macOS binary folders.
|
||||||
|
For an ordinary `python` or `python3` command with an absolute script path,
|
||||||
|
AI Studio also checks for a nearby `.venv` unless the profile sets PATH.
|
||||||
|
Use an explicit virtual-environment executable for reproducibility.
|
||||||
|
|
||||||
|
A remote profile takes a Streamable HTTP `url` and optional `headers`.
|
||||||
|
Use HTTPS for remote hosts. HTTP is supported on loopback. Keep bearer
|
||||||
|
credentials in your selected file or in the manual session-only field.
|
||||||
|
Copy examples with placeholders and supply your own values locally.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"my-local-knowledge": {
|
||||||
|
"command": "/absolute/project/.venv/bin/python",
|
||||||
|
"args": ["-u", "/absolute/project/server.py"],
|
||||||
|
"cwd": "/absolute/project",
|
||||||
|
"env": { "PYTHONUNBUFFERED": "1" }
|
||||||
|
},
|
||||||
|
"my-remote-tools": {
|
||||||
|
"url": "https://tools.example.com/mcp",
|
||||||
|
"headers": { "Authorization": "Bearer YOUR_TOKEN" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The attached archive's `src/knowledge_mcp.py` matches the installed
|
||||||
|
`local-knowledge` program. Select that profile to discover
|
||||||
|
`search_knowledge`, which accepts `query` and an optional `limit`. Run a query
|
||||||
|
in Toolbox, review the returned passages, then attach the result to chat.
|
||||||
|
The MCP index remains with its server. AI Studio's native **Knowledge Stacks**
|
||||||
|
can separately index files you import in Workspace.
|
||||||
|
|
||||||
|
## Implement a server
|
||||||
|
|
||||||
|
Use an official MCP SDK. For stdio, communicate in newline-delimited UTF-8
|
||||||
|
JSON-RPC on stdout and write logs on stderr. Support initialize, the initialized
|
||||||
|
notification, tools/list and tools/call. Return a JSON Schema object for each
|
||||||
|
tool's input, validate arguments server-side, and return structured output or
|
||||||
|
content entries. Paginate discovery with nextCursor if your listing is large.
|
||||||
|
|
||||||
|
A small Python example using the Python SDK's FastMCP interface:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from mcp.server.fastmcp import FastMCP
|
||||||
|
|
||||||
|
server = FastMCP("Example reference tools")
|
||||||
|
|
||||||
|
@server.tool()
|
||||||
|
def lookup(term: str) -> str:
|
||||||
|
"""Return a short glossary entry."""
|
||||||
|
glossary = {"SQLite": "An embedded relational database."}
|
||||||
|
return glossary.get(term, "No matching entry.")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
server.run(transport="stdio")
|
||||||
|
```
|
||||||
|
|
||||||
|
Use your virtual environment's Python and select the executable plus script
|
||||||
|
in an MCP profile. See the [MCP stdio and HTTP specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports)
|
||||||
|
and the [LM Studio configuration format](https://lmstudio.ai/docs/app/mcp).
|
||||||
|
|
||||||
|
## Invoke and troubleshoot
|
||||||
|
|
||||||
|
- Select a discovered tool and inspect **Input Schema**. Enter JSON arguments
|
||||||
|
and confirm the call. Tool runs are manual. You can attach the resulting JSON
|
||||||
|
to the next reply in the active chat.
|
||||||
|
- **Executable unavailable:** set the absolute binary path or check the
|
||||||
|
profile's PATH. A GUI app may start with a different PATH than Terminal.
|
||||||
|
- **Configured script does not exist:** correct its path in the source
|
||||||
|
configuration and choose **Reload**. AI Studio cannot find files moved out
|
||||||
|
of a previous working directory.
|
||||||
|
- **Server closes or times out:** inspect the error and captured stderr.
|
||||||
|
Confirm the virtual environment has the dependencies. Keep startup banners
|
||||||
|
and logs off stdout. The stdio client waits 30 seconds per request.
|
||||||
|
- **HTTP 401/403:** check the configured authorization header and token.
|
||||||
|
Confirm that the URL is the MCP endpoint rather than the service homepage.
|
||||||
|
- **Discovery works but a tool fails:** compare your JSON with its input
|
||||||
|
schema and check the server's own logs. The app sends an invocation once.
|
||||||
|
|
||||||
|
The HTTP client supports legacy and stateless discovery. The stdio client
|
||||||
|
supports legacy protocol initialization. OAuth negotiation, server-requested
|
||||||
|
follow-up inputs, and automatic model-driven dispatch are outside this implementation.
|
||||||
|
|
||||||
|
### Existing Gitea profile
|
||||||
|
|
||||||
|
The older `absdev-gitea` launch script is absent from its configured path.
|
||||||
|
A separate GiteaMCP project uses Streamable HTTP. If you run that service,
|
||||||
|
add a named `url` profile with the endpoint it advertises and configure the
|
||||||
|
service's credentials locally. A Streamable HTTP process cannot be substituted
|
||||||
|
for the missing stdio script.
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
| 5. Generation and local tools | Awaiting Docker daemon check | Silent system instructions, runtime parameter overrides, confirmed Docker commands, Finder file actions |
|
| 5. Generation and local tools | Awaiting Docker daemon check | Silent system instructions, runtime parameter overrides, confirmed Docker commands, Finder file actions |
|
||||||
| 6. Compatibility extensions | Awaiting live LM Studio check | OpenAI-compatible endpoint and MCP stdio |
|
| 6. Compatibility extensions | Awaiting live LM Studio check | OpenAI-compatible endpoint and MCP stdio |
|
||||||
| 7. Desktop and runtime controls | Complete | Selected-file previews and attachments, MLX idle eviction and weight limit |
|
| 7. Desktop and runtime controls | Complete | Selected-file previews and attachments, MLX idle eviction and weight limit |
|
||||||
|
| 8. Workspace and integration improvements | Baseline verified | LM Studio config import, Msty-style resource library and Toolbox, composer fixes, appearance, backups, registered MLX folders |
|
||||||
| Final external verification | Awaiting services and credentials | Live LM Studio, Docker, remote Ollama and MCP, Developer ID signing and notarization |
|
| Final external verification | Awaiting services and credentials | Live LM Studio, Docker, remote Ollama and MCP, Developer ID signing and notarization |
|
||||||
|
|
||||||
## Phase 6 checklist
|
## Phase 6 checklist
|
||||||
@@ -35,6 +36,15 @@
|
|||||||
- [x] Display generation histories, time to first output, wall-clock time, and provider-reported throughput.
|
- [x] Display generation histories, time to first output, wall-clock time, and provider-reported throughput.
|
||||||
- [x] Verify the workspace changes with XCTest, rebuild the app, and confirm the build launches.
|
- [x] Verify the workspace changes with XCTest, rebuild the app, and confirm the build launches.
|
||||||
|
|
||||||
|
## Workspace follow-ups
|
||||||
|
|
||||||
|
- [ ] Add Msty workspace migration, recovery scanning, and workspace relocation.
|
||||||
|
- [ ] Add editable shortcut bindings, additional chat appearance and rendering controls, and split-chat layouts.
|
||||||
|
- [ ] Extend Prompt Library metadata, version history, and authenticated or rendered web clip capture.
|
||||||
|
- [ ] Design ACP agent adapters, diff review, and tool history; integrate or configure a separate local proxy.
|
||||||
|
- [ ] Evaluate LM Studio runtime and plugin parity, including additional engines, runtime updates, and headless service controls.
|
||||||
|
- [ ] Verify the Gitea MCP service once its old stdio profile is replaced with a working endpoint.
|
||||||
|
|
||||||
## Verification log
|
## Verification log
|
||||||
|
|
||||||
**16 November 2026.** The release-readiness test run passed 17 checks and skipped
|
**16 November 2026.** The release-readiness test run passed 17 checks and skipped
|
||||||
@@ -77,3 +87,11 @@ opt-in catalog download was skipped. Tests covered bounded UTF-8 file
|
|||||||
previews, model-weight accounting, and rejection and idle eviction with a
|
previews, model-weight accounting, and rejection and idle eviction with a
|
||||||
live MLX model. Desktop and runtime implementation is complete. The final
|
live MLX model. Desktop and runtime implementation is complete. The final
|
||||||
external verification milestone remains.
|
external verification milestone remains.
|
||||||
|
|
||||||
|
**16 November 2026.** The workspace update built and launched. 36 tests
|
||||||
|
passed and the opt-in download was skipped. The installed Local Knowledge
|
||||||
|
server advertised search_knowledge using its LM Studio profile. Tests also
|
||||||
|
verified workspace backup and restore, web text extraction, performance
|
||||||
|
history encoding, and Return handling. The former Gitea stdio script is
|
||||||
|
missing; the separate GiteaMCP project speaks Streamable HTTP. The workspace
|
||||||
|
follow-up checklist tracks the remaining reference-app features.
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Native SwiftUI chat for Apple silicon Macs running macOS 14 or later. Open `AISt
|
|||||||
|
|
||||||
- **Ollama:** In **Settings → Models**, refresh the installed list and select a tag. The default server is `http://127.0.0.1:11434`. Use the same pane to pull, inspect, and delete models. Enter a remote HTTP or HTTPS base URL to use another server. The optional bearer token stays in memory and requires HTTPS for remote servers.
|
- **Ollama:** In **Settings → Models**, refresh the installed list and select a tag. The default server is `http://127.0.0.1:11434`. Use the same pane to pull, inspect, and delete models. Enter a remote HTTP or HTTPS base URL to use another server. The optional bearer token stays in memory and requires HTTPS for remote servers.
|
||||||
- **OpenAI-compatible:** In **Settings → Models**, choose the compatible backend, enter the API base URL (for example `http://127.0.0.1:1234/v1` for LM Studio), then refresh models and select the exact model ID. Remote URLs require HTTPS. An optional bearer token stays in memory and is cleared when the endpoint changes. The server manages model loading. Chat Completions streams the reply and any separately reported reasoning.
|
- **OpenAI-compatible:** In **Settings → Models**, choose the compatible backend, enter the API base URL (for example `http://127.0.0.1:1234/v1` for LM Studio), then refresh models and select the exact model ID. Remote URLs require HTTPS. An optional bearer token stays in memory and is cleared when the endpoint changes. The server manages model loading. Chat Completions streams the reply and any separately reported reasoning.
|
||||||
- **MLX:** In **Settings → MLX Catalog**, download and select a pinned SmolLM2 or Qwen3 model. **Settings → Models** also accepts a local model folder with configuration, tokenizer files, and safetensors weights. **Use Model** selects on-device inference. **Prefer Ollama** can fall back to the configured MLX folder when Ollama fails before emitting output.
|
- **MLX:** In **Settings → MLX Library**, download and select a pinned SmolLM2 or Qwen3 model. **Settings → Models** also accepts a local model folder with configuration, tokenizer files, and safetensors weights. **Use Model** selects on-device inference. **Prefer Ollama** can fall back to the configured MLX folder when Ollama fails before emitting output.
|
||||||
- **Thinking:** The composer sends Boolean or named effort settings to Ollama. Supported MLX templates expose Default, Off, and On. Reported reasoning appears in an expandable section. If an Ollama request is interrupted after emitting text, reasoning, or a tool call, the router keeps that backend. **Stop** cancels generation and retains any partial output.
|
- **Thinking:** The composer sends Boolean or named effort settings to Ollama. Supported MLX templates expose Default, Off, and On. Reported reasoning appears in an expandable section. If an Ollama request is interrupted after emitting text, reasoning, or a tool call, the router keeps that backend. **Stop** cancels generation and retains any partial output.
|
||||||
|
|
||||||
## 2. Chat with documents
|
## 2. Chat with documents
|
||||||
@@ -17,7 +17,7 @@ Chat history, older-message recall, and document indexes live in `~/Library/Appl
|
|||||||
|
|
||||||
## 3. Run a tool
|
## 3. Run a tool
|
||||||
|
|
||||||
Open **Settings → MCP Tools**, enter an MCP HTTP endpoint, and choose **Discover Tools**. Select a tool, review the schema, enter its JSON arguments, and confirm the invocation. You can attach up to 8,000 characters of the result to the next message in the active conversation. The composer shows the attachment before it is sent.
|
Open **Toolbox**, enter an MCP HTTP endpoint, and choose **Discover Tools**. Select a tool, review the schema, enter its JSON arguments, and confirm the invocation. You can attach up to 8,000 characters of the result to the next message in the active conversation. The composer shows the attachment before it is sent.
|
||||||
|
|
||||||
For a local subprocess, select **Local stdio**, enter the full path of the
|
For a local subprocess, select **Local stdio**, enter the full path of the
|
||||||
server executable, and add one argument per line. Choose **Start Server and
|
server executable, and add one argument per line. Choose **Start Server and
|
||||||
@@ -36,8 +36,8 @@ or save as the global system prompt. Global settings persist across launches.
|
|||||||
|
|
||||||
Search conversation titles and messages in the sidebar. Rename the selected
|
Search conversation titles and messages in the sidebar. Rename the selected
|
||||||
chat with the pencil button. Completed replies render inline Markdown and fenced
|
chat with the pencil button. Completed replies render inline Markdown and fenced
|
||||||
code blocks with copy controls. The **Performance** dashboard tracks the last
|
code blocks with copy controls. The **Performance** dashboard keeps the last
|
||||||
50 generations in this session, including latency, duration, output size,
|
50 generations across launches, including latency, duration, output size,
|
||||||
backend, and tokens per second when the provider supplies it.
|
backend, and tokens per second when the provider supplies it.
|
||||||
|
|
||||||
## 5. Generation and local tools
|
## 5. Generation and local tools
|
||||||
@@ -64,6 +64,22 @@ or set an optional maximum weight-file size for new model loads. The model
|
|||||||
weight limit measures safetensors on disk. It does not estimate total runtime
|
weight limit measures safetensors on disk. It does not estimate total runtime
|
||||||
memory.
|
memory.
|
||||||
|
|
||||||
|
## Workspace and desktop preferences
|
||||||
|
|
||||||
|
Open **Workspace** to create reusable document stacks, store instructions as
|
||||||
|
Skills, save reference Contexts, save Prompts, or capture public UTF-8 pages as
|
||||||
|
Web Clips. Select the resources you want to include in the current chat.
|
||||||
|
Toolbox shows the connected MCP server beside the composer. Read
|
||||||
|
[Programming custom MCP servers](Docs/MCP.md) for configuration, the installed
|
||||||
|
Knowledge server, and troubleshooting.
|
||||||
|
|
||||||
|
Return sends and Shift–Return inserts a newline. **Settings → Appearance**
|
||||||
|
controls workspace mode, theme, accent, typography, spell checking and
|
||||||
|
automatic correction. **Settings → Workspace Data** exports the SQLite
|
||||||
|
workspace and restores an AI Studio backup after confirmation. Backup
|
||||||
|
reminders appear in that panel. **Settings → MLX Library** downloads catalog
|
||||||
|
models and registers existing local MLX model folders.
|
||||||
|
|
||||||
## Build and test
|
## Build and test
|
||||||
|
|
||||||
From the project root, run `Scripts/build.sh` to build and open AI Studio. It defaults to Debug. Use `./build.sh Release` for a Release build, or add `--no-launch` after the configuration to build without opening the app. Run `Scripts/test.sh` for XCTest, including the local MCP and Ollama management fixture. It requires Python 3 for the fixture and keeps its logs and results in the temporary build directory.
|
From the project root, run `Scripts/build.sh` to build and open AI Studio. It defaults to Debug. Use `./build.sh Release` for a Release build, or add `--no-launch` after the configuration to build without opening the app. Run `Scripts/test.sh` for XCTest, including the local MCP and Ollama management fixture. It requires Python 3 for the fixture and keeps its logs and results in the temporary build directory.
|
||||||
|
|||||||
+603
-28
@@ -6,6 +6,10 @@ import UniformTypeIdentifiers
|
|||||||
@main
|
@main
|
||||||
struct AIStudioApp: App {
|
struct AIStudioApp: App {
|
||||||
@StateObject private var studio = StudioModel()
|
@StateObject private var studio = StudioModel()
|
||||||
|
@AppStorage("studioTheme") private var theme = StudioTheme.system
|
||||||
|
@AppStorage("studioAccent") private var accent = StudioAccent.storm
|
||||||
|
@AppStorage("studioChatSize") private var chatSize = 14
|
||||||
|
@AppStorage("studioMode") private var mode = StudioMode.normal
|
||||||
|
|
||||||
var body: some Scene {
|
var body: some Scene {
|
||||||
Window("AI Studio", id: "studio") {
|
Window("AI Studio", id: "studio") {
|
||||||
@@ -17,29 +21,33 @@ struct AIStudioApp: App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(minWidth: 740, minHeight: 500)
|
.frame(minWidth: 740, minHeight: 500)
|
||||||
|
.preferredColorScheme(theme.colorScheme)
|
||||||
|
.tint(accent.color)
|
||||||
.task {
|
.task {
|
||||||
await Task.yield()
|
await Task.yield()
|
||||||
studio.open()
|
studio.open()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.defaultSize(width: 1000, height: 700)
|
.defaultSize(width: 1000, height: 700)
|
||||||
Settings {
|
.commands {
|
||||||
TabView {
|
CommandMenu("Appearance") {
|
||||||
BackendSettings(studio: studio)
|
Button("Increase Chat Font Size") { chatSize = min(28, chatSize + 1) }.keyboardShortcut("=")
|
||||||
.tabItem { Label("Models", systemImage: "cpu") }
|
Button("Decrease Chat Font Size") { chatSize = max(10, chatSize - 1) }.keyboardShortcut("-")
|
||||||
ModelCatalogView(studio: studio)
|
Button("Reset Chat Font Size") { chatSize = 14 }.keyboardShortcut("0")
|
||||||
.tabItem { Label("MLX Catalog", systemImage: "arrow.down.circle") }
|
Button("Cycle Theme") { theme = nextValue(theme) }.keyboardShortcut("3")
|
||||||
GenerationSettingsView()
|
Button("Cycle Workspace Mode") { mode = nextValue(mode) }.keyboardShortcut("9")
|
||||||
.tabItem { Label("Generation", systemImage: "slider.horizontal.3") }
|
|
||||||
LocalToolsView(studio: studio)
|
|
||||||
.tabItem { Label("Local Tools", systemImage: "terminal") }
|
|
||||||
RuntimeSettingsView(studio: studio)
|
|
||||||
.tabItem { Label("Runtime", systemImage: "waveform.path") }
|
|
||||||
MCPSettings(studio: studio)
|
|
||||||
.tabItem { Label("MCP Tools", systemImage: "wrench.and.screwdriver") }
|
|
||||||
}
|
}
|
||||||
.frame(width: 630, height: 600)
|
|
||||||
}
|
}
|
||||||
|
Settings {
|
||||||
|
StudioSettingsView(studio: studio)
|
||||||
|
.preferredColorScheme(theme.colorScheme)
|
||||||
|
.tint(accent.color)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func nextValue<Value: CaseIterable & Equatable>(_ current: Value) -> Value {
|
||||||
|
let all = Array(Value.allCases)
|
||||||
|
return all[((all.firstIndex(of: current) ?? 0) + 1) % all.count]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,6 +68,14 @@ struct ChatView: View {
|
|||||||
@AppStorage(GenerationSettings.key) private var generationSettings = Data()
|
@AppStorage(GenerationSettings.key) private var generationSettings = Data()
|
||||||
@State private var showingPromptBuilder = false
|
@State private var showingPromptBuilder = false
|
||||||
@State private var showingPerformance = false
|
@State private var showingPerformance = false
|
||||||
|
@State private var showingWorkspace = false
|
||||||
|
@State private var showingToolbox = false
|
||||||
|
@AppStorage("composerSpellCheck") private var spellCheck = true
|
||||||
|
@AppStorage("composerAutoCorrect") private var autoCorrect = false
|
||||||
|
@AppStorage("studioChatSize") private var chatSize = 14
|
||||||
|
@AppStorage("studioChatFont") private var chatFont = StudioFont.system
|
||||||
|
@AppStorage("studioMode") private var mode = StudioMode.normal
|
||||||
|
@State private var columns: NavigationSplitViewVisibility = .all
|
||||||
@State private var confirmDelete = false
|
@State private var confirmDelete = false
|
||||||
@State private var search = ""
|
@State private var search = ""
|
||||||
@State private var renaming = false
|
@State private var renaming = false
|
||||||
@@ -77,7 +93,7 @@ struct ChatView: View {
|
|||||||
@State private var useDocuments = false
|
@State private var useDocuments = false
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
NavigationSplitView {
|
NavigationSplitView(columnVisibility: $columns) {
|
||||||
List(visibleChats, selection: $studio.selected) { chat in
|
List(visibleChats, selection: $studio.selected) { chat in
|
||||||
Label(chat.title, systemImage: "bubble.left").tag(chat.id)
|
Label(chat.title, systemImage: "bubble.left").tag(chat.id)
|
||||||
}
|
}
|
||||||
@@ -113,12 +129,19 @@ struct ChatView: View {
|
|||||||
Button("Documents", systemImage: "doc.on.doc") { showingLibrary = true }
|
Button("Documents", systemImage: "doc.on.doc") { showingLibrary = true }
|
||||||
.disabled(studio.selected == nil)
|
.disabled(studio.selected == nil)
|
||||||
Button("Prompt Builder", systemImage: "wand.and.stars") { showingPromptBuilder = true }
|
Button("Prompt Builder", systemImage: "wand.and.stars") { showingPromptBuilder = true }
|
||||||
|
Button("Workspace", systemImage: "square.stack.3d.up") { showingWorkspace = true }
|
||||||
Button("Performance", systemImage: "chart.xyaxis.line") { showingPerformance = true }
|
Button("Performance", systemImage: "chart.xyaxis.line") { showingPerformance = true }
|
||||||
SettingsLink { Label("Settings", systemImage: "gear") }
|
SettingsLink { Label("Settings", systemImage: "gear") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.toolbar(mode == .zen ? .hidden : .visible, for: .windowToolbar)
|
||||||
|
.onChange(of: mode, initial: true) { _, value in columns = value == .normal ? .all : .detailOnly }
|
||||||
.sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) }
|
.sheet(isPresented: $showingLibrary) { DocumentLibraryView(studio: studio) }
|
||||||
.sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) }
|
.sheet(isPresented: $showingPerformance) { PerformanceDashboard(studio: studio) }
|
||||||
|
.sheet(isPresented: $showingWorkspace) { WorkspaceResourcesView(studio: studio) }
|
||||||
|
.sheet(isPresented: $showingToolbox) {
|
||||||
|
ToolboxSheet(studio: studio).frame(width: 650, height: 620)
|
||||||
|
}
|
||||||
.sheet(isPresented: $showingPromptBuilder) {
|
.sheet(isPresented: $showingPromptBuilder) {
|
||||||
PromptBuilder(customPrompt: $customPrompt) { instructions, global in
|
PromptBuilder(customPrompt: $customPrompt) { instructions, global in
|
||||||
if global {
|
if global {
|
||||||
@@ -129,7 +152,15 @@ struct ChatView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.onChange(of: studio.selected) { _, _ in useDocuments = false }
|
.onChange(of: studio.selected) { old, _ in
|
||||||
|
useDocuments = false
|
||||||
|
if old != nil {
|
||||||
|
studio.activeStack = nil
|
||||||
|
studio.activeSkill = nil
|
||||||
|
studio.activeContext = nil
|
||||||
|
studio.activeWebClip = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
.alert("Rename Chat", isPresented: $renaming) {
|
.alert("Rename Chat", isPresented: $renaming) {
|
||||||
TextField("Title", text: $newTitle)
|
TextField("Title", text: $newTitle)
|
||||||
Button("Rename") { studio.renameSelectedChat(newTitle) }
|
Button("Rename") { studio.renameSelectedChat(newTitle) }
|
||||||
@@ -154,6 +185,7 @@ struct ChatView: View {
|
|||||||
.padding(24)
|
.padding(24)
|
||||||
.frame(maxWidth: .infinity)
|
.frame(maxWidth: .infinity)
|
||||||
}
|
}
|
||||||
|
.font(chatFont.font(size: chatSize))
|
||||||
.onChange(of: studio.messages.count, initial: true) { _, _ in proxy.scrollTo("end", anchor: .bottom) }
|
.onChange(of: studio.messages.count, initial: true) { _, _ in proxy.scrollTo("end", anchor: .bottom) }
|
||||||
.onChange(of: studio.partial) { _, _ in proxy.scrollTo("end", anchor: .bottom) }
|
.onChange(of: studio.partial) { _, _ in proxy.scrollTo("end", anchor: .bottom) }
|
||||||
}
|
}
|
||||||
@@ -196,25 +228,38 @@ struct ChatView: View {
|
|||||||
}
|
}
|
||||||
.font(.caption)
|
.font(.caption)
|
||||||
}
|
}
|
||||||
TextEditor(text: $studio.prompt)
|
HStack(spacing: 10) {
|
||||||
.font(.body)
|
Button {
|
||||||
|
showingToolbox = true
|
||||||
|
} label: {
|
||||||
|
Label(studio.activeToolset == nil ? "Toolbox" : "1 Active Toolset",
|
||||||
|
systemImage: "wrench.and.screwdriver")
|
||||||
|
}
|
||||||
|
.buttonStyle(.bordered)
|
||||||
|
if let toolset = studio.activeToolset {
|
||||||
|
Text("\(toolset.name) · \(toolset.tools.count) tools").lineLimit(1).foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
if studio.activeStack != nil || studio.activeSkill != nil ||
|
||||||
|
studio.activeContext != nil || studio.activeWebClip != nil {
|
||||||
|
Button("Active Resources", systemImage: "square.stack") { showingWorkspace = true }
|
||||||
|
.buttonStyle(.borderless)
|
||||||
|
}
|
||||||
|
Spacer()
|
||||||
|
}
|
||||||
|
.font(.caption)
|
||||||
|
ChatComposerInput(text: $studio.prompt, canSend: !studio.running, spellCheck: spellCheck,
|
||||||
|
autoCorrect: autoCorrect, font: chatFont.appKit(size: chatSize), send: sendMessage)
|
||||||
.frame(height: 62)
|
.frame(height: 62)
|
||||||
.padding(5)
|
.padding(5)
|
||||||
.background(.background, in: RoundedRectangle(cornerRadius: 8))
|
.background(.background, in: RoundedRectangle(cornerRadius: 8))
|
||||||
.overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.quaternary))
|
.overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.quaternary))
|
||||||
.accessibilityLabel("Message")
|
|
||||||
HStack {
|
HStack {
|
||||||
Text(studio.status).font(.caption).foregroundStyle(.secondary).textSelection(.enabled)
|
Text(studio.status).font(.caption).foregroundStyle(.secondary).textSelection(.enabled)
|
||||||
Spacer()
|
Spacer()
|
||||||
if studio.running {
|
if studio.running {
|
||||||
Button("Stop", systemImage: "stop.fill") { studio.stop() }
|
Button("Stop", systemImage: "stop.fill") { studio.stop() }
|
||||||
} else {
|
} else {
|
||||||
Button("Send", systemImage: "arrow.up") {
|
Button("Send", systemImage: "arrow.up", action: sendMessage)
|
||||||
studio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking,
|
|
||||||
failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: useDocuments,
|
|
||||||
instructions: promptMode.instructions(custom: customPrompt),
|
|
||||||
settings: GenerationSettings.read(generationSettings))
|
|
||||||
}
|
|
||||||
.buttonStyle(.borderedProminent)
|
.buttonStyle(.borderedProminent)
|
||||||
.keyboardShortcut(.return, modifiers: .command)
|
.keyboardShortcut(.return, modifiers: .command)
|
||||||
.disabled(studio.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
.disabled(studio.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||||
@@ -223,6 +268,13 @@ struct ChatView: View {
|
|||||||
}
|
}
|
||||||
.padding(16)
|
.padding(16)
|
||||||
}
|
}
|
||||||
|
private func sendMessage() {
|
||||||
|
studio.send(endpoint: activeEndpoint, model: activeModel, mlxPath: mlxPath, thinking: thinking,
|
||||||
|
failover: failover, mlxOnly: mlxOnly, compatible: compatibleEnabled, recall: recall, useDocuments: useDocuments,
|
||||||
|
instructions: promptMode.instructions(custom: customPrompt),
|
||||||
|
settings: GenerationSettings.read(generationSettings))
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct MessageView: View {
|
struct MessageView: View {
|
||||||
@@ -472,6 +524,8 @@ private func copyChatText(_ text: String) {
|
|||||||
|
|
||||||
struct ChatMarkdown: View {
|
struct ChatMarkdown: View {
|
||||||
let text: String
|
let text: String
|
||||||
|
@AppStorage("studioCodeTheme") private var codeTheme = StudioTheme.system
|
||||||
|
@Environment(\.colorScheme) private var currentScheme
|
||||||
|
|
||||||
struct Block: Equatable {
|
struct Block: Equatable {
|
||||||
let content: String
|
let content: String
|
||||||
@@ -527,6 +581,7 @@ struct ChatMarkdown: View {
|
|||||||
}
|
}
|
||||||
.padding(10)
|
.padding(10)
|
||||||
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8))
|
.background(.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8))
|
||||||
|
.environment(\.colorScheme, codeTheme.colorScheme ?? currentScheme)
|
||||||
} else {
|
} else {
|
||||||
let parsed = try? AttributedString(markdown: block.content,
|
let parsed = try? AttributedString(markdown: block.content,
|
||||||
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))
|
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))
|
||||||
@@ -625,8 +680,11 @@ struct PerformanceDashboard: View {
|
|||||||
Spacer()
|
Spacer()
|
||||||
Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
|
Button("Done") { dismiss() }.keyboardShortcut(.defaultAction)
|
||||||
}
|
}
|
||||||
Text("Up to 50 generations from this session. First output includes model loading and any fallback.")
|
Text("Last 50 generations. First output includes model loading and any fallback.")
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
|
if studio.running {
|
||||||
|
Label("Generation in progress…", systemImage: "ellipsis").foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
if studio.measurements.isEmpty {
|
if studio.measurements.isEmpty {
|
||||||
ContentUnavailableView("No measurements yet", systemImage: "chart.xyaxis.line",
|
ContentUnavailableView("No measurements yet", systemImage: "chart.xyaxis.line",
|
||||||
description: Text("Send a chat message to collect timing and throughput."))
|
description: Text("Send a chat message to collect timing and throughput."))
|
||||||
@@ -646,7 +704,9 @@ struct PerformanceDashboard: View {
|
|||||||
TableColumn("Total") { Text(seconds($0.seconds)) }
|
TableColumn("Total") { Text(seconds($0.seconds)) }
|
||||||
TableColumn("Tokens/s") { Text($0.provider?.tokensPerSecond.map { $0.formatted(.number.precision(.fractionLength(1))) } ?? "—") }
|
TableColumn("Tokens/s") { Text($0.provider?.tokensPerSecond.map { $0.formatted(.number.precision(.fractionLength(1))) } ?? "—") }
|
||||||
TableColumn("Tokens") { Text($0.provider?.tokens.formatted() ?? "—") }
|
TableColumn("Tokens") { Text($0.provider?.tokens.formatted() ?? "—") }
|
||||||
TableColumn("Characters") { Text($0.characters.formatted()) }
|
TableColumn("Characters/s") { run in
|
||||||
|
Text(run.charactersPerSecond.map { $0.formatted(.number.precision(.fractionLength(1))) } ?? "—")
|
||||||
|
}
|
||||||
TableColumn("Outcome", value: \.outcome)
|
TableColumn("Outcome", value: \.outcome)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1035,3 +1095,518 @@ struct RuntimeSettingsView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct ChatComposerInput: NSViewRepresentable {
|
||||||
|
@Binding var text: String
|
||||||
|
var canSend: Bool
|
||||||
|
var spellCheck: Bool
|
||||||
|
var autoCorrect: Bool
|
||||||
|
var font: NSFont
|
||||||
|
var send: () -> Void
|
||||||
|
|
||||||
|
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||||
|
|
||||||
|
func makeNSView(context: Context) -> NSScrollView {
|
||||||
|
let scroll = NSTextView.scrollableTextView()
|
||||||
|
guard let editor = scroll.documentView as? NSTextView else { return scroll }
|
||||||
|
editor.isRichText = false
|
||||||
|
editor.font = font
|
||||||
|
editor.delegate = context.coordinator
|
||||||
|
editor.drawsBackground = false
|
||||||
|
scroll.drawsBackground = false
|
||||||
|
editor.setAccessibilityLabel("Message")
|
||||||
|
return scroll
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||||
|
context.coordinator.parent = self
|
||||||
|
if let editor = scroll.documentView as? NSTextView {
|
||||||
|
editor.font = font
|
||||||
|
editor.isContinuousSpellCheckingEnabled = spellCheck
|
||||||
|
editor.isAutomaticSpellingCorrectionEnabled = autoCorrect
|
||||||
|
if editor.string != text {
|
||||||
|
editor.string = text
|
||||||
|
editor.setSelectedRange(NSRange(location: text.utf16.count, length: 0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static func sendsReturn(modifiers: NSEvent.ModifierFlags, marked: Bool) -> Bool {
|
||||||
|
!marked && modifiers.intersection([.shift, .command, .option, .control]).isEmpty
|
||||||
|
}
|
||||||
|
|
||||||
|
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||||
|
var parent: ChatComposerInput
|
||||||
|
|
||||||
|
init(_ parent: ChatComposerInput) { self.parent = parent }
|
||||||
|
|
||||||
|
func textDidChange(_ notification: Notification) {
|
||||||
|
guard let editor = notification.object as? NSTextView else { return }
|
||||||
|
parent.text = editor.string
|
||||||
|
}
|
||||||
|
|
||||||
|
func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
|
||||||
|
guard commandSelector == #selector(NSResponder.insertNewline(_:)),
|
||||||
|
let event = NSApp.currentEvent,
|
||||||
|
event.type == .keyDown,
|
||||||
|
ChatComposerInput.sendsReturn(modifiers: event.modifierFlags, marked: textView.hasMarkedText()) else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if parent.canSend { parent.send() }
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ToolboxSheet: View {
|
||||||
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
@ObservedObject var studio: StudioModel
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
HStack {
|
||||||
|
Label("Toolbox", systemImage: "wrench.and.screwdriver").font(.headline)
|
||||||
|
Spacer()
|
||||||
|
Button("Done") { dismiss() }
|
||||||
|
}
|
||||||
|
.padding()
|
||||||
|
MCPSettings(studio: studio)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct WorkspaceResourcesView: View {
|
||||||
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
@ObservedObject var studio: StudioModel
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
HStack {
|
||||||
|
Text("Workspace").font(.title2.bold())
|
||||||
|
Spacer()
|
||||||
|
Button("Done") { dismiss() }
|
||||||
|
}
|
||||||
|
.padding()
|
||||||
|
TabView {
|
||||||
|
KnowledgeStacksView(studio: studio).tabItem { Label("Stacks", systemImage: "square.stack.3d.up") }
|
||||||
|
WorkspaceSnippetsView(studio: studio, kind: .skill).tabItem { Label("Skills", systemImage: "bolt") }
|
||||||
|
WorkspaceSnippetsView(studio: studio, kind: .context).tabItem { Label("Contexts", systemImage: "doc.text") }
|
||||||
|
WorkspaceSnippetsView(studio: studio, kind: .prompt).tabItem { Label("Prompts", systemImage: "text.bubble") }
|
||||||
|
WorkspaceSnippetsView(studio: studio, kind: .webClip).tabItem { Label("Web Clips", systemImage: "link") }
|
||||||
|
}
|
||||||
|
if !studio.workspaceStatus.isEmpty {
|
||||||
|
Text(studio.workspaceStatus).foregroundStyle(.red).textSelection(.enabled).padding(8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(width: 720, height: 560)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct KnowledgeStacksView: View {
|
||||||
|
@ObservedObject var studio: StudioModel
|
||||||
|
@State private var selected: UUID?
|
||||||
|
@State private var name = ""
|
||||||
|
@State private var documents: [LibraryDocument] = []
|
||||||
|
@State private var importing = false
|
||||||
|
@State private var busy = false
|
||||||
|
@State private var removing = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Form {
|
||||||
|
Section("Knowledge Stacks") {
|
||||||
|
HStack {
|
||||||
|
TextField("New stack name", text: $name)
|
||||||
|
Button("Create") {
|
||||||
|
selected = studio.createStack(name.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||||
|
name = ""
|
||||||
|
}.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || busy)
|
||||||
|
}
|
||||||
|
Picker("Manage stack", selection: $selected) {
|
||||||
|
Text("Select a stack").tag(UUID?.none)
|
||||||
|
ForEach(studio.knowledgeStacks) { Text($0.title).tag(Optional($0.id)) }
|
||||||
|
}
|
||||||
|
Picker("Use in this chat", selection: $studio.activeStack) {
|
||||||
|
Text("None").tag(UUID?.none)
|
||||||
|
ForEach(studio.knowledgeStacks) { Text($0.title).tag(Optional($0.id)) }
|
||||||
|
}
|
||||||
|
Text("Matching passages from the active stack are included in inference requests.")
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
if let selected {
|
||||||
|
Section("Indexed Documents") {
|
||||||
|
ForEach(documents) { document in
|
||||||
|
HStack {
|
||||||
|
Text(document.title)
|
||||||
|
Spacer()
|
||||||
|
Button("Remove", role: .destructive) {
|
||||||
|
studio.deleteStackDocument(document, in: selected)
|
||||||
|
refresh()
|
||||||
|
}.disabled(busy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
HStack {
|
||||||
|
Button("Import Document…") { importing = true }.disabled(busy)
|
||||||
|
if busy { ProgressView().controlSize(.small) }
|
||||||
|
Spacer()
|
||||||
|
Button("Delete Stack…", role: .destructive) { removing = true }.disabled(busy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.formStyle(.grouped)
|
||||||
|
.onAppear { selected = studio.activeStack; refresh() }
|
||||||
|
.onChange(of: selected) { _, _ in refresh() }
|
||||||
|
.fileImporter(isPresented: $importing, allowedContentTypes: [
|
||||||
|
.pdf, .plainText, .commaSeparatedText, UTType(filenameExtension: "md") ?? .plainText
|
||||||
|
]) { result in
|
||||||
|
guard let url = try? result.get(), let selected else { return }
|
||||||
|
busy = true
|
||||||
|
Task {
|
||||||
|
await studio.importStackDocument(url, in: selected)
|
||||||
|
refresh()
|
||||||
|
busy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.confirmationDialog("Delete this stack and its index?", isPresented: $removing) {
|
||||||
|
Button("Delete Stack", role: .destructive) {
|
||||||
|
if let selected { studio.deleteStack(selected) }
|
||||||
|
selected = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func refresh() { documents = selected.map(studio.stackDocuments) ?? [] }
|
||||||
|
}
|
||||||
|
|
||||||
|
struct WorkspaceSnippetsView: View {
|
||||||
|
@ObservedObject var studio: StudioModel
|
||||||
|
let kind: WorkspaceSnippet.Kind
|
||||||
|
@State private var search = ""
|
||||||
|
@State private var id: UUID?
|
||||||
|
@State private var title = ""
|
||||||
|
@State private var content = ""
|
||||||
|
@State private var address = ""
|
||||||
|
@State private var importing = false
|
||||||
|
@State private var capturing = false
|
||||||
|
@State private var deleting = false
|
||||||
|
@State private var error = ""
|
||||||
|
|
||||||
|
private var items: [WorkspaceSnippet] {
|
||||||
|
studio.snippets.filter {
|
||||||
|
$0.kind == kind && (search.isEmpty || $0.title.localizedCaseInsensitiveContains(search))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HSplitView {
|
||||||
|
VStack(spacing: 8) {
|
||||||
|
TextField("Search \(kind.rawValue)s", text: $search)
|
||||||
|
List(items, selection: $id) { item in Text(item.title).tag(item.id) }
|
||||||
|
Button("New \(kind.rawValue)") { clear() }
|
||||||
|
}
|
||||||
|
.padding(12)
|
||||||
|
.frame(minWidth: 180, idealWidth: 220)
|
||||||
|
VStack(alignment: .leading, spacing: 10) {
|
||||||
|
TextField("Title", text: $title)
|
||||||
|
if kind == .webClip {
|
||||||
|
HStack {
|
||||||
|
TextField("Source URL", text: $address)
|
||||||
|
Button("Capture Text") {
|
||||||
|
capturing = true
|
||||||
|
let source = address
|
||||||
|
Task {
|
||||||
|
defer { capturing = false }
|
||||||
|
do {
|
||||||
|
content = try await WebClipCapture.text(from: source)
|
||||||
|
if title.isEmpty { title = URL(string: source)?.host ?? "Web Clip" }
|
||||||
|
error = ""
|
||||||
|
} catch { self.error = error.localizedDescription }
|
||||||
|
}
|
||||||
|
}.disabled(capturing || address.isEmpty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
TextEditor(text: $content).accessibilityLabel("\(kind.rawValue) text")
|
||||||
|
.border(.quaternary)
|
||||||
|
if !error.isEmpty { Text(error).foregroundStyle(.red).textSelection(.enabled) }
|
||||||
|
HStack {
|
||||||
|
if kind != .webClip { Button("Import Text…") { importing = true } }
|
||||||
|
if id != nil { Button("Delete…", role: .destructive) { deleting = true } }
|
||||||
|
Spacer()
|
||||||
|
if id != nil {
|
||||||
|
Button(kind == .prompt ? "Use in Composer" : isActive ? "Remove from Chat" : "Use in Chat") {
|
||||||
|
apply()
|
||||||
|
}.disabled(studio.running)
|
||||||
|
}
|
||||||
|
Button("Save", action: save).buttonStyle(.borderedProminent)
|
||||||
|
.disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
|
||||||
|
content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || capturing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.padding(15)
|
||||||
|
.frame(minWidth: 400)
|
||||||
|
}
|
||||||
|
.onChange(of: id) { _, value in
|
||||||
|
if let item = studio.snippets.first(where: { $0.id == value }) {
|
||||||
|
title = item.title
|
||||||
|
if kind == .webClip {
|
||||||
|
let parts = item.content.components(separatedBy: "\n\n")
|
||||||
|
address = String((parts.first ?? "").dropFirst("Source: ".count))
|
||||||
|
content = parts.dropFirst().joined(separator: "\n\n")
|
||||||
|
} else {
|
||||||
|
content = item.content
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.fileImporter(isPresented: $importing, allowedContentTypes: [
|
||||||
|
.plainText, UTType(filenameExtension: "md") ?? .plainText
|
||||||
|
]) { result in
|
||||||
|
do {
|
||||||
|
let file = try result.get()
|
||||||
|
content = try LocalFilePreview.read(file, limit: 12000)
|
||||||
|
if title.isEmpty { title = file.deletingPathExtension().lastPathComponent }
|
||||||
|
error = ""
|
||||||
|
} catch { self.error = error.localizedDescription }
|
||||||
|
}
|
||||||
|
.confirmationDialog("Delete saved \(kind.rawValue.lowercased())?", isPresented: $deleting) {
|
||||||
|
Button("Delete", role: .destructive) {
|
||||||
|
if let id { studio.removeSnippet(id) }
|
||||||
|
clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var isActive: Bool {
|
||||||
|
guard let id else { return false }
|
||||||
|
return switch kind {
|
||||||
|
case .skill: studio.activeSkill == id
|
||||||
|
case .context: studio.activeContext == id
|
||||||
|
case .webClip: studio.activeWebClip == id
|
||||||
|
case .prompt: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func apply() {
|
||||||
|
guard let item = studio.snippets.first(where: { $0.id == id }) else { return }
|
||||||
|
switch kind {
|
||||||
|
case .skill: studio.activeSkill = isActive ? nil : item.id
|
||||||
|
case .context: studio.activeContext = isActive ? nil : item.id
|
||||||
|
case .webClip: studio.activeWebClip = isActive ? nil : item.id
|
||||||
|
case .prompt: studio.prompt = item.content
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func save() {
|
||||||
|
if kind == .webClip {
|
||||||
|
do { _ = try WebClipCapture.url(address) }
|
||||||
|
catch { self.error = error.localizedDescription; return }
|
||||||
|
}
|
||||||
|
let key = id ?? UUID()
|
||||||
|
let stored = kind == .webClip ? "Source: \(address)\n\n\(content)" : content
|
||||||
|
studio.saveSnippet(id: key, kind: kind, title: title.trimmingCharacters(in: .whitespacesAndNewlines), content: stored)
|
||||||
|
id = key
|
||||||
|
error = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
private func clear() { id = nil; title = ""; content = ""; address = ""; error = "" }
|
||||||
|
}
|
||||||
|
|
||||||
|
enum StudioTheme: String, CaseIterable, Identifiable {
|
||||||
|
case system = "System", light = "Light", dark = "Dark"
|
||||||
|
var id: Self { self }
|
||||||
|
var colorScheme: ColorScheme? {
|
||||||
|
switch self { case .system: nil; case .light: .light; case .dark: .dark }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum StudioAccent: String, CaseIterable, Identifiable {
|
||||||
|
case storm = "Storm", moss = "Moss", ocean = "Ocean", dusk = "Dusk", ember = "Ember"
|
||||||
|
var id: Self { self }
|
||||||
|
var color: Color {
|
||||||
|
switch self { case .storm: .blue; case .moss: .green; case .ocean: .teal; case .dusk: .purple; case .ember: .orange }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum StudioMode: String, CaseIterable, Identifiable {
|
||||||
|
case normal = "Normal", focus = "Focus", zen = "Zen"
|
||||||
|
var id: Self { self }
|
||||||
|
}
|
||||||
|
|
||||||
|
enum StudioFont: String, CaseIterable, Identifiable {
|
||||||
|
case system = "System", serif = "Serif", mono = "Monospaced"
|
||||||
|
var id: Self { self }
|
||||||
|
|
||||||
|
func font(size: Int) -> Font {
|
||||||
|
.system(size: CGFloat(size), design: self == .serif ? .serif : self == .mono ? .monospaced : .default)
|
||||||
|
}
|
||||||
|
|
||||||
|
func appKit(size: Int) -> NSFont {
|
||||||
|
switch self {
|
||||||
|
case .system: .systemFont(ofSize: CGFloat(size))
|
||||||
|
case .serif: NSFont(name: "Georgia", size: CGFloat(size)) ?? .systemFont(ofSize: CGFloat(size))
|
||||||
|
case .mono: .monospacedSystemFont(ofSize: CGFloat(size), weight: .regular)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct StudioSettingsView: View {
|
||||||
|
@ObservedObject var studio: StudioModel
|
||||||
|
@State private var page: String? = "Models"
|
||||||
|
private let pages = [
|
||||||
|
("Models", "cpu"), ("MLX Library", "square.stack"), ("Generation", "slider.horizontal.3"),
|
||||||
|
("Toolbox", "wrench.and.screwdriver"), ("Local Tools", "terminal"), ("Runtime", "waveform.path"),
|
||||||
|
("Appearance", "paintpalette"), ("Workspace Data", "externaldrive")
|
||||||
|
]
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HSplitView {
|
||||||
|
List(selection: $page) {
|
||||||
|
ForEach(pages, id: \.0) { name, icon in Label(name, systemImage: icon).tag(name) }
|
||||||
|
}
|
||||||
|
.listStyle(.sidebar)
|
||||||
|
.frame(minWidth: 160, idealWidth: 180, maxWidth: 210)
|
||||||
|
Group {
|
||||||
|
switch page {
|
||||||
|
case "MLX Library": ModelCatalogView(studio: studio)
|
||||||
|
case "Generation": GenerationSettingsView()
|
||||||
|
case "Toolbox": MCPSettings(studio: studio)
|
||||||
|
case "Local Tools": LocalToolsView(studio: studio)
|
||||||
|
case "Runtime": RuntimeSettingsView(studio: studio)
|
||||||
|
case "Appearance": StudioAppearanceView()
|
||||||
|
case "Workspace Data": WorkspaceDataView(studio: studio)
|
||||||
|
default: BackendSettings(studio: studio)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.frame(minWidth: 570, maxWidth: .infinity, maxHeight: .infinity)
|
||||||
|
}
|
||||||
|
.frame(width: 780, height: 610)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct StudioAppearanceView: View {
|
||||||
|
@AppStorage("studioTheme") private var theme = StudioTheme.system
|
||||||
|
@AppStorage("studioAccent") private var accent = StudioAccent.storm
|
||||||
|
@AppStorage("studioMode") private var mode = StudioMode.normal
|
||||||
|
@AppStorage("studioChatFont") private var font = StudioFont.system
|
||||||
|
@AppStorage("studioChatSize") private var size = 14
|
||||||
|
@AppStorage("studioCodeTheme") private var codeTheme = StudioTheme.system
|
||||||
|
@AppStorage("composerSpellCheck") private var spell = true
|
||||||
|
@AppStorage("composerAutoCorrect") private var correct = false
|
||||||
|
@State private var query = ""
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Form {
|
||||||
|
Section("Appearance") {
|
||||||
|
Picker("Color preference", selection: $theme) {
|
||||||
|
ForEach(StudioTheme.allCases) { Text($0.rawValue).tag($0) }
|
||||||
|
}
|
||||||
|
Picker("Workspace mode", selection: $mode) {
|
||||||
|
ForEach(StudioMode.allCases) { Text($0.rawValue).tag($0) }
|
||||||
|
}.pickerStyle(.segmented)
|
||||||
|
Picker("Accent", selection: $accent) {
|
||||||
|
ForEach(StudioAccent.allCases) { entry in
|
||||||
|
Label(entry.rawValue, systemImage: "circle.fill").foregroundStyle(entry.color).tag(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Picker("Chat font", selection: $font) {
|
||||||
|
ForEach(StudioFont.allCases) { Text($0.rawValue).tag($0) }
|
||||||
|
}
|
||||||
|
Stepper(value: $size, in: 10...28) { LabeledContent("Chat font size", value: "\(size) pt") }
|
||||||
|
Picker("Code block appearance", selection: $codeTheme) {
|
||||||
|
ForEach(StudioTheme.allCases) { Text($0.rawValue).tag($0) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Section("Composer") {
|
||||||
|
Toggle("Check spelling as you type", isOn: $spell)
|
||||||
|
Toggle("Correct spelling automatically", isOn: $correct)
|
||||||
|
}
|
||||||
|
Section("Keyboard Shortcuts") {
|
||||||
|
TextField("Find a shortcut", text: $query)
|
||||||
|
ForEach(shortcuts.filter { query.isEmpty || $0.0.localizedCaseInsensitiveContains(query) }, id: \.0) {
|
||||||
|
LabeledContent($0.0, value: $0.1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.formStyle(.grouped)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var shortcuts: [(String, String)] {
|
||||||
|
[("Send chat message", "Return"), ("Insert newline", "⇧ Return"), ("Open Settings", "⌘ ,"),
|
||||||
|
("Increase chat font", "⌘ ="), ("Decrease chat font", "⌘ −"), ("Reset chat font", "⌘ 0"),
|
||||||
|
("Cycle theme", "⌘ 3"), ("Cycle workspace mode", "⌘ 9")]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct WorkspaceDataView: View {
|
||||||
|
@ObservedObject var studio: StudioModel
|
||||||
|
@AppStorage("workspaceBackupTime") private var lastBackup = 0.0
|
||||||
|
@AppStorage("workspaceBackupReminderDays") private var reminderDays = 0
|
||||||
|
@State private var restoring = false
|
||||||
|
@State private var pending: URL?
|
||||||
|
@State private var confirm = false
|
||||||
|
@State private var status = ""
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Form {
|
||||||
|
Section("Backup") {
|
||||||
|
LabeledContent("Last export", value: lastBackup > 0
|
||||||
|
? Date(timeIntervalSince1970: lastBackup).formatted(date: .abbreviated, time: .shortened)
|
||||||
|
: "None")
|
||||||
|
Button("Export Workspace…", action: export)
|
||||||
|
Stepper(value: $reminderDays, in: 0...30) {
|
||||||
|
LabeledContent("Remind every", value: reminderDays > 0 ? "\(reminderDays) day(s)" : "Off")
|
||||||
|
}
|
||||||
|
if reminderDays > 0 && (lastBackup == 0 || Date.now.timeIntervalSince1970 - lastBackup >= Double(reminderDays) * 86_400) {
|
||||||
|
Label("Workspace backup is due", systemImage: "exclamationmark.circle").foregroundStyle(.orange)
|
||||||
|
}
|
||||||
|
Text("Exports include chats, document indexes, stacks and saved resources.")
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
Section("Storage") {
|
||||||
|
Text(StudioModel.workspaceDirectory.path).textSelection(.enabled)
|
||||||
|
Button("Reveal Workspace in Finder") { NSWorkspace.shared.activateFileViewerSelecting([StudioModel.workspaceDirectory]) }
|
||||||
|
}
|
||||||
|
Section("Restore") {
|
||||||
|
Button("Choose Backup…") { restoring = true }
|
||||||
|
.disabled(studio.running || studio.importingDocument)
|
||||||
|
if !status.isEmpty { Text(status).textSelection(.enabled).foregroundStyle(.secondary) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.formStyle(.grouped)
|
||||||
|
.fileImporter(isPresented: $restoring, allowedContentTypes: [.data]) { result in
|
||||||
|
do { pending = try result.get(); confirm = true }
|
||||||
|
catch { status = error.localizedDescription }
|
||||||
|
}
|
||||||
|
.confirmationDialog("Replace the current workspace with this backup?", isPresented: $confirm) {
|
||||||
|
Button("Restore Workspace", role: .destructive) { restore() }
|
||||||
|
} message: {
|
||||||
|
Text("The current chats and saved resources will be replaced. Export a backup first if you need to keep them.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func export() {
|
||||||
|
let panel = NSSavePanel()
|
||||||
|
panel.nameFieldStringValue = "AIStudio-Workspace-\(Date.now.formatted(.iso8601.year().month().day())).sqlite"
|
||||||
|
panel.canCreateDirectories = true
|
||||||
|
panel.begin { response in
|
||||||
|
guard response == .OK, let url = panel.url else { return }
|
||||||
|
do {
|
||||||
|
try studio.exportWorkspace(to: url)
|
||||||
|
lastBackup = Date.now.timeIntervalSince1970
|
||||||
|
status = "Exported \(url.lastPathComponent)."
|
||||||
|
} catch { status = error.localizedDescription }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func restore() {
|
||||||
|
guard let url = pending else { return }
|
||||||
|
let scoped = url.startAccessingSecurityScopedResource()
|
||||||
|
defer {
|
||||||
|
if scoped { url.stopAccessingSecurityScopedResource() }
|
||||||
|
pending = nil
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
try studio.restoreWorkspace(from: url)
|
||||||
|
status = "Restored \(url.lastPathComponent)."
|
||||||
|
} catch { status = error.localizedDescription }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+10
-3
@@ -143,7 +143,7 @@ enum Router {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct ProviderMetrics: Equatable, Sendable {
|
struct ProviderMetrics: Codable, Equatable, Sendable {
|
||||||
let tokens: Int
|
let tokens: Int
|
||||||
let seconds: Double
|
let seconds: Double
|
||||||
|
|
||||||
@@ -154,14 +154,21 @@ struct ProviderMetrics: Equatable, Sendable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct GenerationMeasurement: Identifiable {
|
struct GenerationMeasurement: Codable, Identifiable {
|
||||||
let id = UUID()
|
var id = UUID()
|
||||||
|
static let key = "generationMeasurements"
|
||||||
let backend: String
|
let backend: String
|
||||||
let firstOutput: Double?
|
let firstOutput: Double?
|
||||||
let seconds: Double
|
let seconds: Double
|
||||||
let characters: Int
|
let characters: Int
|
||||||
let provider: ProviderMetrics?
|
let provider: ProviderMetrics?
|
||||||
let outcome: String
|
let outcome: String
|
||||||
|
|
||||||
|
var charactersPerSecond: Double? {
|
||||||
|
guard let firstOutput, seconds > firstOutput, characters > 0 else { return nil }
|
||||||
|
let rate = Double(characters) / (seconds - firstOutput)
|
||||||
|
return rate.isFinite ? rate : nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
enum PromptMode: String, CaseIterable, Identifiable {
|
enum PromptMode: String, CaseIterable, Identifiable {
|
||||||
|
|||||||
@@ -99,3 +99,56 @@ struct DocumentVector {
|
|||||||
return Self(language: "\(language.rawValue):\(model.revision)", values: values.map { Float($0 / magnitude) })
|
return Self(language: "\(language.rawValue):\(model.revision)", values: values.map { Float($0 / magnitude) })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum WebClipCapture {
|
||||||
|
static func url(_ address: String) throws -> URL {
|
||||||
|
let input = address.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard let parts = URLComponents(string: input), let scheme = parts.scheme?.lowercased(),
|
||||||
|
["http", "https"].contains(scheme), let host = parts.host, !host.isEmpty,
|
||||||
|
parts.user == nil, parts.password == nil, let url = parts.url else {
|
||||||
|
throw StudioError("Enter an HTTP or HTTPS page URL.")
|
||||||
|
}
|
||||||
|
return url
|
||||||
|
}
|
||||||
|
|
||||||
|
static func text(from address: String) async throws -> String {
|
||||||
|
let session = URLSession(configuration: .ephemeral)
|
||||||
|
defer { session.invalidateAndCancel() }
|
||||||
|
var request = URLRequest(url: try url(address), timeoutInterval: 20)
|
||||||
|
request.setValue("text/html, text/plain", forHTTPHeaderField: "Accept")
|
||||||
|
let (bytes, response) = try await session.bytes(for: request)
|
||||||
|
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode),
|
||||||
|
let type = response.mimeType, ["text/html", "text/plain", "application/xhtml+xml"].contains(type) else {
|
||||||
|
throw StudioError("The server did not return a supported text page.")
|
||||||
|
}
|
||||||
|
var data = Data()
|
||||||
|
for try await byte in bytes {
|
||||||
|
try Task.checkCancellation()
|
||||||
|
guard data.count < 1_048_576 else { throw StudioError("The page exceeds the 1 MB capture limit.") }
|
||||||
|
data.append(byte)
|
||||||
|
}
|
||||||
|
guard let raw = String(data: data, encoding: .utf8) else { throw StudioError("The page is not UTF-8.") }
|
||||||
|
let content = type == "text/plain" ? raw : plainText(raw)
|
||||||
|
guard !content.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||||
|
throw StudioError("The page contains no readable text.")
|
||||||
|
}
|
||||||
|
return String(content.prefix(12_000))
|
||||||
|
}
|
||||||
|
|
||||||
|
static func plainText(_ html: String) -> String {
|
||||||
|
html.replacingOccurrences(of: "(?is)<(script|style|head|noscript)\\b[^>]*>.*?</\\1\\s*>", with: " ",
|
||||||
|
options: .regularExpression)
|
||||||
|
.replacingOccurrences(of: "(?s)<!--.*?-->", with: " ", options: .regularExpression)
|
||||||
|
.replacingOccurrences(of: "(?i)</(?:p|div|li|section|article|h[1-6])\\s*>|<br\\s*/?>", with: "\n",
|
||||||
|
options: .regularExpression)
|
||||||
|
.replacingOccurrences(of: "<[^>]+>", with: " ", options: .regularExpression)
|
||||||
|
.replacingOccurrences(of: " ", with: " ")
|
||||||
|
.replacingOccurrences(of: "<", with: "<")
|
||||||
|
.replacingOccurrences(of: ">", with: ">")
|
||||||
|
.replacingOccurrences(of: """, with: "\"")
|
||||||
|
.replacingOccurrences(of: "&", with: "&")
|
||||||
|
.components(separatedBy: .newlines)
|
||||||
|
.map { $0.split(whereSeparator: \.isWhitespace).joined(separator: " ") }
|
||||||
|
.filter { !$0.isEmpty }.joined(separator: "\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+233
-35
@@ -1,6 +1,8 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import Darwin
|
import Darwin
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import AppKit
|
||||||
|
import UniformTypeIdentifiers
|
||||||
|
|
||||||
actor HTTPMCPClient: MCPToolClient {
|
actor HTTPMCPClient: MCPToolClient {
|
||||||
private struct Connection {
|
private struct Connection {
|
||||||
@@ -19,12 +21,13 @@ actor HTTPMCPClient: MCPToolClient {
|
|||||||
|
|
||||||
private let endpoint: URL
|
private let endpoint: URL
|
||||||
private let token: String
|
private let token: String
|
||||||
|
private let headers: [String: String]
|
||||||
private let session: URLSession
|
private let session: URLSession
|
||||||
private var connection: Connection?
|
private var connection: Connection?
|
||||||
private static let modern = "2026-07-28"
|
private static let modern = "2026-07-28"
|
||||||
private let versions = ["2025-11-25", "2025-06-18", "2025-03-26"]
|
private let versions = ["2025-11-25", "2025-06-18", "2025-03-26"]
|
||||||
|
|
||||||
init(endpoint: String, token: String = "") throws {
|
init(endpoint: String, token: String = "", headers: [String: String] = [:]) throws {
|
||||||
guard let parsed = URLComponents(string: endpoint.trimmingCharacters(in: .whitespacesAndNewlines)),
|
guard let parsed = URLComponents(string: endpoint.trimmingCharacters(in: .whitespacesAndNewlines)),
|
||||||
let host = parsed.host?.lowercased(), !host.isEmpty,
|
let host = parsed.host?.lowercased(), !host.isEmpty,
|
||||||
parsed.user == nil, parsed.password == nil, parsed.fragment == nil, let url = parsed.url else {
|
parsed.user == nil, parsed.password == nil, parsed.fragment == nil, let url = parsed.url else {
|
||||||
@@ -37,6 +40,13 @@ actor HTTPMCPClient: MCPToolClient {
|
|||||||
guard !token.contains(where: \.isNewline) else { throw StudioError("The bearer token must be a single line.") }
|
guard !token.contains(where: \.isNewline) else { throw StudioError("The bearer token must be a single line.") }
|
||||||
self.endpoint = url
|
self.endpoint = url
|
||||||
self.token = token
|
self.token = token
|
||||||
|
self.headers = headers
|
||||||
|
let protected = Set(["host", "content-length", "transfer-encoding", "connection", "content-type",
|
||||||
|
"accept", "mcp-protocol-version", "mcp-session-id", "mcp-method", "mcp-name"])
|
||||||
|
guard headers.allSatisfy({ name, value in
|
||||||
|
guard !name.isEmpty, !protected.contains(name.lowercased()), !value.contains(where: \.isNewline) else { return false }
|
||||||
|
return name.utf8.allSatisfy { (33...126).contains($0) && $0 != 58 }
|
||||||
|
}) else { throw StudioError("A custom MCP HTTP header has an invalid or reserved name or value.") }
|
||||||
let config = URLSessionConfiguration.ephemeral
|
let config = URLSessionConfiguration.ephemeral
|
||||||
config.timeoutIntervalForRequest = 30
|
config.timeoutIntervalForRequest = 30
|
||||||
config.timeoutIntervalForResource = 120
|
config.timeoutIntervalForResource = 120
|
||||||
@@ -151,6 +161,7 @@ actor HTTPMCPClient: MCPToolClient {
|
|||||||
request.setValue(params["name"] as? String, forHTTPHeaderField: "Mcp-Name")
|
request.setValue(params["name"] as? String, forHTTPHeaderField: "Mcp-Name")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) }
|
||||||
if !token.isEmpty { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }
|
if !token.isEmpty { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }
|
||||||
let (bytes, response) = try await session.bytes(for: request)
|
let (bytes, response) = try await session.bytes(for: request)
|
||||||
guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
|
guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
|
||||||
@@ -213,9 +224,18 @@ struct MCPSettings: View {
|
|||||||
@AppStorage("mcpTransport") private var transport = "http"
|
@AppStorage("mcpTransport") private var transport = "http"
|
||||||
@AppStorage("mcpExecutable") private var executable = ""
|
@AppStorage("mcpExecutable") private var executable = ""
|
||||||
@AppStorage("mcpArguments") private var launchArguments = ""
|
@AppStorage("mcpArguments") private var launchArguments = ""
|
||||||
@State private var client: (any MCPToolClient)?
|
private var client: (any MCPToolClient)? { studio.activeToolset?.client }
|
||||||
@State private var confirmLaunch = false
|
@State private var confirmLaunch = false
|
||||||
@State private var tools: [MCPTool] = []
|
@AppStorage("mcpConfigPath") private var configPath = ""
|
||||||
|
@AppStorage("mcpSelectedProfile") private var selectedProfile = ""
|
||||||
|
@State private var profiles: [String: MCPServerConfiguration] = [:]
|
||||||
|
@State private var importingConfig = false
|
||||||
|
@State private var configStatus = ""
|
||||||
|
|
||||||
|
private var profile: MCPServerConfiguration? { profiles[selectedProfile] }
|
||||||
|
private var local: Bool { profile.map { $0.command != nil } ?? (transport == "stdio") }
|
||||||
|
private var target: String { profile?.target ?? (local ? executable : endpoint) }
|
||||||
|
private var tools: [MCPTool] { studio.activeToolset?.tools ?? [] }
|
||||||
@State private var name = ""
|
@State private var name = ""
|
||||||
@State private var arguments = "{}"
|
@State private var arguments = "{}"
|
||||||
@State private var result = ""
|
@State private var result = ""
|
||||||
@@ -226,24 +246,49 @@ struct MCPSettings: View {
|
|||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
Form {
|
Form {
|
||||||
Section("MCP server") {
|
Section("Custom MCP Servers") {
|
||||||
Picker("Transport", selection: $transport) {
|
HStack {
|
||||||
Text("Streamable HTTP").tag("http")
|
Button("Import mcp.json…") { importingConfig = true }
|
||||||
Text("Local stdio").tag("stdio")
|
Button("Use LM Studio Config") {
|
||||||
|
let url = FileManager.default.homeDirectoryForCurrentUser.appending(path: ".lmstudio/mcp.json")
|
||||||
|
loadConfig(url)
|
||||||
|
}
|
||||||
|
if !configPath.isEmpty {
|
||||||
|
Button("Reload") { loadConfig(URL(fileURLWithPath: configPath)) }
|
||||||
|
Button("Edit File") { NSWorkspace.shared.open(URL(fileURLWithPath: configPath)) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if transport == "stdio" {
|
if !profiles.isEmpty {
|
||||||
TextField("Executable path", text: $executable, prompt: Text("/absolute/path/to/server"))
|
Picker("Server", selection: $selectedProfile) {
|
||||||
TextField("Arguments (one per line)", text: $launchArguments, axis: .vertical)
|
Text("Manual connection").tag("")
|
||||||
|
ForEach(profiles.keys.sorted(), id: \.self) { name in Text(name).tag(name) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !configStatus.isEmpty { Text(configStatus).foregroundStyle(.secondary).textSelection(.enabled) }
|
||||||
|
}
|
||||||
|
Section("MCP server") {
|
||||||
|
if let profile {
|
||||||
|
LabeledContent("Transport", value: local ? "Local stdio" : "Streamable HTTP")
|
||||||
|
LabeledContent("Target", value: profile.target)
|
||||||
} else {
|
} else {
|
||||||
TextField("Endpoint", text: $endpoint, prompt: Text("https://server.example/mcp"))
|
Picker("Transport", selection: $transport) {
|
||||||
SecureField("Bearer token (optional)", text: $token)
|
Text("Streamable HTTP").tag("http")
|
||||||
|
Text("Local stdio").tag("stdio")
|
||||||
|
}
|
||||||
|
if transport == "stdio" {
|
||||||
|
TextField("Executable path", text: $executable, prompt: Text("/absolute/path/to/server"))
|
||||||
|
TextField("Arguments (one per line)", text: $launchArguments, axis: .vertical)
|
||||||
|
} else {
|
||||||
|
TextField("Endpoint", text: $endpoint, prompt: Text("https://server.example/mcp"))
|
||||||
|
SecureField("Bearer token (optional)", text: $token)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
HStack {
|
HStack {
|
||||||
Button(transport == "stdio" ? "Start Server and Discover…" : "Discover Tools") {
|
Button(local ? "Start Server and Discover…" : "Discover Tools") {
|
||||||
if transport == "stdio" { confirmLaunch = true }
|
if local { confirmLaunch = true }
|
||||||
else { discover() }
|
else { discover() }
|
||||||
}
|
}
|
||||||
.disabled(busy || (transport == "stdio" ? executable.isEmpty : endpoint.isEmpty))
|
.disabled(busy || target.isEmpty)
|
||||||
if client != nil {
|
if client != nil {
|
||||||
Button("Disconnect") { resetConnection() }.disabled(busy)
|
Button("Disconnect") { resetConnection() }.disabled(busy)
|
||||||
}
|
}
|
||||||
@@ -286,22 +331,48 @@ struct MCPSettings: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
.formStyle(.grouped)
|
.formStyle(.grouped)
|
||||||
|
.fileImporter(isPresented: $importingConfig, allowedContentTypes: [.json]) { result in
|
||||||
|
do { loadConfig(try result.get()) }
|
||||||
|
catch { configStatus = error.localizedDescription }
|
||||||
|
}
|
||||||
|
.onAppear {
|
||||||
|
if !configPath.isEmpty { loadConfig(URL(fileURLWithPath: configPath), disconnect: false) }
|
||||||
|
if !tools.contains(where: { $0.name == name }) { name = tools.first?.name ?? "" }
|
||||||
|
}
|
||||||
|
.onChange(of: selectedProfile) { _, _ in resetConnection() }
|
||||||
.onChange(of: endpoint) { _, _ in resetConnection() }
|
.onChange(of: endpoint) { _, _ in resetConnection() }
|
||||||
.onChange(of: token) { _, _ in resetConnection() }
|
.onChange(of: token) { _, _ in resetConnection() }
|
||||||
.onChange(of: name) { _, _ in arguments = "{}" }
|
.onChange(of: name) { _, _ in arguments = "{}" }
|
||||||
.onChange(of: transport) { _, _ in resetConnection() }
|
.onChange(of: transport) { _, _ in resetConnection() }
|
||||||
.onChange(of: executable) { _, _ in resetConnection() }
|
.onChange(of: executable) { _, _ in resetConnection() }
|
||||||
.onChange(of: launchArguments) { _, _ in resetConnection() }
|
.onChange(of: launchArguments) { _, _ in resetConnection() }
|
||||||
.onDisappear { resetConnection() }
|
.onDisappear { operation?.cancel() }
|
||||||
.confirmationDialog("Start local MCP server?", isPresented: $confirmLaunch, titleVisibility: .visible) {
|
.confirmationDialog("Start local MCP server?", isPresented: $confirmLaunch, titleVisibility: .visible) {
|
||||||
Button("Start and Discover", action: discover)
|
Button("Start and Discover", action: discover)
|
||||||
} message: {
|
} message: {
|
||||||
Text("Launch \(executable) with the listed arguments using your macOS account.")
|
Text("Launch \(target) with its configured arguments using your macOS account.")
|
||||||
}
|
}
|
||||||
.confirmationDialog("Run \(name)?", isPresented: $confirm, titleVisibility: .visible) {
|
.confirmationDialog("Run \(name)?", isPresented: $confirm, titleVisibility: .visible) {
|
||||||
Button("Run Tool", action: invoke)
|
Button("Run Tool", action: invoke)
|
||||||
} message: {
|
} message: {
|
||||||
Text("Send these arguments to \(transport == "stdio" ? executable : endpoint):\n\(arguments.prefix(800))")
|
Text("Send these arguments to \(target):\n\(arguments.prefix(800))")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func loadConfig(_ url: URL, disconnect: Bool = true) {
|
||||||
|
let scoped = url.startAccessingSecurityScopedResource()
|
||||||
|
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||||
|
do {
|
||||||
|
let file = try MCPServerConfiguration.File.read(url)
|
||||||
|
if disconnect { resetConnection() }
|
||||||
|
profiles = file.mcpServers
|
||||||
|
configPath = url.path
|
||||||
|
if profiles[selectedProfile] == nil && (disconnect || !selectedProfile.isEmpty) {
|
||||||
|
selectedProfile = profiles.keys.sorted().first ?? ""
|
||||||
|
}
|
||||||
|
configStatus = "\(profiles.count) custom server(s) loaded from \(url.lastPathComponent)."
|
||||||
|
} catch {
|
||||||
|
configStatus = "Could not read \(url.lastPathComponent): \(error.localizedDescription)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -309,7 +380,9 @@ struct MCPSettings: View {
|
|||||||
run {
|
run {
|
||||||
resetConnection(cancel: false)
|
resetConnection(cancel: false)
|
||||||
let server: any MCPToolClient
|
let server: any MCPToolClient
|
||||||
if transport == "stdio" {
|
if let profile {
|
||||||
|
server = try profile.makeClient()
|
||||||
|
} else if local {
|
||||||
let args = launchArguments.split(whereSeparator: \.isNewline).map(String.init)
|
let args = launchArguments.split(whereSeparator: \.isNewline).map(String.init)
|
||||||
server = try StdioMCPClient(path: executable, arguments: args)
|
server = try StdioMCPClient(path: executable, arguments: args)
|
||||||
} else {
|
} else {
|
||||||
@@ -317,8 +390,8 @@ struct MCPSettings: View {
|
|||||||
}
|
}
|
||||||
let discovered = try await server.listTools()
|
let discovered = try await server.listTools()
|
||||||
try Task.checkCancellation()
|
try Task.checkCancellation()
|
||||||
client = server
|
studio.activeToolset = ActiveToolset(name: profile == nil ? target : selectedProfile,
|
||||||
tools = discovered
|
client: server, tools: discovered)
|
||||||
name = discovered.first?.name ?? ""
|
name = discovered.first?.name ?? ""
|
||||||
result = discovered.isEmpty ? "This server has no exposed tools." : "\(discovered.count) tools discovered."
|
result = discovered.isEmpty ? "This server has no exposed tools." : "\(discovered.count) tools discovered."
|
||||||
}
|
}
|
||||||
@@ -338,8 +411,7 @@ struct MCPSettings: View {
|
|||||||
|
|
||||||
private func resetConnection(cancel: Bool = true) {
|
private func resetConnection(cancel: Bool = true) {
|
||||||
if cancel { operation?.cancel() }
|
if cancel { operation?.cancel() }
|
||||||
client = nil
|
studio.activeToolset = nil
|
||||||
tools = []
|
|
||||||
name = ""
|
name = ""
|
||||||
invokedTool = nil
|
invokedTool = nil
|
||||||
result = ""
|
result = ""
|
||||||
@@ -361,18 +433,19 @@ struct MCPSettings: View {
|
|||||||
actor StdioMCPClient: MCPToolClient {
|
actor StdioMCPClient: MCPToolClient {
|
||||||
private let executable: URL
|
private let executable: URL
|
||||||
private let arguments: [String]
|
private let arguments: [String]
|
||||||
|
private let environment: [String: String]
|
||||||
|
private let workingDirectory: URL?
|
||||||
private var transport: StdioTransport?
|
private var transport: StdioTransport?
|
||||||
private var ready = false
|
private var ready = false
|
||||||
private var busy = false
|
private var busy = false
|
||||||
private static let versions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
|
private static let versions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
|
||||||
|
|
||||||
init(path: String, arguments: [String]) throws {
|
init(path: String, arguments: [String], environment: [String: String] = [:], cwd: String? = nil) throws {
|
||||||
let expanded = (path.trimmingCharacters(in: .whitespacesAndNewlines) as NSString).expandingTildeInPath
|
let launch = try MCPServerConfiguration.resolveCommand(path, environment: environment, cwd: cwd)
|
||||||
guard expanded.hasPrefix("/"), FileManager.default.isExecutableFile(atPath: expanded) else {
|
executable = launch.executable
|
||||||
throw StudioError("Choose the absolute path to a local MCP server executable.")
|
|
||||||
}
|
|
||||||
executable = URL(fileURLWithPath: expanded)
|
|
||||||
self.arguments = arguments
|
self.arguments = arguments
|
||||||
|
self.environment = launch.environment
|
||||||
|
workingDirectory = launch.workingDirectory
|
||||||
}
|
}
|
||||||
|
|
||||||
func disconnect() {
|
func disconnect() {
|
||||||
@@ -385,7 +458,7 @@ actor StdioMCPClient: MCPToolClient {
|
|||||||
busy = true
|
busy = true
|
||||||
defer { busy = false }
|
defer { busy = false }
|
||||||
if !ready {
|
if !ready {
|
||||||
transport = try StdioTransport(executable: executable, arguments: arguments)
|
transport = try StdioTransport(executable: executable, arguments: arguments, environment: environment, cwd: workingDirectory)
|
||||||
do {
|
do {
|
||||||
let info = try await exchange("initialize", params: [
|
let info = try await exchange("initialize", params: [
|
||||||
"protocolVersion": Self.versions[0], "capabilities": [:],
|
"protocolVersion": Self.versions[0], "capabilities": [:],
|
||||||
@@ -466,19 +539,31 @@ private final class StdioTransport: @unchecked Sendable {
|
|||||||
private let child = Process()
|
private let child = Process()
|
||||||
private let input: FileHandle
|
private let input: FileHandle
|
||||||
private let output: FileHandle
|
private let output: FileHandle
|
||||||
|
private let errorOutput: FileHandle
|
||||||
|
private let diagnostics = MCPDiagnostics()
|
||||||
private var buffered = Data()
|
private var buffered = Data()
|
||||||
private let limit = 2_000_000
|
private let limit = 2_000_000
|
||||||
|
|
||||||
init(executable: URL, arguments: [String]) throws {
|
init(executable: URL, arguments: [String], environment: [String: String], cwd: URL?) throws {
|
||||||
let source = Pipe()
|
let source = Pipe()
|
||||||
let sink = Pipe()
|
let sink = Pipe()
|
||||||
|
let errors = Pipe()
|
||||||
|
errorOutput = errors.fileHandleForReading
|
||||||
input = source.fileHandleForWriting
|
input = source.fileHandleForWriting
|
||||||
output = sink.fileHandleForReading
|
output = sink.fileHandleForReading
|
||||||
child.executableURL = executable
|
child.executableURL = executable
|
||||||
child.arguments = arguments
|
child.arguments = arguments
|
||||||
|
child.environment = environment
|
||||||
|
child.currentDirectoryURL = cwd
|
||||||
child.standardInput = source
|
child.standardInput = source
|
||||||
child.standardOutput = sink
|
child.standardOutput = sink
|
||||||
child.standardError = FileHandle.nullDevice
|
child.standardError = errors
|
||||||
|
let diagnostics = diagnostics
|
||||||
|
errorOutput.readabilityHandler = { handle in
|
||||||
|
let data = handle.availableData
|
||||||
|
if data.isEmpty { handle.readabilityHandler = nil }
|
||||||
|
else { diagnostics.append(data) }
|
||||||
|
}
|
||||||
guard fcntl(input.fileDescriptor, F_SETNOSIGPIPE, 1) != -1,
|
guard fcntl(input.fileDescriptor, F_SETNOSIGPIPE, 1) != -1,
|
||||||
fcntl(input.fileDescriptor, F_SETFL, O_NONBLOCK) != -1 else {
|
fcntl(input.fileDescriptor, F_SETFL, O_NONBLOCK) != -1 else {
|
||||||
throw StudioError("Could not configure the local MCP input pipe.")
|
throw StudioError("Could not configure the local MCP input pipe.")
|
||||||
@@ -490,6 +575,7 @@ private final class StdioTransport: @unchecked Sendable {
|
|||||||
if child.isRunning { child.terminate() }
|
if child.isRunning { child.terminate() }
|
||||||
try? input.close()
|
try? input.close()
|
||||||
try? output.close()
|
try? output.close()
|
||||||
|
errorOutput.readabilityHandler = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func exchange(_ payload: Data, id: String?) throws -> Data {
|
func exchange(_ payload: Data, id: String?) throws -> Data {
|
||||||
@@ -524,7 +610,7 @@ private final class StdioTransport: @unchecked Sendable {
|
|||||||
Darwin.read(output.fileDescriptor, $0.baseAddress, $0.count)
|
Darwin.read(output.fileDescriptor, $0.baseAddress, $0.count)
|
||||||
}
|
}
|
||||||
if count < 0 && errno == EINTR { continue }
|
if count < 0 && errno == EINTR { continue }
|
||||||
guard count > 0 else { throw StudioError("The local MCP server closed its output.") }
|
guard count > 0 else { throw diagnostics.error("The local MCP server closed its output.") }
|
||||||
buffered.append(contentsOf: bytes.prefix(count))
|
buffered.append(contentsOf: bytes.prefix(count))
|
||||||
guard buffered.count <= limit else { throw StudioError("The local MCP response is too large.") }
|
guard buffered.count <= limit else { throw StudioError("The local MCP response is too large.") }
|
||||||
}
|
}
|
||||||
@@ -538,7 +624,7 @@ private final class StdioTransport: @unchecked Sendable {
|
|||||||
try wait(input.fileDescriptor, event: Int16(POLLOUT), until: deadline)
|
try wait(input.fileDescriptor, event: Int16(POLLOUT), until: deadline)
|
||||||
let count = Darwin.write(input.fileDescriptor, start.advanced(by: sent), bytes.count - sent)
|
let count = Darwin.write(input.fileDescriptor, start.advanced(by: sent), bytes.count - sent)
|
||||||
if count < 0 && (errno == EINTR || errno == EAGAIN) { continue }
|
if count < 0 && (errno == EINTR || errno == EAGAIN) { continue }
|
||||||
guard count > 0 else { throw StudioError("The local MCP server closed its input.") }
|
guard count > 0 else { throw diagnostics.error("The local MCP server closed its input.") }
|
||||||
sent += count
|
sent += count
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -552,6 +638,118 @@ private final class StdioTransport: @unchecked Sendable {
|
|||||||
if result > 0 { return }
|
if result > 0 { return }
|
||||||
if result < 0 && errno != EINTR { throw StudioError("An MCP pipe error occurred.") }
|
if result < 0 && errno != EINTR { throw StudioError("An MCP pipe error occurred.") }
|
||||||
}
|
}
|
||||||
throw StudioError("The local MCP server timed out.")
|
throw diagnostics.error("The local MCP server timed out.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct MCPServerConfiguration: Decodable {
|
||||||
|
let command: String?
|
||||||
|
let args: [String]?
|
||||||
|
let env: [String: String]?
|
||||||
|
let cwd: String?
|
||||||
|
let url: String?
|
||||||
|
let headers: [String: String]?
|
||||||
|
|
||||||
|
struct File: Decodable {
|
||||||
|
let mcpServers: [String: MCPServerConfiguration]
|
||||||
|
|
||||||
|
static func read(_ url: URL) throws -> Self {
|
||||||
|
let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
|
||||||
|
guard size <= 1_048_576 else { throw StudioError("Choose an MCP configuration under 1 MB.") }
|
||||||
|
return try JSONDecoder().decode(Self.self, from: Data(contentsOf: url))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var target: String { command ?? url ?? "Unconfigured server" }
|
||||||
|
|
||||||
|
func makeClient() throws -> any MCPToolClient {
|
||||||
|
switch (command, url) {
|
||||||
|
case (let command?, nil):
|
||||||
|
let arguments = args ?? []
|
||||||
|
let launcher = Self.projectPython(command, arguments: arguments, environment: env ?? [:]) ?? command
|
||||||
|
if let script = arguments.first(where: { $0.hasPrefix("/") && $0.hasSuffix(".py") }),
|
||||||
|
["python", "python3"].contains(URL(fileURLWithPath: command).lastPathComponent),
|
||||||
|
!FileManager.default.fileExists(atPath: script) {
|
||||||
|
throw StudioError("The configured Python script does not exist: \(script)")
|
||||||
|
}
|
||||||
|
return try StdioMCPClient(path: launcher, arguments: arguments, environment: env ?? [:], cwd: cwd)
|
||||||
|
case (nil, let url?):
|
||||||
|
return try HTTPMCPClient(endpoint: url, headers: headers ?? [:])
|
||||||
|
default:
|
||||||
|
throw StudioError("An MCP server must specify either command or url.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static func projectPython(_ command: String, arguments: [String], environment: [String: String]) -> String? {
|
||||||
|
guard ["python", "python3"].contains(command), environment["PATH"] == nil,
|
||||||
|
let script = arguments.first(where: { $0.hasPrefix("/") && $0.hasSuffix(".py") }) else { return nil }
|
||||||
|
let folder = URL(fileURLWithPath: script).deletingLastPathComponent()
|
||||||
|
return [folder, folder.deletingLastPathComponent()]
|
||||||
|
.map { $0.appending(path: ".venv/bin/" + command).path }
|
||||||
|
.first(where: FileManager.default.isExecutableFile(atPath:))
|
||||||
|
}
|
||||||
|
|
||||||
|
static func resolveCommand(_ command: String, environment: [String: String], cwd: String?) throws
|
||||||
|
-> (executable: URL, environment: [String: String], workingDirectory: URL?) {
|
||||||
|
let command = (command.trimmingCharacters(in: .whitespacesAndNewlines) as NSString).expandingTildeInPath
|
||||||
|
guard !command.isEmpty else { throw StudioError("Enter an MCP executable or command name.") }
|
||||||
|
let manager = FileManager.default
|
||||||
|
let home = manager.homeDirectoryForCurrentUser.path
|
||||||
|
var childEnvironment = ProcessInfo.processInfo.environment.merging(environment) { _, new in new }
|
||||||
|
let common = ["/opt/homebrew/bin", "/usr/local/bin", "/Applications/ServBay/bin",
|
||||||
|
home + "/.local/bin", home + "/.cargo/bin", "/usr/bin", "/bin"]
|
||||||
|
let directories = (childEnvironment["PATH"] ?? "").split(separator: ":").map(String.init) + common
|
||||||
|
childEnvironment["PATH"] = directories.joined(separator: ":")
|
||||||
|
let folder: URL?
|
||||||
|
if let cwd {
|
||||||
|
let path = (cwd as NSString).expandingTildeInPath
|
||||||
|
var isDirectory: ObjCBool = false
|
||||||
|
guard path.hasPrefix("/"), manager.fileExists(atPath: path, isDirectory: &isDirectory), isDirectory.boolValue else {
|
||||||
|
throw StudioError("The configured MCP working directory does not exist.")
|
||||||
|
}
|
||||||
|
folder = URL(fileURLWithPath: path, isDirectory: true)
|
||||||
|
} else {
|
||||||
|
folder = nil
|
||||||
|
}
|
||||||
|
let candidates: [String]
|
||||||
|
if command.hasPrefix("/") {
|
||||||
|
candidates = [command]
|
||||||
|
} else if command.contains("/") {
|
||||||
|
candidates = folder.map { [$0.appending(path: command).path] } ?? []
|
||||||
|
} else {
|
||||||
|
let names = command == "python" ? ["python", "python3"] : [command]
|
||||||
|
candidates = names.flatMap { name in
|
||||||
|
directories.filter { $0.hasPrefix("/") }.map { URL(fileURLWithPath: $0).appending(path: name).path }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
guard let path = candidates.first(where: manager.isExecutableFile(atPath:)) else {
|
||||||
|
throw StudioError("Could not find the MCP executable ‘\(command)’. Check PATH or use an absolute path.")
|
||||||
|
}
|
||||||
|
return (URL(fileURLWithPath: path), childEnvironment, folder)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class MCPDiagnostics: @unchecked Sendable {
|
||||||
|
private let lock = NSLock()
|
||||||
|
private var tail = Data()
|
||||||
|
|
||||||
|
func append(_ bytes: Data) {
|
||||||
|
lock.lock()
|
||||||
|
defer { lock.unlock() }
|
||||||
|
tail.append(bytes)
|
||||||
|
if tail.count > 4096 { tail = Data(tail.suffix(4096)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func error(_ message: String) -> StudioError {
|
||||||
|
lock.lock()
|
||||||
|
defer { lock.unlock() }
|
||||||
|
let context = String(decoding: tail, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
return StudioError(context.isEmpty ? message : message + "\n" + context)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ActiveToolset {
|
||||||
|
let name: String
|
||||||
|
let client: any MCPToolClient
|
||||||
|
let tools: [MCPTool]
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import UniformTypeIdentifiers
|
||||||
|
import AppKit
|
||||||
|
|
||||||
struct CatalogModel: Identifiable, Hashable, Sendable {
|
struct CatalogModel: Identifiable, Hashable, Sendable {
|
||||||
let id: String
|
let id: String
|
||||||
@@ -78,11 +80,40 @@ struct ModelCatalogView: View {
|
|||||||
@AppStorage("mlxOnly") private var mlxOnly = false
|
@AppStorage("mlxOnly") private var mlxOnly = false
|
||||||
@State private var operation: Task<Void, Never>?
|
@State private var operation: Task<Void, Never>?
|
||||||
@State private var active: CatalogModel?
|
@State private var active: CatalogModel?
|
||||||
|
@AppStorage("mlxRegisteredPaths") private var registered = Data()
|
||||||
|
@State private var pickingLibrary = false
|
||||||
|
@State private var libraryStatus = ""
|
||||||
|
|
||||||
|
private var library: [String] { (try? JSONDecoder().decode([String].self, from: registered)) ?? [] }
|
||||||
@State private var removing: CatalogModel?
|
@State private var removing: CatalogModel?
|
||||||
@State private var status = ""
|
@State private var status = ""
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
Form {
|
Form {
|
||||||
|
Section("Model Library") {
|
||||||
|
Button("Register Model Folder…") { pickingLibrary = true }
|
||||||
|
.disabled(studio.running)
|
||||||
|
ForEach(library, id: \.self) { path in
|
||||||
|
HStack {
|
||||||
|
Text(URL(fileURLWithPath: path).lastPathComponent).help(path)
|
||||||
|
Spacer()
|
||||||
|
Button(mlxPath == path && mlxOnly ? "Selected" : "Use Model") {
|
||||||
|
mlxPath = path
|
||||||
|
mlxOnly = true
|
||||||
|
studio.unloadMLX()
|
||||||
|
}
|
||||||
|
.disabled(studio.running || !MLXLibrary.isModel(at: URL(fileURLWithPath: path)) ||
|
||||||
|
(mlxPath == path && mlxOnly))
|
||||||
|
Button("Reveal") {
|
||||||
|
NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
|
||||||
|
}
|
||||||
|
Button("Unregister") {
|
||||||
|
registered = (try? JSONEncoder().encode(library.filter { $0 != path })) ?? Data()
|
||||||
|
}.disabled(studio.running)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !libraryStatus.isEmpty { Text(libraryStatus).foregroundStyle(.secondary) }
|
||||||
|
}
|
||||||
Section("Download for on-device inference") {
|
Section("Download for on-device inference") {
|
||||||
ForEach(CatalogModel.all) { model in
|
ForEach(CatalogModel.all) { model in
|
||||||
let installed = model.installed(at: model.localFolder)
|
let installed = model.installed(at: model.localFolder)
|
||||||
@@ -122,6 +153,18 @@ struct ModelCatalogView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
.formStyle(.grouped)
|
.formStyle(.grouped)
|
||||||
|
.fileImporter(isPresented: $pickingLibrary, allowedContentTypes: [.folder]) { result in
|
||||||
|
do {
|
||||||
|
let url = try result.get().resolvingSymlinksInPath()
|
||||||
|
guard MLXLibrary.isModel(at: url) else {
|
||||||
|
throw StudioError("Choose an MLX folder with config.json and safetensors weights.")
|
||||||
|
}
|
||||||
|
if !library.contains(url.path) {
|
||||||
|
registered = try JSONEncoder().encode(library + [url.path])
|
||||||
|
}
|
||||||
|
libraryStatus = "Registered \(url.lastPathComponent)."
|
||||||
|
} catch { libraryStatus = error.localizedDescription }
|
||||||
|
}
|
||||||
.confirmationDialog("Remove downloaded model?", isPresented: Binding(
|
.confirmationDialog("Remove downloaded model?", isPresented: Binding(
|
||||||
get: { removing != nil }, set: { if !$0 { removing = nil } }
|
get: { removing != nil }, set: { if !$0 { removing = nil } }
|
||||||
), titleVisibility: .visible, presenting: removing) { model in
|
), titleVisibility: .visible, presenting: removing) { model in
|
||||||
@@ -157,3 +200,10 @@ struct ModelCatalogView: View {
|
|||||||
} catch { status = error.localizedDescription }
|
} catch { status = error.localizedDescription }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum MLXLibrary {
|
||||||
|
static func isModel(at url: URL) -> Bool {
|
||||||
|
FileManager.default.fileExists(atPath: url.appending(path: "config.json").path) &&
|
||||||
|
((try? MLXRuntimeLimits.weightBytes(in: url)) ?? 0) > 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -285,8 +285,10 @@ struct CompatibleEndpoint: InferenceProvider {
|
|||||||
let delta: Piece?
|
let delta: Piece?
|
||||||
let finish_reason: String?
|
let finish_reason: String?
|
||||||
}
|
}
|
||||||
|
struct Usage: Decodable { let completion_tokens: Int? }
|
||||||
let error: Failure?
|
let error: Failure?
|
||||||
let choices: [Choice]?
|
let choices: [Choice]?
|
||||||
|
let usage: Usage?
|
||||||
}
|
}
|
||||||
|
|
||||||
func models() async throws -> [String] {
|
func models() async throws -> [String] {
|
||||||
@@ -317,6 +319,9 @@ struct CompatibleEndpoint: InferenceProvider {
|
|||||||
if payload.isEmpty { continue }
|
if payload.isEmpty { continue }
|
||||||
let frame = try JSONDecoder().decode(Frame.self, from: Data(payload.utf8))
|
let frame = try JSONDecoder().decode(Frame.self, from: Data(payload.utf8))
|
||||||
if let error = frame.error { throw StudioError(error.message) }
|
if let error = frame.error { throw StudioError(error.message) }
|
||||||
|
if let tokens = frame.usage?.completion_tokens, tokens >= 0 {
|
||||||
|
continuation.yield(.metrics(ProviderMetrics(tokens: tokens, seconds: 0)))
|
||||||
|
}
|
||||||
guard let choice = frame.choices?.first else { continue }
|
guard let choice = frame.choices?.first else { continue }
|
||||||
if choice.finish_reason == "tool_calls" || !(choice.delta?.tool_calls ?? []).isEmpty {
|
if choice.finish_reason == "tool_calls" || !(choice.delta?.tool_calls ?? []).isEmpty {
|
||||||
continuation.yield(.committed)
|
continuation.yield(.committed)
|
||||||
|
|||||||
+101
-3
@@ -6,6 +6,22 @@ struct Conversation: Identifiable {
|
|||||||
let title: String
|
let title: String
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct WorkspaceSnippet: Identifiable {
|
||||||
|
enum Kind: String, CaseIterable, Identifiable {
|
||||||
|
case skill = "Skill"
|
||||||
|
case context = "Context"
|
||||||
|
case prompt = "Prompt"
|
||||||
|
case webClip = "Web Clip"
|
||||||
|
|
||||||
|
var id: Self { self }
|
||||||
|
}
|
||||||
|
|
||||||
|
let id: UUID
|
||||||
|
let kind: Kind
|
||||||
|
let title: String
|
||||||
|
let content: String
|
||||||
|
}
|
||||||
|
|
||||||
final class Store {
|
final class Store {
|
||||||
private let db: OpaquePointer
|
private let db: OpaquePointer
|
||||||
private let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
|
private let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
|
||||||
@@ -24,6 +40,12 @@ final class Store {
|
|||||||
CREATE TABLE IF NOT EXISTS chats(
|
CREATE TABLE IF NOT EXISTS chats(
|
||||||
id TEXT PRIMARY KEY, title TEXT NOT NULL
|
id TEXT PRIMARY KEY, title TEXT NOT NULL
|
||||||
);
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS knowledge_stacks(
|
||||||
|
id TEXT PRIMARY KEY REFERENCES chats(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS workspace_snippets(
|
||||||
|
id TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL
|
||||||
|
);
|
||||||
CREATE TABLE IF NOT EXISTS messages(
|
CREATE TABLE IF NOT EXISTS messages(
|
||||||
id TEXT PRIMARY KEY, chat TEXT NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
id TEXT PRIMARY KEY, chat TEXT NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
role TEXT NOT NULL, content TEXT NOT NULL, thinking TEXT NOT NULL, backend TEXT NOT NULL
|
role TEXT NOT NULL, content TEXT NOT NULL, thinking TEXT NOT NULL, backend TEXT NOT NULL
|
||||||
@@ -50,7 +72,7 @@ final class Store {
|
|||||||
deinit { sqlite3_close(db) }
|
deinit { sqlite3_close(db) }
|
||||||
|
|
||||||
func conversations() throws -> [Conversation] {
|
func conversations() throws -> [Conversation] {
|
||||||
try query("SELECT id,title FROM chats ORDER BY rowid DESC") {
|
try query("SELECT id,title FROM chats WHERE id NOT IN (SELECT id FROM knowledge_stacks) ORDER BY rowid DESC") {
|
||||||
Conversation(id: try uuid($0, 0), title: string($0, 1))
|
Conversation(id: try uuid($0, 0), title: string($0, 1))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,8 +82,10 @@ final class Store {
|
|||||||
guard !term.isEmpty else { return try conversations() }
|
guard !term.isEmpty else { return try conversations() }
|
||||||
return try query("""
|
return try query("""
|
||||||
SELECT c.id, c.title FROM chats c
|
SELECT c.id, c.title FROM chats c
|
||||||
WHERE instr(lower(c.title), lower(?)) > 0 OR EXISTS (
|
WHERE c.id NOT IN (SELECT id FROM knowledge_stacks) AND (
|
||||||
SELECT 1 FROM messages m WHERE m.chat=c.id AND instr(lower(m.content), lower(?)) > 0
|
instr(lower(c.title), lower(?)) > 0 OR EXISTS (
|
||||||
|
SELECT 1 FROM messages m WHERE m.chat=c.id AND instr(lower(m.content), lower(?)) > 0
|
||||||
|
)
|
||||||
)
|
)
|
||||||
ORDER BY c.rowid DESC
|
ORDER BY c.rowid DESC
|
||||||
""", [term, term]) {
|
""", [term, term]) {
|
||||||
@@ -69,6 +93,45 @@ final class Store {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func knowledgeStacks() throws -> [Conversation] {
|
||||||
|
try query("SELECT c.id,c.title FROM chats c JOIN knowledge_stacks s ON s.id=c.id ORDER BY c.rowid DESC") {
|
||||||
|
Conversation(id: try uuid($0, 0), title: string($0, 1))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func createKnowledgeStack(title: String) throws -> Conversation {
|
||||||
|
try execute("BEGIN IMMEDIATE")
|
||||||
|
do {
|
||||||
|
let entry = try create(title: title)
|
||||||
|
try mutate("INSERT INTO knowledge_stacks(id) VALUES(?)", [entry.id.uuidString])
|
||||||
|
try execute("COMMIT")
|
||||||
|
return entry
|
||||||
|
} catch {
|
||||||
|
try? execute("ROLLBACK")
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func snippets() throws -> [WorkspaceSnippet] {
|
||||||
|
try query("SELECT id,kind,title,content FROM workspace_snippets ORDER BY rowid DESC") {
|
||||||
|
guard let kind = WorkspaceSnippet.Kind(rawValue: string($0, 1)) else {
|
||||||
|
throw StudioError("Invalid workspace resource.")
|
||||||
|
}
|
||||||
|
return WorkspaceSnippet(id: try uuid($0, 0), kind: kind, title: string($0, 2), content: string($0, 3))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func saveSnippet(id: UUID, kind: WorkspaceSnippet.Kind, title: String, content: String) throws {
|
||||||
|
try mutate("""
|
||||||
|
INSERT INTO workspace_snippets(id,kind,title,content) VALUES(?,?,?,?)
|
||||||
|
ON CONFLICT(id) DO UPDATE SET kind=excluded.kind, title=excluded.title, content=excluded.content
|
||||||
|
""", [id.uuidString, kind.rawValue, title, content])
|
||||||
|
}
|
||||||
|
|
||||||
|
func deleteSnippet(_ id: UUID) throws {
|
||||||
|
try mutate("DELETE FROM workspace_snippets WHERE id=?", [id.uuidString])
|
||||||
|
}
|
||||||
|
|
||||||
func rename(_ id: UUID, title: String) throws {
|
func rename(_ id: UUID, title: String) throws {
|
||||||
try mutate("UPDATE chats SET title=? WHERE id=?", [title, id.uuidString])
|
try mutate("UPDATE chats SET title=? WHERE id=?", [title, id.uuidString])
|
||||||
}
|
}
|
||||||
@@ -180,6 +243,41 @@ final class Store {
|
|||||||
return excerpts
|
return excerpts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func exportWorkspace(to url: URL) throws {
|
||||||
|
guard !FileManager.default.fileExists(atPath: url.path) else {
|
||||||
|
throw StudioError("Choose a new filename for the workspace backup.")
|
||||||
|
}
|
||||||
|
try mutate("VACUUM INTO ?", [url.path])
|
||||||
|
}
|
||||||
|
|
||||||
|
func restoreWorkspace(from url: URL) throws {
|
||||||
|
var input: OpaquePointer?
|
||||||
|
let opened = sqlite3_open_v2(url.path, &input, SQLITE_OPEN_READONLY, nil)
|
||||||
|
guard opened == SQLITE_OK, let input else {
|
||||||
|
if let input { sqlite3_close(input) }
|
||||||
|
throw StudioError("The workspace backup could not be opened.")
|
||||||
|
}
|
||||||
|
defer { sqlite3_close(input) }
|
||||||
|
let check = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name IN ('chats','messages','documents','workspace_snippets','knowledge_stacks')"
|
||||||
|
var prepared: OpaquePointer?
|
||||||
|
guard sqlite3_prepare_v2(input, check, -1, &prepared, nil) == SQLITE_OK, let prepared else {
|
||||||
|
throw StudioError("The selected file is not an AI Studio workspace backup.")
|
||||||
|
}
|
||||||
|
let valid = sqlite3_step(prepared) == SQLITE_ROW && sqlite3_column_int(prepared, 0) == 5
|
||||||
|
sqlite3_finalize(prepared)
|
||||||
|
guard valid else { throw StudioError("The selected file is not an AI Studio workspace backup.") }
|
||||||
|
var checkHandle: OpaquePointer?
|
||||||
|
guard sqlite3_prepare_v2(input, "PRAGMA quick_check", -1, &checkHandle, nil) == SQLITE_OK,
|
||||||
|
let integrity = checkHandle else { throw StudioError("Could not verify backup integrity.") }
|
||||||
|
let healthy = sqlite3_step(integrity) == SQLITE_ROW && string(integrity, 0) == "ok"
|
||||||
|
sqlite3_finalize(integrity)
|
||||||
|
guard healthy else { throw StudioError("The selected backup did not pass SQLite integrity checks.") }
|
||||||
|
guard let backup = sqlite3_backup_init(db, "main", input, "main") else { throw failure }
|
||||||
|
let step = sqlite3_backup_step(backup, -1)
|
||||||
|
let finish = sqlite3_backup_finish(backup)
|
||||||
|
guard step == SQLITE_DONE, finish == SQLITE_OK else { throw failure }
|
||||||
|
}
|
||||||
|
|
||||||
private func execute(_ sql: String) throws {
|
private func execute(_ sql: String) throws {
|
||||||
guard sqlite3_exec(db, sql, nil, nil, nil) == SQLITE_OK else { throw failure }
|
guard sqlite3_exec(db, sql, nil, nil, nil) == SQLITE_OK else { throw failure }
|
||||||
}
|
}
|
||||||
|
|||||||
+120
-3
@@ -19,6 +19,14 @@ final class StudioModel: ObservableObject {
|
|||||||
@Published private(set) var managing = false
|
@Published private(set) var managing = false
|
||||||
@Published private(set) var running = false
|
@Published private(set) var running = false
|
||||||
@Published private(set) var measurements: [GenerationMeasurement] = []
|
@Published private(set) var measurements: [GenerationMeasurement] = []
|
||||||
|
@Published private(set) var knowledgeStacks: [Conversation] = []
|
||||||
|
@Published private(set) var snippets: [WorkspaceSnippet] = []
|
||||||
|
@Published var activeToolset: ActiveToolset?
|
||||||
|
@Published var activeStack: UUID?
|
||||||
|
@Published var activeSkill: UUID?
|
||||||
|
@Published var activeContext: UUID?
|
||||||
|
@Published var activeWebClip: UUID?
|
||||||
|
@Published private(set) var workspaceStatus = ""
|
||||||
@Published var selected: UUID? {
|
@Published var selected: UUID? {
|
||||||
didSet { if selected != oldValue { loadMessages() } }
|
didSet { if selected != oldValue { loadMessages() } }
|
||||||
}
|
}
|
||||||
@@ -35,11 +43,16 @@ final class StudioModel: ObservableObject {
|
|||||||
defer { launching = false }
|
defer { launching = false }
|
||||||
reloadRuntimeSettings()
|
reloadRuntimeSettings()
|
||||||
guard store == nil else { return }
|
guard store == nil else { return }
|
||||||
|
if let history = UserDefaults.standard.data(forKey: GenerationMeasurement.key),
|
||||||
|
let saved = try? JSONDecoder().decode([GenerationMeasurement].self, from: history) {
|
||||||
|
measurements = Array(saved.prefix(50))
|
||||||
|
}
|
||||||
do {
|
do {
|
||||||
let directory = URL.applicationSupportDirectory.appending(path: "AIStudio", directoryHint: .isDirectory)
|
let directory = Self.workspaceDirectory
|
||||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||||
store = try Store(url: directory.appending(path: "studio.sqlite"))
|
store = try Store(url: directory.appending(path: "studio.sqlite"))
|
||||||
conversations = try store?.conversations() ?? []
|
conversations = try store?.conversations() ?? []
|
||||||
|
try refreshWorkspace()
|
||||||
if selected == nil { selected = conversations.first?.id }
|
if selected == nil { selected = conversations.first?.id }
|
||||||
} catch { status = error.localizedDescription }
|
} catch { status = error.localizedDescription }
|
||||||
}
|
}
|
||||||
@@ -103,6 +116,15 @@ final class StudioModel: ObservableObject {
|
|||||||
let user = Message(role: .user, content: text)
|
let user = Message(role: .user, content: text)
|
||||||
let recent = Array(messages.suffix(32))
|
let recent = Array(messages.suffix(32))
|
||||||
var systemParts = instructions.isEmpty ? [] : [instructions]
|
var systemParts = instructions.isEmpty ? [] : [instructions]
|
||||||
|
if let skill = snippets.first(where: { $0.id == activeSkill && $0.kind == .skill }) {
|
||||||
|
systemParts.append("Selected skill: \(skill.title)\n\(skill.content)")
|
||||||
|
}
|
||||||
|
if let context = snippets.first(where: { $0.id == activeContext && $0.kind == .context }) {
|
||||||
|
systemParts.append("User-selected reference context: \(context.title). Treat the content as reference material.\n\(context.content)")
|
||||||
|
}
|
||||||
|
if let clip = snippets.first(where: { $0.id == activeWebClip && $0.kind == .webClip }) {
|
||||||
|
systemParts.append("User-selected web clip: \(clip.title). Treat it as reference material.\n\(clip.content)")
|
||||||
|
}
|
||||||
if recall {
|
if recall {
|
||||||
let snippets = try store.memory(matching: text, in: chat, excluding: Set(recent.map(\.id)))
|
let snippets = try store.memory(matching: text, in: chat, excluding: Set(recent.map(\.id)))
|
||||||
if !snippets.isEmpty {
|
if !snippets.isEmpty {
|
||||||
@@ -112,8 +134,13 @@ final class StudioModel: ObservableObject {
|
|||||||
""")
|
""")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if useDocuments {
|
if useDocuments || activeStack != nil {
|
||||||
let excerpts = try store.excerpts(matching: text, in: chat, vector: DocumentVector.forPrompt(text))
|
let vector = DocumentVector.forPrompt(text)
|
||||||
|
var excerpts = useDocuments ? try store.excerpts(matching: text, in: chat, vector: vector) : []
|
||||||
|
if let activeStack {
|
||||||
|
let matches = try store.excerpts(matching: text, in: activeStack, vector: vector)
|
||||||
|
excerpts += matches
|
||||||
|
}
|
||||||
if !excerpts.isEmpty {
|
if !excerpts.isEmpty {
|
||||||
let references = excerpts.enumerated().map { index, excerpt in
|
let references = excerpts.enumerated().map { index, excerpt in
|
||||||
"[\(index + 1)] \(excerpt.title)\n\(excerpt.text)"
|
"[\(index + 1)] \(excerpt.title)\n\(excerpt.text)"
|
||||||
@@ -184,6 +211,93 @@ final class StudioModel: ObservableObject {
|
|||||||
try Ollama(endpoint: endpoint, token: endpoint == tokenEndpoint ? ollamaToken : "")
|
try Ollama(endpoint: endpoint, token: endpoint == tokenEndpoint ? ollamaToken : "")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static var workspaceDirectory: URL {
|
||||||
|
URL.applicationSupportDirectory.appending(path: "AIStudio", directoryHint: .isDirectory)
|
||||||
|
}
|
||||||
|
|
||||||
|
func exportWorkspace(to url: URL) throws {
|
||||||
|
try database().exportWorkspace(to: url)
|
||||||
|
}
|
||||||
|
|
||||||
|
func restoreWorkspace(from url: URL) throws {
|
||||||
|
guard !running, !importingDocument else { throw StudioError("Wait for the current operation to finish.") }
|
||||||
|
try database().restoreWorkspace(from: url)
|
||||||
|
conversations = try database().conversations()
|
||||||
|
try refreshWorkspace()
|
||||||
|
selected = nil
|
||||||
|
selected = conversations.first?.id
|
||||||
|
activeStack = nil
|
||||||
|
activeSkill = nil
|
||||||
|
activeContext = nil
|
||||||
|
activeWebClip = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func refreshWorkspace() throws {
|
||||||
|
let store = try database()
|
||||||
|
knowledgeStacks = try store.knowledgeStacks()
|
||||||
|
snippets = try store.snippets()
|
||||||
|
}
|
||||||
|
|
||||||
|
func createStack(_ title: String) -> UUID? {
|
||||||
|
do {
|
||||||
|
let stack = try database().createKnowledgeStack(title: String(title.prefix(100)))
|
||||||
|
try refreshWorkspace()
|
||||||
|
workspaceStatus = ""
|
||||||
|
return stack.id
|
||||||
|
} catch { workspaceStatus = error.localizedDescription; return nil }
|
||||||
|
}
|
||||||
|
|
||||||
|
func stackDocuments(_ id: UUID) -> [LibraryDocument] {
|
||||||
|
(try? store?.documents(in: id)) ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
func deleteStack(_ id: UUID) {
|
||||||
|
do {
|
||||||
|
try database().delete(id)
|
||||||
|
if activeStack == id { activeStack = nil }
|
||||||
|
try refreshWorkspace()
|
||||||
|
workspaceStatus = ""
|
||||||
|
} catch { workspaceStatus = error.localizedDescription }
|
||||||
|
}
|
||||||
|
|
||||||
|
func deleteStackDocument(_ document: LibraryDocument, in id: UUID) {
|
||||||
|
do {
|
||||||
|
try database().deleteDocument(document.id, in: id)
|
||||||
|
workspaceStatus = ""
|
||||||
|
} catch { workspaceStatus = error.localizedDescription }
|
||||||
|
}
|
||||||
|
|
||||||
|
func importStackDocument(_ url: URL, in id: UUID) async {
|
||||||
|
do {
|
||||||
|
let (chunks, vectors) = try await Task.detached(priority: .userInitiated) {
|
||||||
|
let chunks = try LibraryImport.chunks(at: url)
|
||||||
|
return (chunks, DocumentVector.forChunks(chunks))
|
||||||
|
}.value
|
||||||
|
try Task.checkCancellation()
|
||||||
|
try database().addDocument(title: url.lastPathComponent, chunks: chunks, vectors: vectors, in: id)
|
||||||
|
workspaceStatus = ""
|
||||||
|
} catch { workspaceStatus = error.localizedDescription }
|
||||||
|
}
|
||||||
|
|
||||||
|
func saveSnippet(id: UUID, kind: WorkspaceSnippet.Kind, title: String, content: String) {
|
||||||
|
do {
|
||||||
|
try database().saveSnippet(id: id, kind: kind, title: String(title.prefix(100)), content: String(content.prefix(12000)))
|
||||||
|
try refreshWorkspace()
|
||||||
|
workspaceStatus = ""
|
||||||
|
} catch { workspaceStatus = error.localizedDescription }
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeSnippet(_ id: UUID) {
|
||||||
|
do {
|
||||||
|
try database().deleteSnippet(id)
|
||||||
|
if activeSkill == id { activeSkill = nil }
|
||||||
|
if activeContext == id { activeContext = nil }
|
||||||
|
if activeWebClip == id { activeWebClip = nil }
|
||||||
|
try refreshWorkspace()
|
||||||
|
workspaceStatus = ""
|
||||||
|
} catch { workspaceStatus = error.localizedDescription }
|
||||||
|
}
|
||||||
|
|
||||||
func importDocument(_ url: URL) async {
|
func importDocument(_ url: URL) async {
|
||||||
guard !importingDocument, let chat = selected else { return }
|
guard !importingDocument, let chat = selected else { return }
|
||||||
importingDocument = true
|
importingDocument = true
|
||||||
@@ -318,6 +432,9 @@ final class StudioModel: ObservableObject {
|
|||||||
provider: provider, outcome: Task.isCancelled ? "Stopped" : (status.isEmpty ? "Complete" : "Failed")
|
provider: provider, outcome: Task.isCancelled ? "Stopped" : (status.isEmpty ? "Complete" : "Failed")
|
||||||
), at: 0)
|
), at: 0)
|
||||||
if measurements.count > 50 { measurements.removeLast() }
|
if measurements.count > 50 { measurements.removeLast() }
|
||||||
|
if let history = try? JSONEncoder().encode(measurements) {
|
||||||
|
UserDefaults.standard.set(history, forKey: GenerationMeasurement.key)
|
||||||
|
}
|
||||||
if var reply = partial, !reply.content.isEmpty || !reply.thinking.isEmpty {
|
if var reply = partial, !reply.content.isEmpty || !reply.thinking.isEmpty {
|
||||||
if !status.isEmpty { reply.backend += " · Interrupted" }
|
if !status.isEmpty { reply.backend += " · Interrupted" }
|
||||||
do {
|
do {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import XCTest
|
import XCTest
|
||||||
|
import AppKit
|
||||||
@testable import AIStudio
|
@testable import AIStudio
|
||||||
|
|
||||||
final class StudioTests: XCTestCase {
|
final class StudioTests: XCTestCase {
|
||||||
@@ -475,3 +476,81 @@ final class DesktopRuntimeTests: XCTestCase {
|
|||||||
XCTAssertEqual(try MLXRuntimeLimits.weightBytes(in: directory), 50)
|
XCTAssertEqual(try MLXRuntimeLimits.weightBytes(in: directory), 50)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final class CustomMCPConfigurationTests: XCTestCase {
|
||||||
|
func testCustomProfileParsesEnvAndHeaders() throws {
|
||||||
|
let configuration = try JSONDecoder().decode(MCPServerConfiguration.File.self, from: Data(#"""
|
||||||
|
{"mcpServers":{"remote":{"url":"https://example.com/mcp","headers":{"X-Example":"token"}},
|
||||||
|
"local":{"command":"sh","args":["one","two with spaces"],"env":{"TEST_MCP_SETTING":"example"}}}}
|
||||||
|
"""#.utf8))
|
||||||
|
let local = try XCTUnwrap(configuration.mcpServers["local"])
|
||||||
|
XCTAssertEqual(local.args, ["one", "two with spaces"])
|
||||||
|
let launch = try MCPServerConfiguration.resolveCommand("sh", environment: local.env ?? [:], cwd: "/private/tmp")
|
||||||
|
XCTAssertTrue(launch.executable.path.hasSuffix("/sh"))
|
||||||
|
XCTAssertEqual(launch.environment["TEST_MCP_SETTING"], "example")
|
||||||
|
XCTAssertEqual(launch.workingDirectory?.path, "/private/tmp")
|
||||||
|
XCTAssertNoThrow(try configuration.mcpServers["remote"]?.makeClient())
|
||||||
|
XCTAssertThrowsError(try HTTPMCPClient(endpoint: "https://example.com/mcp", headers: ["Host": "elsewhere"]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testInstalledKnowledgeServerDiscovery() async throws {
|
||||||
|
guard let path = ProcessInfo.processInfo.environment["AISTUDIO_TEST_REAL_MCP_CONFIG"] else {
|
||||||
|
throw XCTSkip("Set AISTUDIO_TEST_REAL_MCP_CONFIG to the installed configuration.")
|
||||||
|
}
|
||||||
|
let configuration = try MCPServerConfiguration.File.read(URL(fileURLWithPath: path))
|
||||||
|
let profile = try XCTUnwrap(configuration.mcpServers["local-knowledge"])
|
||||||
|
let client = try profile.makeClient()
|
||||||
|
let tools = try await client.listTools()
|
||||||
|
XCTAssertTrue(tools.contains { $0.name == "search_knowledge" })
|
||||||
|
}
|
||||||
|
|
||||||
|
func testGenerationMeasurementsRoundTripAndCharacterRate() throws {
|
||||||
|
let run = GenerationMeasurement(backend: "Fixture", firstOutput: 1, seconds: 3, characters: 40,
|
||||||
|
provider: ProviderMetrics(tokens: 7, seconds: 0), outcome: "Complete")
|
||||||
|
let copy = try JSONDecoder().decode(GenerationMeasurement.self, from: JSONEncoder().encode(run))
|
||||||
|
XCTAssertEqual(copy.id, run.id)
|
||||||
|
XCTAssertEqual(copy.charactersPerSecond, 20)
|
||||||
|
XCTAssertEqual(copy.provider?.tokens, 7)
|
||||||
|
XCTAssertNil(copy.provider?.tokensPerSecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final class WorkspaceLibraryTests: XCTestCase {
|
||||||
|
func testStackIsReusableAndBackupRestoresWorkspaceResources() throws {
|
||||||
|
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
||||||
|
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||||
|
defer { try? FileManager.default.removeItem(at: folder) }
|
||||||
|
let store = try Store(url: folder.appending(path: "workspace.sqlite"))
|
||||||
|
let backup = folder.appending(path: "backup.sqlite")
|
||||||
|
let stack = try store.createKnowledgeStack(title: "Customer Help")
|
||||||
|
let chat = try store.create(title: "Chat")
|
||||||
|
let key = UUID()
|
||||||
|
try store.addDocument(title: "Reference", chunks: ["This answer describes tides."], in: stack.id)
|
||||||
|
try store.saveSnippet(id: key, kind: .prompt, title: "Reusable Prompt", content: "Explain tides")
|
||||||
|
try store.exportWorkspace(to: backup)
|
||||||
|
XCTAssertEqual(try store.conversations().map(\.id), [chat.id])
|
||||||
|
XCTAssertTrue(try store.searchConversations("Customer Help").isEmpty)
|
||||||
|
try store.delete(stack.id)
|
||||||
|
try store.deleteSnippet(key)
|
||||||
|
try store.restoreWorkspace(from: backup)
|
||||||
|
XCTAssertEqual(try store.knowledgeStacks().map(\.id), [stack.id])
|
||||||
|
XCTAssertEqual(try store.excerpts(matching: "tides", in: stack.id).first?.title, "Reference")
|
||||||
|
XCTAssertEqual(try store.snippets().first?.content, "Explain tides")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testReturnSendsWithoutInterruptingNewlinesOrInputComposition() {
|
||||||
|
XCTAssertTrue(ChatComposerInput.sendsReturn(modifiers: [], marked: false))
|
||||||
|
XCTAssertFalse(ChatComposerInput.sendsReturn(modifiers: .shift, marked: false))
|
||||||
|
XCTAssertFalse(ChatComposerInput.sendsReturn(modifiers: .option, marked: false))
|
||||||
|
XCTAssertFalse(ChatComposerInput.sendsReturn(modifiers: [], marked: true))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testWebClipExtractsStaticText() throws {
|
||||||
|
let content = WebClipCapture.plainText("""
|
||||||
|
<head><title>Hidden</title></head><script>ignore()</script><h1>Title</h1><p>Two & three</p>
|
||||||
|
""")
|
||||||
|
XCTAssertEqual(content, "Title\nTwo & three")
|
||||||
|
XCTAssertThrowsError(try WebClipCapture.url("file:///etc/hosts"))
|
||||||
|
XCTAssertNoThrow(try WebClipCapture.url("https://example.com"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user