new features

This commit is contained in:
Mark Gregory
2026-11-18 08:32:12 +00:00
parent 8061981ccb
commit 8467977403
6 changed files with 383 additions and 16 deletions
+198 -3
View File
@@ -3,8 +3,19 @@ import AppKit
import Charts
import UniformTypeIdentifiers
import WebKit
import JavaScriptCore
@main
enum StudioEntryPoint {
@MainActor static func main() {
let arguments = CommandLine.arguments
if arguments.count == 3, arguments[1] == "--javascript-sandbox" {
exit(JavaScriptSandbox.evaluate(arguments[2]))
}
AIStudioApp.main()
}
}
struct AIStudioApp: App {
@StateObject private var studio = StudioModel()
@AppStorage("studioCustomThemes") private var customThemesData = Data()
@@ -83,6 +94,10 @@ struct ChatView: View {
@AppStorage("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1"
@AppStorage("compatibleModel") private var compatibleModel = ""
@AppStorage("recall") private var recall = true
@AppStorage("chatRAGEnabled") private var ragEnabled = true
@AppStorage("lmStudioPluginEndpoint") private var pluginEndpoint = ""
@AppStorage("lmStudioPluginIDs") private var pluginIDs = ""
@AppStorage("lmStudioPluginsEnabled") private var pluginsEnabled = false
@AppStorage("globalPromptMode") private var promptMode = PromptMode.standard
@AppStorage("globalCustomPrompt") private var customPrompt = ""
@AppStorage(GenerationSettings.key) private var generationSettings = Data()
@@ -442,7 +457,7 @@ struct ChatView: View {
private var composer: some View {
VStack(alignment: .leading, spacing: 8) {
if !studio.documents.isEmpty {
if ragEnabled && !studio.documents.isEmpty {
Toggle(chatModel.backend == .mlx ? "Include matching document excerpts" :
"Send matching document excerpts to \(backendName)", isOn: documentExcerptsEnabled)
.font(.caption)
@@ -502,6 +517,9 @@ struct ChatView: View {
.buttonStyle(.bordered)
.help(studio.activeToolsets.map { $0.toolset.name }.joined(separator: ", "))
resourceMenu(for: studio)
Toggle("RAG", isOn: $ragEnabled)
.toggleStyle(.button)
.help("Retrieve matching documents and knowledge stack content")
Spacer()
}
HStack(spacing: 10) {
@@ -591,7 +609,9 @@ struct ChatView: View {
thinking: choice.thinkingMode(thinking), failover: failover,
mlxOnly: choice.backend == .mlx, compatible: choice.backend == .compatible,
recall: recall, useDocuments: useDocuments, instructions: promptMode.instructions(custom: customPrompt),
settings: GenerationSettings.read(generationSettings), agents: selectedAgents, agentTools: allowAgentTools)
settings: GenerationSettings.read(generationSettings), agents: selectedAgents, agentTools: allowAgentTools,
ragEnabled: ragEnabled, lmStudioPlugins: pluginsEnabled && pluginEndpoint == compatibleEndpoint
? CompatibleEndpoint.pluginIDs(pluginIDs) : [])
}
}
@@ -872,7 +892,7 @@ struct MessageView: View {
}
if !message.content.isEmpty {
if message.role == .assistant && renderMarkdown {
ChatMarkdown(text: message.content)
ChatMarkdown(text: message.content, canRunJavaScript: !streaming)
} else {
Text(message.content).textSelection(.enabled)
}
@@ -1154,6 +1174,8 @@ private func copyChatText(_ text: String) {
struct ChatMarkdown: View {
let text: String
var canRunJavaScript = false
@State private var sandboxSource: String?
@AppStorage("studioCodeTheme") private var codeTheme = StudioTheme.system
@Environment(\.colorScheme) private var currentScheme
@@ -1202,6 +1224,12 @@ struct ChatMarkdown: View {
Text(language.isEmpty ? "Code" : String(language.prefix(60)))
.font(.caption).foregroundStyle(.secondary)
Spacer()
if canRunJavaScript && ["js", "javascript"].contains(language.lowercased()) {
Button("Open in JavaScript Sandbox", systemImage: "play") {
sandboxSource = block.content
}
.buttonStyle(.borderless)
}
Button("Copy Code", systemImage: "doc.on.doc") { copyChatText(block.content) }
.buttonStyle(.borderless)
}
@@ -1219,6 +1247,154 @@ struct ChatMarkdown: View {
}
}
}
.sheet(isPresented: Binding(
get: { sandboxSource != nil },
set: { if !$0 { sandboxSource = nil } }
)) {
JavaScriptSandboxView(source: sandboxSource ?? "")
.frame(minWidth: 520, minHeight: 400)
}
}
}
enum JavaScriptSandbox {
static func run(_ source: String) throws -> String {
guard source.utf8.count <= 32_768 else { throw StudioError("JavaScript is limited to 32 KB.") }
guard let executable = Bundle.main.executableURL else { throw StudioError("Sandbox executable is unavailable.") }
let child = Process()
let output = Pipe()
child.executableURL = executable
child.arguments = ["--javascript-sandbox", Data(source.utf8).base64EncodedString()]
child.environment = [:]
child.standardInput = FileHandle.nullDevice
child.standardOutput = output
child.standardError = FileHandle.nullDevice
try child.run()
let deadline = DispatchWorkItem {
if child.isRunning { kill(child.processIdentifier, SIGKILL) }
}
DispatchQueue.global().asyncAfter(deadline: .now() + 5, execute: deadline)
defer { deadline.cancel() }
let data = output.fileHandleForReading.readDataToEndOfFile()
child.waitUntilExit()
if child.terminationReason == .uncaughtSignal {
throw StudioError("JavaScript exceeded the time limit or the sandbox stopped unexpectedly.")
}
let result = String(decoding: data, as: UTF8.self)
guard child.terminationStatus == 0 else {
throw StudioError(result.isEmpty ? "Could not run JavaScript." : result)
}
return result
}
static func evaluate(_ encoded: String) -> Int32 {
guard let data = Data(base64Encoded: encoded), data.count <= 32_768,
let source = String(data: data, encoding: .utf8), let context = JSContext() else { return 1 }
// Use a fresh JavaScriptCore context with no host functions or native objects exposed.
let runner = context.evaluateScript(#"""
(source => {
let output = "";
const format = value => {
if (typeof value === "string") return value;
try { return JSON.stringify(value) ?? String(value); }
catch { return String(value); }
};
const log = (...values) => {
for (const value of values) {
if (output.length >= 8000) break;
output += format(value).slice(0, 8000 - output.length) + " ";
}
if (output.length < 8000) output += "\n";
};
globalThis.console = { log, info: log, warn: log, error: log };
try {
const value = (0, eval)(source);
if (value !== undefined) log(value);
return [true, output.trimEnd().slice(0, 8000)];
} catch (error) {
return [false, (output + String(error)).slice(0, 8000)];
}
})
"""#)
guard let result = runner?.call(withArguments: [source]), result.isObject,
let text = result.atIndex(1)?.toString() else { return 1 }
FileHandle.standardOutput.write(Data(text.utf8))
return result.atIndex(0)?.toBool() == true ? 0 : 1
}
}
private struct JavaScriptSandboxView: View {
@Environment(\.dismiss) private var dismiss
var studio: StudioModel?
@State private var source: String
@State private var output = ""
@State private var error = ""
@State private var running = false
init(studio: StudioModel? = nil, source: String = "") {
self.studio = studio
_source = State(initialValue: source)
}
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack {
Text("JavaScript Sandbox").font(.headline)
Spacer()
if studio == nil { Button("Done") { dismiss() } }
}
Text("Run JavaScript with console output and a five-second time limit.")
.foregroundStyle(.secondary)
TextEditor(text: $source)
.font(.system(.body, design: .monospaced))
.accessibilityLabel("JavaScript source")
.frame(minHeight: 130)
.border(.quaternary)
.disabled(running)
.onChange(of: source) {
output = ""
error = ""
}
HStack {
Button("Run JavaScript", systemImage: "play", action: run)
.disabled(running || source.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
if running { ProgressView().controlSize(.small) }
Spacer()
if let studio, !output.isEmpty {
Button("Attach Output to Chat") {
studio.attachToolResult(name: "JavaScript Sandbox", output: output)
dismiss()
}
.disabled(studio.running)
}
}
ScrollView {
Text(error.isEmpty ? output : error)
.font(.system(.body, design: .monospaced))
.foregroundStyle(error.isEmpty ? Color.primary : Color.red)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(minHeight: 90)
.accessibilityLabel("JavaScript output")
}
.padding()
}
private func run() {
let code = source
running = true
output = ""
error = ""
Task {
defer { running = false }
do {
output = try await Task.detached { try JavaScriptSandbox.run(code) }.value
if output.isEmpty { error = "Finished with no output." }
} catch {
self.error = error.localizedDescription
}
}
}
}
@@ -1646,6 +1822,9 @@ struct CompatibleEndpointSettings: View {
@ObservedObject var studio: StudioModel
@Binding var endpoint: String
@Binding var model: String
@AppStorage("lmStudioPluginEndpoint") private var pluginEndpoint = ""
@AppStorage("lmStudioPluginIDs") private var pluginIDs = ""
@AppStorage("lmStudioPluginsEnabled") private var pluginsEnabled = false
@State private var models: [String] = []
@State private var connecting = false
@State private var status = ""
@@ -1660,6 +1839,18 @@ struct CompatibleEndpointSettings: View {
))
.disabled(connecting)
TextField("Model ID", text: $model)
TextField("LM Studio plugin IDs", text: $pluginIDs, prompt: Text("mcp/server, mcp/another-server"))
.onChange(of: pluginIDs) { pluginsEnabled = false }
Toggle("Use LM Studio plugins in chat", isOn: Binding(
get: { pluginsEnabled && pluginEndpoint == endpoint },
set: { enabled in
pluginEndpoint = endpoint
pluginsEnabled = enabled
}
))
.disabled(CompatibleEndpoint.pluginIDs(pluginIDs).isEmpty)
Text("Enable authentication and Allow calling servers from mcp.json in LM Studio. Enter the API token above. Enabled servers can run tools during chat.")
.foregroundStyle(.secondary)
HStack {
Button("Refresh Models") { Task { await refresh() } }
.disabled(connecting)
@@ -1676,6 +1867,7 @@ struct CompatibleEndpointSettings: View {
}
.onChange(of: endpoint) { _, value in
studio.setCompatibleToken("", endpoint: value)
pluginsEnabled = false
models = []
status = ""
}
@@ -1829,6 +2021,7 @@ struct ToolboxSheet: View {
case servers = "MCP Servers"
case search = "Web Search"
case retrieve = "Retrieve Page"
case javascript = "JavaScript"
}
@Binding var section: Section
@@ -1851,6 +2044,8 @@ struct ToolboxSheet: View {
Divider()
if section == .servers {
MCPSettings(studio: studio)
} else if section == .javascript {
JavaScriptSandboxView(studio: studio)
} else {
WebToolsView(studio: studio, section: $section, done: { dismiss() })
}
+97
View File
@@ -394,6 +394,103 @@ struct CompatibleEndpoint: InferenceProvider {
}
}
static func pluginIDs(_ text: String) -> [String] {
var seen = Set<String>()
return text.split(whereSeparator: { $0 == "," || $0.isWhitespace })
.map { $0.hasPrefix("mcp/") ? String($0) : "mcp/\($0)" }
.filter { $0.count > 4 && seen.insert($0).inserted }
}
func generateWithPlugins(_ request: InferenceRequest, plugins: [String]) -> AsyncThrowingStream<Delta, Error> {
streaming { continuation in
guard !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw StudioError("Enter an LM Studio API token in Settings → Models to use installed plugins.")
}
var server = base
if server.lastPathComponent == "v1" {
server.deleteLastPathComponent()
}
var wire = URLRequest(url: server.appending(path: "api/v1/chat"))
wire.httpMethod = "POST"
wire.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
wire.setValue("application/json", forHTTPHeaderField: "Content-Type")
wire.setValue("text/event-stream", forHTTPHeaderField: "Accept")
wire.httpBody = try JSONEncoder().encode(PluginChatBody(request, plugins: plugins))
let (bytes, response) = try await Ollama.session.bytes(for: wire)
try validate(response)
continuation.yield(.backend("LM Studio Plugins · \(request.model)"))
for try await line in bytes.lines where line.hasPrefix("data:") {
try Task.checkCancellation()
let payload = line.dropFirst(5).trimmingCharacters(in: .whitespacesAndNewlines)
guard !payload.isEmpty else { continue }
let event = try JSONDecoder().decode(PluginChatEvent.self, from: Data(payload.utf8))
switch event.type {
case "message.delta":
if let content = event.content { continuation.yield(.answer(content)) }
case "reasoning.delta":
if let content = event.content { continuation.yield(.thinking(content)) }
case "tool_call.start":
continuation.yield(.committed)
case "error":
throw StudioError(event.error?.message ?? "LM Studio plugin chat failed.")
case "chat.end":
if let stats = event.result?.stats, stats.total_output_tokens >= 0 {
continuation.yield(.metrics(ProviderMetrics(tokens: stats.total_output_tokens, seconds: 0)))
}
return
default:
break
}
}
throw StudioError("LM Studio disconnected before completing the plugin response.")
}
}
private struct PluginChatBody: Encodable {
let model: String
let input: String
let system_prompt: String?
let integrations: [String]
let stream = true
let store = false
let temperature: Double?
let top_p: Double?
let max_output_tokens: Int?
let context_length: Int?
init(_ request: InferenceRequest, plugins: [String]) {
model = request.model
integrations = plugins
let system = request.messages.filter { $0.role == .system }.map(\.content)
system_prompt = system.isEmpty ? nil : system.joined(separator: "\n\n")
// Native chat accepts user input and a system prompt. Preserve prepared history as reference text.
let conversation = request.messages.filter { $0.role != .system }
let history = conversation.dropLast()
if history.isEmpty {
input = conversation.last?.content ?? ""
} else {
let transcript = history.map { "\($0.role.rawValue): \($0.content)" }.joined(separator: "\n\n")
input = "Previous conversation for reference:\n\(transcript)\n\nLatest message:\n\(conversation.last?.content ?? "")"
}
temperature = request.parameters.temperature
top_p = request.parameters.topP
max_output_tokens = request.parameters.maxTokens
context_length = request.parameters.context
}
}
private struct PluginChatEvent: Decodable {
struct Failure: Decodable { let message: String }
struct Result: Decodable {
struct Stats: Decodable { let total_output_tokens: Int }
let stats: Stats?
}
let type: String
let content: String?
let error: Failure?
let result: Result?
}
private func urlRequest(_ path: String) -> URLRequest {
var request = URLRequest(url: base.appending(path: path))
if !token.isEmpty { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }
+12 -4
View File
@@ -174,7 +174,8 @@ final class StudioModel: ObservableObject {
}
func send(endpoint: String, model: String, mlxPath: String, thinking: Thinking, failover: Bool,
mlxOnly: Bool, compatible: Bool, recall: Bool, useDocuments: Bool, instructions: String, settings: GenerationSettings, agents: [AgentRole] = [], agentTools: Bool = false) {
mlxOnly: Bool, compatible: Bool, recall: Bool, useDocuments: Bool, instructions: String, settings: GenerationSettings, agents: [AgentRole] = [], agentTools: Bool = false,
ragEnabled: Bool = true, lmStudioPlugins: [String] = []) {
let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
let tag = model.trimmingCharacters(in: .whitespacesAndNewlines)
guard !running, !text.isEmpty else { return }
@@ -200,6 +201,8 @@ final class StudioModel: ObservableObject {
let (name, generate) = try inferenceRoute(
endpoint: endpoint, model: tag, mlxPath: mlxPath, mlxOnly: mlxOnly,
compatible: compatible, failover: failover)
let pluginClient = compatible && !mlxOnly && !lmStudioPlugins.isEmpty
? try compatibleClient(endpoint: endpoint) : nil
let parameters = try settings.parameters(mlxOnly: mlxOnly, compatible: compatible)
let templates = Dictionary(uniqueKeysWithValues: snippets.filter { $0.kind == .prompt }.map {
($0.id, PromptTemplate(body: $0.content, examples: $0.examples))
@@ -260,7 +263,7 @@ final class StudioModel: ObservableObject {
""")
}
}
if !smallTalk && (useDocuments || activeStack != nil) && (agents.isEmpty || agents.contains(where: { $0.promptSettings.useDocuments })) {
if ragEnabled && !smallTalk && (useDocuments || activeStack != nil) && (agents.isEmpty || agents.contains(where: { $0.promptSettings.useDocuments })) {
let vector = DocumentVector.forPrompt(text)
var excerpts = useDocuments ? try store.excerpts(matching: text, in: chat, vector: vector, includeLocations: true) : []
if useDocuments && excerpts.isEmpty { excerpts = try store.openingExcerpts(in: chat, includeLocations: true) }
@@ -283,9 +286,9 @@ final class StudioModel: ObservableObject {
let webEnabled = UserDefaults.standard.object(forKey: "builtInWebEnabled") as? Bool != false
let wantsRepositories = filePath == nil && GiteaRepositoryLookup.matches(text)
let automaticWeb = UserDefaults.standard.object(forKey: "automaticChatWebSearch") as? Bool != false
let remoteChoice = activeRemoteStack
let remoteChoice = ragEnabled ? activeRemoteStack : .off
let maySearchAutomatically = automaticWeb && (remoteChoice == .automatic || remoteChoice == .off) && !smallTalk && !wantsRepositories && attachment == nil &&
!(useDocuments && !documents.isEmpty) && activeStack == nil && activeContext == nil && activeSkill == nil && activeWebClip == nil
(!ragEnabled || (!(useDocuments && !documents.isEmpty) && activeStack == nil)) && activeContext == nil && activeSkill == nil && activeWebClip == nil
let lookup = filePath == nil && webEnabled
? ChatWebLookup.forChat(message: text, recent: Array(recent), automatic: maySearchAutomatically) : nil
let explicitWeb = ChatWebLookup(message: text) != nil
@@ -436,6 +439,11 @@ final class StudioModel: ObservableObject {
let prepared = try StudioPromptRequest.prepare(
messages, template: template, options: options, parameters: parameters)
if final { self.partial?.documentCitations = prepared.citations }
if final, let pluginClient {
return pluginClient.generateWithPlugins(
InferenceRequest(model: tag, messages: prepared.messages, thinking: requestThinking,
parameters: prepared.parameters), plugins: lmStudioPlugins)
}
return generate(prepared.messages, final ? requestThinking : .off, prepared.parameters)
} catch {
return AsyncThrowingStream { $0.finish(throwing: error) }