new features
This commit is contained in:
+198
-3
@@ -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() })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user