new features
This commit is contained in:
@@ -244,14 +244,14 @@
|
|||||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
CODE_SIGN_IDENTITY = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 12;
|
CURRENT_PROJECT_VERSION = 13;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEVELOPMENT_TEAM = 39R6U3437D;
|
DEVELOPMENT_TEAM = 39R6U3437D;
|
||||||
ENABLE_HARDENED_RUNTIME = NO;
|
ENABLE_HARDENED_RUNTIME = NO;
|
||||||
ENABLE_TESTABILITY = YES;
|
ENABLE_TESTABILITY = YES;
|
||||||
INFOPLIST_FILE = Info.plist;
|
INFOPLIST_FILE = Info.plist;
|
||||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
|
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
|
||||||
MARKETING_VERSION = 1.1.10;
|
MARKETING_VERSION = 1.1.11;
|
||||||
OTHER_LDFLAGS = (
|
OTHER_LDFLAGS = (
|
||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"-lsqlite3",
|
"-lsqlite3",
|
||||||
@@ -269,13 +269,13 @@
|
|||||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||||
CODE_SIGN_IDENTITY = "Apple Development";
|
CODE_SIGN_IDENTITY = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 12;
|
CURRENT_PROJECT_VERSION = 13;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEVELOPMENT_TEAM = 39R6U3437D;
|
DEVELOPMENT_TEAM = 39R6U3437D;
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
ENABLE_HARDENED_RUNTIME = YES;
|
||||||
INFOPLIST_FILE = Info.plist;
|
INFOPLIST_FILE = Info.plist;
|
||||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
|
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
|
||||||
MARKETING_VERSION = 1.1.10;
|
MARKETING_VERSION = 1.1.11;
|
||||||
OTHER_LDFLAGS = (
|
OTHER_LDFLAGS = (
|
||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"-lsqlite3",
|
"-lsqlite3",
|
||||||
|
|||||||
+198
-3
@@ -3,8 +3,19 @@ import AppKit
|
|||||||
import Charts
|
import Charts
|
||||||
import UniformTypeIdentifiers
|
import UniformTypeIdentifiers
|
||||||
import WebKit
|
import WebKit
|
||||||
|
import JavaScriptCore
|
||||||
|
|
||||||
@main
|
@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 {
|
struct AIStudioApp: App {
|
||||||
@StateObject private var studio = StudioModel()
|
@StateObject private var studio = StudioModel()
|
||||||
@AppStorage("studioCustomThemes") private var customThemesData = Data()
|
@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("compatibleEndpoint") private var compatibleEndpoint = "http://127.0.0.1:1234/v1"
|
||||||
@AppStorage("compatibleModel") private var compatibleModel = ""
|
@AppStorage("compatibleModel") private var compatibleModel = ""
|
||||||
@AppStorage("recall") private var recall = true
|
@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("globalPromptMode") private var promptMode = PromptMode.standard
|
||||||
@AppStorage("globalCustomPrompt") private var customPrompt = ""
|
@AppStorage("globalCustomPrompt") private var customPrompt = ""
|
||||||
@AppStorage(GenerationSettings.key) private var generationSettings = Data()
|
@AppStorage(GenerationSettings.key) private var generationSettings = Data()
|
||||||
@@ -442,7 +457,7 @@ struct ChatView: View {
|
|||||||
|
|
||||||
private var composer: some View {
|
private var composer: some View {
|
||||||
VStack(alignment: .leading, spacing: 8) {
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
if !studio.documents.isEmpty {
|
if ragEnabled && !studio.documents.isEmpty {
|
||||||
Toggle(chatModel.backend == .mlx ? "Include matching document excerpts" :
|
Toggle(chatModel.backend == .mlx ? "Include matching document excerpts" :
|
||||||
"Send matching document excerpts to \(backendName)", isOn: documentExcerptsEnabled)
|
"Send matching document excerpts to \(backendName)", isOn: documentExcerptsEnabled)
|
||||||
.font(.caption)
|
.font(.caption)
|
||||||
@@ -502,6 +517,9 @@ struct ChatView: View {
|
|||||||
.buttonStyle(.bordered)
|
.buttonStyle(.bordered)
|
||||||
.help(studio.activeToolsets.map { $0.toolset.name }.joined(separator: ", "))
|
.help(studio.activeToolsets.map { $0.toolset.name }.joined(separator: ", "))
|
||||||
resourceMenu(for: studio)
|
resourceMenu(for: studio)
|
||||||
|
Toggle("RAG", isOn: $ragEnabled)
|
||||||
|
.toggleStyle(.button)
|
||||||
|
.help("Retrieve matching documents and knowledge stack content")
|
||||||
Spacer()
|
Spacer()
|
||||||
}
|
}
|
||||||
HStack(spacing: 10) {
|
HStack(spacing: 10) {
|
||||||
@@ -591,7 +609,9 @@ struct ChatView: View {
|
|||||||
thinking: choice.thinkingMode(thinking), failover: failover,
|
thinking: choice.thinkingMode(thinking), failover: failover,
|
||||||
mlxOnly: choice.backend == .mlx, compatible: choice.backend == .compatible,
|
mlxOnly: choice.backend == .mlx, compatible: choice.backend == .compatible,
|
||||||
recall: recall, useDocuments: useDocuments, instructions: promptMode.instructions(custom: customPrompt),
|
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.content.isEmpty {
|
||||||
if message.role == .assistant && renderMarkdown {
|
if message.role == .assistant && renderMarkdown {
|
||||||
ChatMarkdown(text: message.content)
|
ChatMarkdown(text: message.content, canRunJavaScript: !streaming)
|
||||||
} else {
|
} else {
|
||||||
Text(message.content).textSelection(.enabled)
|
Text(message.content).textSelection(.enabled)
|
||||||
}
|
}
|
||||||
@@ -1154,6 +1174,8 @@ private func copyChatText(_ text: String) {
|
|||||||
|
|
||||||
struct ChatMarkdown: View {
|
struct ChatMarkdown: View {
|
||||||
let text: String
|
let text: String
|
||||||
|
var canRunJavaScript = false
|
||||||
|
@State private var sandboxSource: String?
|
||||||
@AppStorage("studioCodeTheme") private var codeTheme = StudioTheme.system
|
@AppStorage("studioCodeTheme") private var codeTheme = StudioTheme.system
|
||||||
@Environment(\.colorScheme) private var currentScheme
|
@Environment(\.colorScheme) private var currentScheme
|
||||||
|
|
||||||
@@ -1202,6 +1224,12 @@ struct ChatMarkdown: View {
|
|||||||
Text(language.isEmpty ? "Code" : String(language.prefix(60)))
|
Text(language.isEmpty ? "Code" : String(language.prefix(60)))
|
||||||
.font(.caption).foregroundStyle(.secondary)
|
.font(.caption).foregroundStyle(.secondary)
|
||||||
Spacer()
|
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) }
|
Button("Copy Code", systemImage: "doc.on.doc") { copyChatText(block.content) }
|
||||||
.buttonStyle(.borderless)
|
.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
|
@ObservedObject var studio: StudioModel
|
||||||
@Binding var endpoint: String
|
@Binding var endpoint: String
|
||||||
@Binding var model: 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 models: [String] = []
|
||||||
@State private var connecting = false
|
@State private var connecting = false
|
||||||
@State private var status = ""
|
@State private var status = ""
|
||||||
@@ -1660,6 +1839,18 @@ struct CompatibleEndpointSettings: View {
|
|||||||
))
|
))
|
||||||
.disabled(connecting)
|
.disabled(connecting)
|
||||||
TextField("Model ID", text: $model)
|
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 {
|
HStack {
|
||||||
Button("Refresh Models") { Task { await refresh() } }
|
Button("Refresh Models") { Task { await refresh() } }
|
||||||
.disabled(connecting)
|
.disabled(connecting)
|
||||||
@@ -1676,6 +1867,7 @@ struct CompatibleEndpointSettings: View {
|
|||||||
}
|
}
|
||||||
.onChange(of: endpoint) { _, value in
|
.onChange(of: endpoint) { _, value in
|
||||||
studio.setCompatibleToken("", endpoint: value)
|
studio.setCompatibleToken("", endpoint: value)
|
||||||
|
pluginsEnabled = false
|
||||||
models = []
|
models = []
|
||||||
status = ""
|
status = ""
|
||||||
}
|
}
|
||||||
@@ -1829,6 +2021,7 @@ struct ToolboxSheet: View {
|
|||||||
case servers = "MCP Servers"
|
case servers = "MCP Servers"
|
||||||
case search = "Web Search"
|
case search = "Web Search"
|
||||||
case retrieve = "Retrieve Page"
|
case retrieve = "Retrieve Page"
|
||||||
|
case javascript = "JavaScript"
|
||||||
}
|
}
|
||||||
|
|
||||||
@Binding var section: Section
|
@Binding var section: Section
|
||||||
@@ -1851,6 +2044,8 @@ struct ToolboxSheet: View {
|
|||||||
Divider()
|
Divider()
|
||||||
if section == .servers {
|
if section == .servers {
|
||||||
MCPSettings(studio: studio)
|
MCPSettings(studio: studio)
|
||||||
|
} else if section == .javascript {
|
||||||
|
JavaScriptSandboxView(studio: studio)
|
||||||
} else {
|
} else {
|
||||||
WebToolsView(studio: studio, section: $section, done: { dismiss() })
|
WebToolsView(studio: studio, section: $section, done: { dismiss() })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {
|
private func urlRequest(_ path: String) -> URLRequest {
|
||||||
var request = URLRequest(url: base.appending(path: path))
|
var request = URLRequest(url: base.appending(path: path))
|
||||||
if !token.isEmpty { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }
|
if !token.isEmpty { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") }
|
||||||
|
|||||||
@@ -174,7 +174,8 @@ final class StudioModel: ObservableObject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func send(endpoint: String, model: String, mlxPath: String, thinking: Thinking, failover: Bool,
|
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 text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
let tag = model.trimmingCharacters(in: .whitespacesAndNewlines)
|
let tag = model.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
guard !running, !text.isEmpty else { return }
|
guard !running, !text.isEmpty else { return }
|
||||||
@@ -200,6 +201,8 @@ final class StudioModel: ObservableObject {
|
|||||||
let (name, generate) = try inferenceRoute(
|
let (name, generate) = try inferenceRoute(
|
||||||
endpoint: endpoint, model: tag, mlxPath: mlxPath, mlxOnly: mlxOnly,
|
endpoint: endpoint, model: tag, mlxPath: mlxPath, mlxOnly: mlxOnly,
|
||||||
compatible: compatible, failover: failover)
|
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 parameters = try settings.parameters(mlxOnly: mlxOnly, compatible: compatible)
|
||||||
let templates = Dictionary(uniqueKeysWithValues: snippets.filter { $0.kind == .prompt }.map {
|
let templates = Dictionary(uniqueKeysWithValues: snippets.filter { $0.kind == .prompt }.map {
|
||||||
($0.id, PromptTemplate(body: $0.content, examples: $0.examples))
|
($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)
|
let vector = DocumentVector.forPrompt(text)
|
||||||
var excerpts = useDocuments ? try store.excerpts(matching: text, in: chat, vector: vector, includeLocations: true) : []
|
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) }
|
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 webEnabled = UserDefaults.standard.object(forKey: "builtInWebEnabled") as? Bool != false
|
||||||
let wantsRepositories = filePath == nil && GiteaRepositoryLookup.matches(text)
|
let wantsRepositories = filePath == nil && GiteaRepositoryLookup.matches(text)
|
||||||
let automaticWeb = UserDefaults.standard.object(forKey: "automaticChatWebSearch") as? Bool != false
|
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 &&
|
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
|
let lookup = filePath == nil && webEnabled
|
||||||
? ChatWebLookup.forChat(message: text, recent: Array(recent), automatic: maySearchAutomatically) : nil
|
? ChatWebLookup.forChat(message: text, recent: Array(recent), automatic: maySearchAutomatically) : nil
|
||||||
let explicitWeb = ChatWebLookup(message: text) != nil
|
let explicitWeb = ChatWebLookup(message: text) != nil
|
||||||
@@ -436,6 +439,11 @@ final class StudioModel: ObservableObject {
|
|||||||
let prepared = try StudioPromptRequest.prepare(
|
let prepared = try StudioPromptRequest.prepare(
|
||||||
messages, template: template, options: options, parameters: parameters)
|
messages, template: template, options: options, parameters: parameters)
|
||||||
if final { self.partial?.documentCitations = prepared.citations }
|
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)
|
return generate(prepared.messages, final ? requestThinking : .off, prepared.parameters)
|
||||||
} catch {
|
} catch {
|
||||||
return AsyncThrowingStream { $0.finish(throwing: error) }
|
return AsyncThrowingStream { $0.finish(throwing: error) }
|
||||||
|
|||||||
@@ -40,6 +40,30 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
payload = ''.join(f'data: {json.dumps(frame)}\n\n' for frame in frames)
|
payload = ''.join(f'data: {json.dumps(frame)}\n\n' for frame in frames)
|
||||||
self.reply(200, (payload + 'data: [DONE]\n\n').encode(), 'text/event-stream')
|
self.reply(200, (payload + 'data: [DONE]\n\n').encode(), 'text/event-stream')
|
||||||
return
|
return
|
||||||
|
if self.path == '/compatible/api/v1/chat':
|
||||||
|
valid = (self.headers.get('Authorization') == 'Bearer fixture-token'
|
||||||
|
and message.get('integrations') == ['mcp/fixture']
|
||||||
|
and message.get('system_prompt') == 'Silent instruction'
|
||||||
|
and message.get('input') == 'Previous conversation for reference:\nuser: Earlier question\n\nassistant: Earlier answer\n\nLatest message:\nUse the fixture'
|
||||||
|
and message.get('stream') is True and message.get('store') is False)
|
||||||
|
if not valid:
|
||||||
|
self.reply(400)
|
||||||
|
return
|
||||||
|
frames = [
|
||||||
|
{'type': 'tool_call.start'},
|
||||||
|
{'type': 'reasoning.delta', 'content': 'Checking'},
|
||||||
|
{'type': 'message.delta', 'content': 'Plugin response'},
|
||||||
|
{'type': 'chat.end', 'result': {'stats': {'total_output_tokens': 2}}},
|
||||||
|
]
|
||||||
|
payload = ''.join(f"event: {frame['type']}\ndata: {json.dumps(frame)}\n\n" for frame in frames)
|
||||||
|
self.reply(200, payload.encode(), 'text/event-stream')
|
||||||
|
return
|
||||||
|
if self.path == '/chat-rag-off/api/chat':
|
||||||
|
if any('Cobalt river trail' in item['content'] for item in message['messages']):
|
||||||
|
self.reply(400)
|
||||||
|
return
|
||||||
|
self.reply(200, b'{"message":{"content":"RAG is off."},"done":true}\n', 'application/x-ndjson')
|
||||||
|
return
|
||||||
if self.path == '/chat-web/api/chat':
|
if self.path == '/chat-web/api/chat':
|
||||||
system, user = message['messages']
|
system, user = message['messages']
|
||||||
if system['role'] != 'system' or 'Test passage.' not in system['content'] or '/article' not in user['content']:
|
if system['role'] != 'system' or 'Test passage.' not in system['content'] or '/article' not in user['content']:
|
||||||
|
|||||||
+48
-5
@@ -550,7 +550,47 @@ final class GenerationConfigurationTests: XCTestCase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final class JavaScriptSandboxTests: XCTestCase {
|
||||||
|
func testSandboxRunsJavaScriptWithoutHostAPIs() throws {
|
||||||
|
XCTAssertEqual(try JavaScriptSandbox.run("console.log(6 * 7); ({ready: true})"),
|
||||||
|
"42 \n{\"ready\":true}")
|
||||||
|
XCTAssertEqual(try JavaScriptSandbox.run("[typeof require, typeof fetch, typeof process]"),
|
||||||
|
"[\"undefined\",\"undefined\",\"undefined\"]")
|
||||||
|
XCTAssertThrowsError(try JavaScriptSandbox.run("throw new Error('expected')")) {
|
||||||
|
XCTAssertEqual($0.localizedDescription, "Error: expected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSandboxStopsInfiniteLoops() throws {
|
||||||
|
XCTAssertThrowsError(try JavaScriptSandbox.run("while (true) {}")) {
|
||||||
|
XCTAssertTrue($0.localizedDescription.contains("time limit"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
final class CompatibleEndpointTests: XCTestCase {
|
final class CompatibleEndpointTests: XCTestCase {
|
||||||
|
func testLMStudioPluginRequestAndStream() async throws {
|
||||||
|
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_COMPATIBLE_URL"] else {
|
||||||
|
throw XCTSkip("Run Scripts/test.sh to configure the local fixture.")
|
||||||
|
}
|
||||||
|
let client = try CompatibleEndpoint(endpoint: endpoint, token: "fixture-token")
|
||||||
|
let plugins = CompatibleEndpoint.pluginIDs("fixture, mcp/fixture")
|
||||||
|
XCTAssertEqual(plugins, ["mcp/fixture"])
|
||||||
|
let request = InferenceRequest(model: "fixture-model", messages: [
|
||||||
|
Message(role: .system, content: "Silent instruction"),
|
||||||
|
Message(role: .user, content: "Earlier question"),
|
||||||
|
Message(role: .assistant, content: "Earlier answer"),
|
||||||
|
Message(role: .user, content: "Use the fixture")
|
||||||
|
], thinking: .automatic)
|
||||||
|
var deltas: [Delta] = []
|
||||||
|
for try await delta in client.generateWithPlugins(request, plugins: plugins) {
|
||||||
|
deltas.append(delta)
|
||||||
|
}
|
||||||
|
XCTAssertEqual(deltas, [.backend("LM Studio Plugins · fixture-model"), .committed,
|
||||||
|
.thinking("Checking"), .answer("Plugin response"),
|
||||||
|
.metrics(ProviderMetrics(tokens: 2, seconds: 0))])
|
||||||
|
}
|
||||||
|
|
||||||
func testRequiresHTTPSForRemoteAndRejectsEmbeddedCredentials() throws {
|
func testRequiresHTTPSForRemoteAndRejectsEmbeddedCredentials() throws {
|
||||||
XCTAssertThrowsError(try CompatibleEndpoint(endpoint: "http://example.com/v1"))
|
XCTAssertThrowsError(try CompatibleEndpoint(endpoint: "http://example.com/v1"))
|
||||||
XCTAssertThrowsError(try CompatibleEndpoint(endpoint: "https://user:[email protected]/v1"))
|
XCTAssertThrowsError(try CompatibleEndpoint(endpoint: "https://user:[email protected]/v1"))
|
||||||
@@ -1740,7 +1780,7 @@ extension ChatDocumentFallbackTests {
|
|||||||
let database = root.appending(path: "studio.sqlite")
|
let database = root.appending(path: "studio.sqlite")
|
||||||
let studio = StudioModel()
|
let studio = StudioModel()
|
||||||
studio.open(databaseURL: database)
|
studio.open(databaseURL: database)
|
||||||
for imported in [false, true] {
|
for (imported, ragEnabled) in [(false, false), (true, true), (true, false)] {
|
||||||
studio.newChat()
|
studio.newChat()
|
||||||
if imported {
|
if imported {
|
||||||
let store = try Store(url: database)
|
let store = try Store(url: database)
|
||||||
@@ -1750,17 +1790,20 @@ extension ChatDocumentFallbackTests {
|
|||||||
studio.attachToolResult(name: "brief.txt", output: "Cobalt river trail", isDocument: true)
|
studio.attachToolResult(name: "brief.txt", output: "Cobalt river trail", isDocument: true)
|
||||||
}
|
}
|
||||||
studio.prompt = "Tell me about this"
|
studio.prompt = "Tell me about this"
|
||||||
studio.send(endpoint: base.appending(path: "chat-document").absoluteString, model: "fixture",
|
let includeExcerpt = !imported || ragEnabled
|
||||||
|
let route = includeExcerpt ? "chat-document" : "chat-rag-off"
|
||||||
|
studio.send(endpoint: base.appending(path: route).absoluteString, model: "fixture",
|
||||||
mlxPath: "", thinking: .off, failover: false, mlxOnly: false, compatible: false,
|
mlxPath: "", thinking: .off, failover: false, mlxOnly: false, compatible: false,
|
||||||
recall: false, useDocuments: imported, instructions: "", settings: GenerationSettings())
|
recall: false, useDocuments: imported, instructions: "", settings: GenerationSettings(),
|
||||||
|
ragEnabled: ragEnabled)
|
||||||
let deadline = ContinuousClock.now + .seconds(5)
|
let deadline = ContinuousClock.now + .seconds(5)
|
||||||
while studio.running && ContinuousClock.now < deadline {
|
while studio.running && ContinuousClock.now < deadline {
|
||||||
try await Task.sleep(for: .milliseconds(10))
|
try await Task.sleep(for: .milliseconds(10))
|
||||||
}
|
}
|
||||||
XCTAssertEqual(studio.messages.last?.content, "Document received.", studio.status)
|
XCTAssertEqual(studio.messages.last?.content, includeExcerpt ? "Document received." : "RAG is off.", studio.status)
|
||||||
let saved = try Store(url: database).messages(in: XCTUnwrap(studio.selected))
|
let saved = try Store(url: database).messages(in: XCTUnwrap(studio.selected))
|
||||||
XCTAssertEqual(saved.first?.content, "Tell me about this")
|
XCTAssertEqual(saved.first?.content, "Tell me about this")
|
||||||
XCTAssertEqual(saved.first?.documentNames, ["brief.txt"])
|
XCTAssertEqual(saved.first?.documentNames, includeExcerpt ? ["brief.txt"] : [])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user