Complete workspace recovery, migration, and compatibility checks
This commit is contained in:
+35
-11
@@ -4,18 +4,18 @@
|
||||
| --- | --- | --- |
|
||||
| 1. Native foundation | Complete | SwiftUI chat, Ollama-first inference, MLX fallback, SQLite persistence, scripts |
|
||||
| 2. Studio features | Complete | App icon and startup screen, MLX catalog, Qwen thinking, document retrieval, MCP Streamable HTTP tools |
|
||||
| 3. Release readiness | Awaiting external checks | Authenticated gateway tests, archive verification, live remote interoperability and distribution signing |
|
||||
| 3. Release readiness | Partially verified | Gateway, Developer ID archive, and remote MCP verified. Remote Ollama and notarization pending |
|
||||
| 4. Chat workspace | Complete | Chat search and rename, formatted answers, global prompt modes, prompt builder, performance dashboard |
|
||||
| 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 | Verified | Live LM Studio discovery and streamed chat, plus MCP stdio fixture |
|
||||
| 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 endpoint and notary profile | Remote Ollama and Apple notarization. Docker daemon verification remains separate |
|
||||
|
||||
## Phase 6 checklist
|
||||
|
||||
- [x] Verify OpenAI-compatible model discovery and streamed chat.
|
||||
- [ ] Verify with a running LM Studio server.
|
||||
- [x] Verify with a running LM Studio server.
|
||||
- [x] Verify MCP stdio discovery, confirmed invocation support, cancellation, and disconnect against a local fixture.
|
||||
|
||||
## Phase 3 checklist
|
||||
@@ -25,8 +25,10 @@
|
||||
- [x] Verify authenticated Ollama streaming, invalid credentials and redirect handling with the loopback gateway.
|
||||
- [x] Verify the ZIP checksum, then extract it and verify the app signature and arm64-only executable.
|
||||
- [ ] Run a smoke test against a real remote Ollama endpoint with a preinstalled model.
|
||||
- [ ] Run a smoke test against a real remote MCP endpoint.
|
||||
- [ ] Sign and notarize with a Developer ID Application identity and notary profile.
|
||||
- [x] Run discovery, source inventory, and read-only search against the Pegasus MCP server over SSH stdio.
|
||||
- [ ] Verify a real remote Streamable HTTP MCP endpoint when one is configured.
|
||||
- [x] Sign with Developer ID Application and verify the extracted app has hardened runtime.
|
||||
- [ ] Notarize and staple with a configured notary profile.
|
||||
|
||||
## Phase 4 checklist
|
||||
|
||||
@@ -38,11 +40,13 @@
|
||||
|
||||
## 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.
|
||||
- [x] Import text chats from the installed Msty Studio database schema, scan a chosen folder for AI Studio backups, and relocate a workspace. Msty attachments and non-chat resources are outside the importer.
|
||||
- [x] Add editable appearance shortcuts, chat rendering options, and a side-by-side conversation comparison.
|
||||
- [ ] Add independent composers and concurrent generation in split chats.
|
||||
- [x] Extend Prompt Library with notes, tags, and version history. Add rendered web clip capture in an isolated WebKit session. Interactive sign-in has not been verified.
|
||||
- [x] Document the ACP adapter, diff review, tool history, and compatible proxy configuration design.
|
||||
- [ ] Implement and validate ACP adapters, diff review, and tool history. Verify a selected separate local proxy.
|
||||
- [x] Evaluate LM Studio runtime and plugin parity. See [Integration notes](#integration-notes).
|
||||
- [x] Verify tool discovery on the repaired Gitea stdio profile.
|
||||
|
||||
## Verification log
|
||||
@@ -130,3 +134,23 @@ file. The authenticated read-only repository listing and the complete chat
|
||||
request containing both knowledge and repository context passed. The composer
|
||||
uses one compact control row. Debug built and launched. 46 tests passed,
|
||||
with three opt-in inference checks skipped.
|
||||
|
||||
## 17 November 2026 verification
|
||||
|
||||
- The compatible client discovered and streamed from a Qwen 3.5 model on a live loopback LM Studio server. The authenticated compatible fixture and MCP stdio lifecycle fixture also passed.
|
||||
- Gitea stdio discovery and read-only repository listing passed. Pegasus returned an indexed-source inventory and answered a read-only knowledge query over the configured SSH stdio connection.
|
||||
- The configured inference endpoint was loopback. Pegasus had no reachable Ollama on port 11434 or detected installed Ollama binary, so remote Ollama generation remains pending.
|
||||
- The final Debug build launched. The Developer ID release ZIP matched its SHA-256 checksum. The extracted app passed strict signature verification, enabled hardened runtime, and contained only an arm64 executable slice. No notarization profile was located.
|
||||
- Phase 4 workspace tests passed. The latest workspace tests also covered reopening the relocated database, refusing to overwrite a destination database, Msty chat import with repeat-import deduplication, and saved prompt versions.
|
||||
|
||||
## Integration notes
|
||||
|
||||
### LM Studio parity
|
||||
|
||||
AI Studio has native MLX inference and delegates Ollama or compatible inference to an external server. The verified LM Studio integration uses the OpenAI-compatible model list and chat stream. Its MCP configuration import covers server definitions. LM Studio's JavaScript plugin runtime has its own SDK and lifecycle. Engine selection, runtime updates, and headless service management are currently external to AI Studio. LM Studio's `lms runtime` and `lms daemon` provide those external controls. [LM Studio CLI](https://lmstudio.ai/docs/cli) · [Headless service](https://lmstudio.ai/docs/developer/core/headless) · [Developer APIs and plugin SDK](https://lmstudio.ai/docs/developer)
|
||||
|
||||
### ACP and local proxy
|
||||
|
||||
A future coding adapter should negotiate protocol version and capabilities, maintain an ACP session per selected workspace, and forward prompt updates and cancellation independently of chat inference. Store tool events by session ID and tool-call ID so updates can amend existing entries. Use a read-only diff panel for agent-reported patches. Render approval requests as explicit user decisions and bind any later file operations to the selected workspace. Acceptance checks should cover reconnect, cancellation during permission requests, and accurate rendering of renamed and deleted files. [ACP protocol and schema](https://github.com/agentclientprotocol/agent-client-protocol)
|
||||
|
||||
For a separately managed OpenAI-compatible local proxy, enter its loopback `/v1` base URL in **Settings → Models → OpenAI-compatible**, refresh model discovery, and select the proxy's model ID. The existing compatible client handles streaming. A separate proxy service and its authentication flow have not been selected or deployed.
|
||||
|
||||
+281
-22
@@ -2,6 +2,7 @@ import SwiftUI
|
||||
import AppKit
|
||||
import Charts
|
||||
import UniformTypeIdentifiers
|
||||
import WebKit
|
||||
|
||||
@main
|
||||
struct AIStudioApp: App {
|
||||
@@ -12,6 +13,7 @@ struct AIStudioApp: App {
|
||||
@AppStorage("studioAccent") private var accent = StudioAccent.storm
|
||||
@AppStorage("studioChatSize") private var chatSize = 14
|
||||
@AppStorage("studioMode") private var mode = StudioMode.normal
|
||||
@AppStorage("studioShortcutKeys") private var shortcutData = Data()
|
||||
|
||||
var body: some Scene {
|
||||
Window("AI Studio", id: "studio") {
|
||||
@@ -33,11 +35,11 @@ struct AIStudioApp: App {
|
||||
.defaultSize(width: 1000, height: 700)
|
||||
.commands {
|
||||
CommandMenu("Appearance") {
|
||||
Button("Increase Chat Font Size") { chatSize = min(28, chatSize + 1) }.keyboardShortcut("=")
|
||||
Button("Decrease Chat Font Size") { chatSize = max(10, chatSize - 1) }.keyboardShortcut("-")
|
||||
Button("Reset Chat Font Size") { chatSize = 14 }.keyboardShortcut("0")
|
||||
Button("Cycle Theme") { theme = nextValue(theme) }.keyboardShortcut("3")
|
||||
Button("Cycle Workspace Mode") { mode = nextValue(mode) }.keyboardShortcut("9")
|
||||
Button("Increase Chat Font Size") { chatSize = min(28, chatSize + 1) }.keyboardShortcut(StudioShortcut.increase.shortcut(in: shortcutData))
|
||||
Button("Decrease Chat Font Size") { chatSize = max(10, chatSize - 1) }.keyboardShortcut(StudioShortcut.decrease.shortcut(in: shortcutData))
|
||||
Button("Reset Chat Font Size") { chatSize = 14 }.keyboardShortcut(StudioShortcut.reset.shortcut(in: shortcutData))
|
||||
Button("Cycle Theme") { theme = nextValue(theme) }.keyboardShortcut(StudioShortcut.theme.shortcut(in: shortcutData))
|
||||
Button("Cycle Workspace Mode") { mode = nextValue(mode) }.keyboardShortcut(StudioShortcut.workspaceMode.shortcut(in: shortcutData))
|
||||
}
|
||||
}
|
||||
Settings {
|
||||
@@ -70,6 +72,8 @@ struct ChatView: View {
|
||||
@AppStorage(GenerationSettings.key) private var generationSettings = Data()
|
||||
@State private var showingPromptBuilder = false
|
||||
@State private var showingPerformance = false
|
||||
@State private var showingComparison = false
|
||||
@State private var comparisonChat: UUID?
|
||||
@State private var showingWorkspace = false
|
||||
@State private var showingToolbox = false
|
||||
@AppStorage("chatDebugOutput") private var showDebugOutput = false
|
||||
@@ -137,10 +141,13 @@ struct ChatView: View {
|
||||
}
|
||||
} detail: {
|
||||
VStack(spacing: 0) {
|
||||
if studio.messages.isEmpty && studio.partial == nil {
|
||||
StudioWelcome(loading: false)
|
||||
if showingComparison {
|
||||
HSplitView {
|
||||
currentTranscript.frame(minWidth: 280)
|
||||
comparisonTranscript.frame(minWidth: 260)
|
||||
}
|
||||
} else {
|
||||
transcript
|
||||
currentTranscript
|
||||
}
|
||||
Divider()
|
||||
composer
|
||||
@@ -152,6 +159,11 @@ struct ChatView: View {
|
||||
.disabled(studio.selected == nil)
|
||||
Button("Prompt Builder", systemImage: "wand.and.stars") { showingPromptBuilder = true }
|
||||
Button("Workspace", systemImage: "square.stack.3d.up") { showingWorkspace = true }
|
||||
Button("Compare Chats", systemImage: "rectangle.split.2x1") {
|
||||
showingComparison.toggle()
|
||||
if showingComparison { comparisonChat = studio.conversations.first { $0.id != studio.selected }?.id }
|
||||
}
|
||||
.disabled(studio.conversations.count < 2 && !showingComparison)
|
||||
Button("Performance", systemImage: "chart.xyaxis.line") { showingPerformance = true }
|
||||
SettingsLink { Label("Settings", systemImage: "gear") }
|
||||
}
|
||||
@@ -220,6 +232,43 @@ struct ChatView: View {
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder private var currentTranscript: some View {
|
||||
if studio.messages.isEmpty && studio.partial == nil {
|
||||
StudioWelcome(loading: false)
|
||||
} else {
|
||||
transcript
|
||||
}
|
||||
}
|
||||
|
||||
private var comparisonTranscript: some View {
|
||||
VStack(spacing: 0) {
|
||||
Picker("Compare with", selection: $comparisonChat) {
|
||||
Text("Choose a conversation").tag(Optional<UUID>.none)
|
||||
ForEach(studio.conversations.filter { $0.id != studio.selected }) { chat in
|
||||
Text(chat.title).tag(Optional(chat.id))
|
||||
}
|
||||
}
|
||||
.padding(10)
|
||||
Divider()
|
||||
if let comparisonChat, comparisonChat != studio.selected,
|
||||
studio.conversations.contains(where: { $0.id == comparisonChat }) {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 12) {
|
||||
ForEach(studio.conversationMessages(comparisonChat)) { MessageView(message: $0) }
|
||||
}.padding(12)
|
||||
}
|
||||
.font(chatFont.font(size: chatSize))
|
||||
} else {
|
||||
ContentUnavailableView("Choose a conversation", systemImage: "rectangle.split.2x1")
|
||||
}
|
||||
}
|
||||
.onChange(of: studio.selected) {
|
||||
if comparisonChat == studio.selected {
|
||||
comparisonChat = studio.conversations.first { $0.id != studio.selected }?.id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var transcript: some View {
|
||||
ScrollViewReader { proxy in
|
||||
ScrollView {
|
||||
@@ -389,6 +438,11 @@ struct MessageView: View {
|
||||
@Environment(\.colorScheme) private var colorScheme
|
||||
var streaming = false
|
||||
|
||||
@AppStorage("renderChatMarkdown") private var renderMarkdown = true
|
||||
@AppStorage("compactChatMessages") private var compactMessages = false
|
||||
@AppStorage("expandChatThinking") private var expandThinking = false
|
||||
@State private var thinkingExpanded = false
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
HStack {
|
||||
@@ -407,13 +461,13 @@ struct MessageView: View {
|
||||
}
|
||||
}
|
||||
if !message.thinking.isEmpty {
|
||||
DisclosureGroup("Thinking") {
|
||||
DisclosureGroup("Thinking", isExpanded: $thinkingExpanded) {
|
||||
Text(message.thinking).foregroundStyle(.secondary).textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
if !message.content.isEmpty {
|
||||
if message.role == .assistant {
|
||||
if message.role == .assistant && renderMarkdown {
|
||||
ChatMarkdown(text: message.content)
|
||||
} else {
|
||||
Text(message.content).textSelection(.enabled)
|
||||
@@ -422,7 +476,8 @@ struct MessageView: View {
|
||||
if message.content.isEmpty && message.thinking.isEmpty { ProgressView().controlSize(.small) }
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(14)
|
||||
.padding(compactMessages ? 8 : 14)
|
||||
.onChange(of: expandThinking, initial: true) { _, expanded in thinkingExpanded = expanded }
|
||||
.background(StudioCustomTheme.selected(customThemeID, in: customThemesData)?.message(dark: colorScheme == .dark, user: message.role == .user) ?? palette.message(dark: colorScheme == .dark, user: message.role == .user),
|
||||
in: RoundedRectangle(cornerRadius: 12))
|
||||
}
|
||||
@@ -1464,16 +1519,20 @@ struct WorkspaceSnippetsView: View {
|
||||
@State private var search = ""
|
||||
@State private var id: UUID?
|
||||
@State private var title = ""
|
||||
@State private var notes = ""
|
||||
@State private var tags = ""
|
||||
@State private var versions: [PromptVersion] = []
|
||||
@State private var content = ""
|
||||
@State private var address = ""
|
||||
@State private var importing = false
|
||||
@State private var capturing = false
|
||||
@State private var renderedPage: RenderedClipPage?
|
||||
@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))
|
||||
$0.kind == kind && (search.isEmpty || $0.title.localizedCaseInsensitiveContains(search) || $0.tags.localizedCaseInsensitiveContains(search) || $0.notes.localizedCaseInsensitiveContains(search))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1488,6 +1547,22 @@ struct WorkspaceSnippetsView: View {
|
||||
.frame(minWidth: 180, idealWidth: 220)
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
TextField("Title", text: $title)
|
||||
if kind == .prompt {
|
||||
TextField("Notes", text: $notes)
|
||||
TextField("Tags (comma-separated)", text: $tags)
|
||||
if !versions.isEmpty {
|
||||
Menu("Version History") {
|
||||
ForEach(versions) { version in
|
||||
Button("\(version.savedAt) · \(version.title)") {
|
||||
title = version.title
|
||||
content = version.content
|
||||
notes = version.notes
|
||||
tags = version.tags
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if kind == .webClip {
|
||||
HStack {
|
||||
TextField("Source URL", text: $address)
|
||||
@@ -1503,6 +1578,11 @@ struct WorkspaceSnippetsView: View {
|
||||
} catch { self.error = error.localizedDescription }
|
||||
}
|
||||
}.disabled(capturing || address.isEmpty)
|
||||
Button("Open Rendered Page…") {
|
||||
do { renderedPage = RenderedClipPage(url: try WebClipCapture.pageURL(address)) }
|
||||
catch { self.error = error.localizedDescription }
|
||||
}
|
||||
.disabled(capturing || address.isEmpty)
|
||||
}
|
||||
}
|
||||
TextEditor(text: $content).accessibilityLabel("\(kind.rawValue) text")
|
||||
@@ -1528,6 +1608,9 @@ struct WorkspaceSnippetsView: View {
|
||||
.onChange(of: id) { _, value in
|
||||
if let item = studio.snippets.first(where: { $0.id == value }) {
|
||||
title = item.title
|
||||
notes = item.notes
|
||||
tags = item.tags
|
||||
versions = kind == .prompt ? studio.promptVersions(item.id) : []
|
||||
if kind == .webClip {
|
||||
let parts = item.content.components(separatedBy: "\n\n")
|
||||
address = String((parts.first ?? "").dropFirst("Source: ".count))
|
||||
@@ -1537,6 +1620,14 @@ struct WorkspaceSnippetsView: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
.sheet(item: $renderedPage) { page in
|
||||
RenderedClipView(url: page.url) { finalURL, pageTitle, text in
|
||||
address = finalURL.absoluteString
|
||||
if title.isEmpty { title = pageTitle }
|
||||
content = text
|
||||
error = ""
|
||||
}
|
||||
}
|
||||
.fileImporter(isPresented: $importing, allowedContentTypes: [
|
||||
.plainText, UTType(filenameExtension: "md") ?? .plainText
|
||||
]) { result in
|
||||
@@ -1582,12 +1673,75 @@ struct WorkspaceSnippetsView: View {
|
||||
}
|
||||
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)
|
||||
studio.saveSnippet(id: key, kind: kind, title: title.trimmingCharacters(in: .whitespacesAndNewlines), content: stored, notes: notes, tags: tags)
|
||||
id = key
|
||||
if kind == .prompt { versions = studio.promptVersions(key) }
|
||||
error = ""
|
||||
}
|
||||
|
||||
private func clear() { id = nil; title = ""; content = ""; address = ""; error = "" }
|
||||
private func clear() { id = nil; title = ""; content = ""; address = ""; error = ""; notes = ""; tags = ""; versions = [] }
|
||||
}
|
||||
|
||||
private struct RenderedClipPage: Identifiable {
|
||||
let url: URL
|
||||
var id: URL { url }
|
||||
}
|
||||
|
||||
private struct RenderedClipView: View {
|
||||
let url: URL
|
||||
let capture: (URL, String, String) -> Void
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var browser: WKWebView?
|
||||
@State private var error = ""
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Text(browser?.url?.host ?? url.host ?? "Web Page").font(.headline)
|
||||
Spacer()
|
||||
Button("Cancel") { dismiss() }
|
||||
Button("Capture Visible Text", action: captureText)
|
||||
.buttonStyle(.borderedProminent)
|
||||
.disabled(browser == nil)
|
||||
}.padding()
|
||||
if !error.isEmpty { Text(error).foregroundStyle(.red).padding(.horizontal) }
|
||||
if let browser {
|
||||
ClipBrowserView(browser: browser)
|
||||
}
|
||||
}
|
||||
.frame(width: 800, height: 570)
|
||||
.onAppear {
|
||||
guard browser == nil else { return }
|
||||
let configuration = WKWebViewConfiguration()
|
||||
configuration.websiteDataStore = .nonPersistent()
|
||||
let view = WKWebView(frame: .zero, configuration: configuration)
|
||||
browser = view
|
||||
view.load(URLRequest(url: url))
|
||||
}
|
||||
}
|
||||
|
||||
private func captureText() {
|
||||
guard let browser, let url = browser.url,
|
||||
(try? WebClipCapture.url(url.absoluteString)) != nil else {
|
||||
error = "Wait for an HTTP or HTTPS page to load."
|
||||
return
|
||||
}
|
||||
browser.evaluateJavaScript("document.body?.innerText?.slice(0, 12000) ?? ''") { result, failure in
|
||||
guard browser.url == url, let text = result as? String,
|
||||
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
error = failure?.localizedDescription ?? "The page has no readable text yet."
|
||||
return
|
||||
}
|
||||
capture(url, browser.title ?? url.host ?? "Web Clip", text)
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct ClipBrowserView: NSViewRepresentable {
|
||||
let browser: WKWebView
|
||||
func makeNSView(context: Context) -> WKWebView { browser }
|
||||
func updateNSView(_ view: WKWebView, context: Context) {}
|
||||
}
|
||||
|
||||
enum StudioTheme: String, CaseIterable, Identifiable {
|
||||
@@ -1662,6 +1816,43 @@ struct StudioSettingsView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private enum StudioShortcut: String, CaseIterable, Identifiable {
|
||||
case increase, decrease, reset, theme, workspaceMode
|
||||
|
||||
var id: Self { self }
|
||||
|
||||
var title: String {
|
||||
switch self {
|
||||
case .increase: "Increase chat font"
|
||||
case .decrease: "Decrease chat font"
|
||||
case .reset: "Reset chat font"
|
||||
case .theme: "Cycle theme"
|
||||
case .workspaceMode: "Cycle workspace mode"
|
||||
}
|
||||
}
|
||||
|
||||
var defaultKey: String {
|
||||
switch self {
|
||||
case .increase: "="
|
||||
case .decrease: "-"
|
||||
case .reset: "0"
|
||||
case .theme: "3"
|
||||
case .workspaceMode: "9"
|
||||
}
|
||||
}
|
||||
|
||||
static let choices = ["=", "-", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
||||
|
||||
func key(in data: Data) -> String {
|
||||
let saved = (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:]
|
||||
return saved[rawValue].flatMap { Self.choices.contains($0) ? $0 : nil } ?? defaultKey
|
||||
}
|
||||
|
||||
func shortcut(in data: Data) -> KeyEquivalent {
|
||||
KeyEquivalent(key(in: data).first ?? "0")
|
||||
}
|
||||
}
|
||||
|
||||
struct StudioAppearanceView: View {
|
||||
@AppStorage("studioTheme") private var theme = StudioTheme.system
|
||||
@AppStorage("studioAccent") private var accent = StudioAccent.storm
|
||||
@@ -1675,6 +1866,10 @@ struct StudioAppearanceView: View {
|
||||
@AppStorage("composerSpellCheck") private var spell = true
|
||||
@AppStorage("composerAutoCorrect") private var correct = false
|
||||
@State private var query = ""
|
||||
@AppStorage("studioShortcutKeys") private var shortcutData = Data()
|
||||
@AppStorage("renderChatMarkdown") private var renderMarkdown = true
|
||||
@AppStorage("compactChatMessages") private var compactMessages = false
|
||||
@AppStorage("expandChatThinking") private var expandThinking = false
|
||||
@State private var draft: StudioCustomTheme?
|
||||
|
||||
private var customThemes: [StudioCustomTheme] {
|
||||
@@ -1730,15 +1925,35 @@ struct StudioAppearanceView: View {
|
||||
}
|
||||
.disabled(!customThemeID.isEmpty)
|
||||
}
|
||||
Section("Chat Display") {
|
||||
Toggle("Render Markdown", isOn: $renderMarkdown)
|
||||
Toggle("Compact messages", isOn: $compactMessages)
|
||||
Toggle("Expand thinking by default", isOn: $expandThinking)
|
||||
}
|
||||
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)
|
||||
ForEach(StudioShortcut.allCases.filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }) { action in
|
||||
Picker(action.title, selection: Binding(
|
||||
get: { action.key(in: shortcutData) },
|
||||
set: { key in
|
||||
var saved = (try? JSONDecoder().decode([String: String].self, from: shortcutData)) ?? [:]
|
||||
saved[action.rawValue] = key
|
||||
if let data = try? JSONEncoder().encode(saved) { shortcutData = data }
|
||||
}
|
||||
)) {
|
||||
let used = Set(StudioShortcut.allCases.filter { $0 != action }.map { $0.key(in: shortcutData) })
|
||||
ForEach(StudioShortcut.choices.filter { !used.contains($0) }, id: \.self) { key in
|
||||
Text("⌘ \(key)").tag(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
Button("Reset Shortcuts") { shortcutData = Data() }
|
||||
LabeledContent("Send chat message", value: "Return")
|
||||
LabeledContent("Insert newline", value: "⇧ Return")
|
||||
}
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
@@ -1771,11 +1986,7 @@ struct StudioAppearanceView: View {
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -1786,6 +1997,8 @@ struct WorkspaceDataView: View {
|
||||
@State private var pending: URL?
|
||||
@State private var confirm = false
|
||||
@State private var status = ""
|
||||
@State private var backups: [URL] = []
|
||||
@AppStorage("workspaceLocation") private var workspaceLocation = ""
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
@@ -1804,12 +2017,35 @@ struct WorkspaceDataView: View {
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
Section("Storage") {
|
||||
Text(StudioModel.workspaceDirectory.path).textSelection(.enabled)
|
||||
Text(workspaceLocation.isEmpty ? StudioModel.workspaceDirectory.path : workspaceLocation).textSelection(.enabled)
|
||||
Button("Reveal Workspace in Finder") { NSWorkspace.shared.activateFileViewerSelecting([StudioModel.workspaceDirectory]) }
|
||||
Button("Change Workspace Folder…") {
|
||||
chooseFolder { folder in
|
||||
try studio.relocateWorkspace(to: folder)
|
||||
status = "Workspace copied and opened at the new location."
|
||||
}
|
||||
}
|
||||
.disabled(studio.running || studio.importingDocument)
|
||||
}
|
||||
Section("Restore") {
|
||||
Button("Choose Backup…") { restoring = true }
|
||||
.disabled(studio.running || studio.importingDocument)
|
||||
Button("Scan Folder for Backups…") {
|
||||
chooseFolder { folder in
|
||||
let files = try FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isRegularFileKey], options: .skipsHiddenFiles)
|
||||
backups = files.filter {
|
||||
["sqlite", "sqlite3", "db"].contains($0.pathExtension.lowercased()) && Store.isWorkspaceBackup($0)
|
||||
}.sorted { $0.lastPathComponent.localizedStandardCompare($1.lastPathComponent) == .orderedAscending }
|
||||
status = "Found \(backups.count) workspace backups."
|
||||
}
|
||||
}
|
||||
ForEach(backups, id: \.self) { url in
|
||||
Button(url.lastPathComponent) { pending = url; confirm = true }
|
||||
.disabled(studio.running || studio.importingDocument)
|
||||
.help(url.path)
|
||||
}
|
||||
Button("Import Msty Studio Chats…", action: importMsty)
|
||||
.disabled(studio.running || studio.importingDocument)
|
||||
if !status.isEmpty { Text(status).textSelection(.enabled).foregroundStyle(.secondary) }
|
||||
}
|
||||
}
|
||||
@@ -1825,6 +2061,29 @@ struct WorkspaceDataView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private func chooseFolder(_ action: @escaping (URL) throws -> Void) {
|
||||
let panel = NSOpenPanel()
|
||||
panel.canChooseDirectories = true
|
||||
panel.canChooseFiles = false
|
||||
panel.canCreateDirectories = true
|
||||
panel.begin { result in
|
||||
guard result == .OK, let url = panel.url else { return }
|
||||
do { try action(url) }
|
||||
catch { status = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
private func importMsty() {
|
||||
let panel = NSOpenPanel()
|
||||
panel.allowedContentTypes = UTType(filenameExtension: "db").map { [$0] } ?? [.data]
|
||||
panel.directoryURL = URL.applicationSupportDirectory.appending(path: "MstyStudio/data/workspaces/default")
|
||||
panel.begin { result in
|
||||
guard result == .OK, let url = panel.url else { return }
|
||||
do { status = "Imported \(try studio.importMstyChats(from: url)) Msty chat threads." }
|
||||
catch { status = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
private func export() {
|
||||
let panel = NSSavePanel()
|
||||
panel.nameFieldStringValue = "AIStudio-Workspace-\(Date.now.formatted(.iso8601.year().month().day())).sqlite"
|
||||
|
||||
+122
-8
@@ -20,6 +20,17 @@ struct WorkspaceSnippet: Identifiable {
|
||||
let kind: Kind
|
||||
let title: String
|
||||
let content: String
|
||||
var notes = ""
|
||||
var tags = ""
|
||||
}
|
||||
|
||||
struct PromptVersion: Identifiable {
|
||||
let id: String
|
||||
let savedAt: String
|
||||
let title: String
|
||||
let content: String
|
||||
let notes: String
|
||||
let tags: String
|
||||
}
|
||||
|
||||
final class Store {
|
||||
@@ -67,6 +78,21 @@ final class Store {
|
||||
DELETE FROM document_index WHERE document=old.id;
|
||||
END;
|
||||
""")
|
||||
try preparePromptLibrary()
|
||||
}
|
||||
|
||||
private func preparePromptLibrary() throws {
|
||||
try execute("""
|
||||
CREATE TABLE IF NOT EXISTS prompt_metadata (
|
||||
prompt TEXT PRIMARY KEY REFERENCES workspace_snippets(id) ON DELETE CASCADE,
|
||||
notes TEXT NOT NULL, tags TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS prompt_versions (
|
||||
id TEXT PRIMARY KEY, prompt TEXT NOT NULL REFERENCES workspace_snippets(id) ON DELETE CASCADE,
|
||||
saved_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
title TEXT NOT NULL, content TEXT NOT NULL, notes TEXT NOT NULL, tags TEXT NOT NULL
|
||||
);
|
||||
""")
|
||||
}
|
||||
|
||||
deinit { sqlite3_close(db) }
|
||||
@@ -113,11 +139,11 @@ final class Store {
|
||||
}
|
||||
|
||||
func snippets() throws -> [WorkspaceSnippet] {
|
||||
try query("SELECT id,kind,title,content FROM workspace_snippets ORDER BY rowid DESC") {
|
||||
try query("SELECT s.id,s.kind,s.title,s.content,m.notes,m.tags FROM workspace_snippets s LEFT JOIN prompt_metadata m ON m.prompt=s.id ORDER BY s.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))
|
||||
return WorkspaceSnippet(id: try uuid($0, 0), kind: kind, title: string($0, 2), content: string($0, 3), notes: string($0, 4), tags: string($0, 5))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,6 +154,31 @@ final class Store {
|
||||
""", [id.uuidString, kind.rawValue, title, content])
|
||||
}
|
||||
|
||||
func promptVersions(_ id: UUID) throws -> [PromptVersion] {
|
||||
try query("SELECT id,saved_at,title,content,notes,tags FROM prompt_versions WHERE prompt=? ORDER BY rowid DESC", [id.uuidString]) {
|
||||
PromptVersion(id: string($0, 0), savedAt: string($0, 1), title: string($0, 2),
|
||||
content: string($0, 3), notes: string($0, 4), tags: string($0, 5))
|
||||
}
|
||||
}
|
||||
|
||||
func savePrompt(id: UUID, title: String, content: String, notes: String, tags: String) throws {
|
||||
try execute("BEGIN IMMEDIATE")
|
||||
do {
|
||||
try saveSnippet(id: id, kind: .prompt, title: title, content: content)
|
||||
try mutate("""
|
||||
INSERT INTO prompt_metadata(prompt,notes,tags) VALUES(?,?,?)
|
||||
ON CONFLICT(prompt) DO UPDATE SET notes=excluded.notes, tags=excluded.tags
|
||||
""", [id.uuidString, notes, tags])
|
||||
try mutate("""
|
||||
INSERT INTO prompt_versions(id,prompt,title,content,notes,tags) VALUES(?,?,?,?,?,?)
|
||||
""", [UUID().uuidString, id.uuidString, title, content, notes, tags])
|
||||
try execute("COMMIT")
|
||||
} catch {
|
||||
try? execute("ROLLBACK")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
func deleteSnippet(_ id: UUID) throws {
|
||||
try mutate("DELETE FROM workspace_snippets WHERE id=?", [id.uuidString])
|
||||
}
|
||||
@@ -250,6 +301,73 @@ final class Store {
|
||||
return excerpts
|
||||
}
|
||||
|
||||
static func isWorkspaceBackup(_ url: URL) -> Bool {
|
||||
var input: OpaquePointer?
|
||||
let result = sqlite3_open_v2(url.path, &input, SQLITE_OPEN_READONLY, nil)
|
||||
defer { if let input { sqlite3_close(input) } }
|
||||
guard result == SQLITE_OK, let input else { return false }
|
||||
return hasWorkspaceSchema(input)
|
||||
}
|
||||
|
||||
private static func hasWorkspaceSchema(_ input: OpaquePointer) -> Bool {
|
||||
let sql = "SELECT count(*) FROM sqlite_master WHERE type='table' AND name IN ('chats','messages','documents','workspace_snippets','knowledge_stacks')"
|
||||
var statement: OpaquePointer?
|
||||
guard sqlite3_prepare_v2(input, sql, -1, &statement, nil) == SQLITE_OK, let statement else { return false }
|
||||
defer { sqlite3_finalize(statement) }
|
||||
return sqlite3_step(statement) == SQLITE_ROW && sqlite3_column_int(statement, 0) == 5
|
||||
}
|
||||
|
||||
func importMstyChats(from url: URL) throws -> Int {
|
||||
var input: OpaquePointer?
|
||||
let opened = sqlite3_open_v2(url.path, &input, SQLITE_OPEN_READONLY, nil)
|
||||
defer { if let input { sqlite3_close(input) } }
|
||||
guard opened == SQLITE_OK, let input else { throw StudioError("Could not open the Msty database.") }
|
||||
let sql = """
|
||||
SELECT s.id, c.title, m.role, m.content
|
||||
FROM conversationTexts c
|
||||
JOIN conversationTextChatSplits s ON s.conversationId = c.id
|
||||
JOIN conversationTextMessages m ON m.chatSplitId = s.id
|
||||
WHERE m.role IN ('user','assistant') AND length(m.content) > 0
|
||||
ORDER BY c.createdAt, s.createdAt, s.id, m.createdAt, m.rowid
|
||||
"""
|
||||
var statement: OpaquePointer?
|
||||
guard sqlite3_prepare_v2(input, sql, -1, &statement, nil) == SQLITE_OK, let statement else {
|
||||
throw StudioError("The database does not match the supported Msty Studio chat format.")
|
||||
}
|
||||
defer { sqlite3_finalize(statement) }
|
||||
try execute("BEGIN IMMEDIATE")
|
||||
var count = 0
|
||||
do {
|
||||
try execute("CREATE TABLE IF NOT EXISTS msty_imports (source_id TEXT PRIMARY KEY)")
|
||||
var previous = ""
|
||||
var destination: UUID?
|
||||
while true {
|
||||
let step = sqlite3_step(statement)
|
||||
if step == SQLITE_DONE { break }
|
||||
guard step == SQLITE_ROW else { throw StudioError("The Msty chat database could not be read.") }
|
||||
let split = string(statement, 0)
|
||||
if split != previous {
|
||||
previous = split
|
||||
destination = nil
|
||||
let exists = try query("SELECT source_id FROM msty_imports WHERE source_id=?", [split]) { string($0, 0) }
|
||||
if exists.isEmpty {
|
||||
destination = try create(title: String(string(statement, 1).prefix(100))).id
|
||||
try mutate("INSERT INTO msty_imports(source_id) VALUES(?)", [split])
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
if let destination, let role = Role(rawValue: string(statement, 2)) {
|
||||
try save(Message(role: role, content: string(statement, 3)), in: destination)
|
||||
}
|
||||
}
|
||||
try execute("COMMIT")
|
||||
return count
|
||||
} catch {
|
||||
try? execute("ROLLBACK")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
func exportWorkspace(to url: URL) throws {
|
||||
guard !FileManager.default.fileExists(atPath: url.path) else {
|
||||
throw StudioError("Choose a new filename for the workspace backup.")
|
||||
@@ -265,14 +383,9 @@ final class Store {
|
||||
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 {
|
||||
guard Self.hasWorkspaceSchema(input) 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.") }
|
||||
@@ -283,6 +396,7 @@ final class Store {
|
||||
let step = sqlite3_backup_step(backup, -1)
|
||||
let finish = sqlite3_backup_finish(backup)
|
||||
guard step == SQLITE_DONE, finish == SQLITE_OK else { throw failure }
|
||||
try preparePromptLibrary()
|
||||
}
|
||||
|
||||
private func execute(_ sql: String) throws {
|
||||
|
||||
@@ -84,6 +84,10 @@ final class StudioModel: ObservableObject {
|
||||
catch { status = error.localizedDescription }
|
||||
}
|
||||
|
||||
func conversationMessages(_ id: UUID) -> [Message] {
|
||||
(try? store?.messages(in: id)) ?? []
|
||||
}
|
||||
|
||||
func searchConversations(_ term: String) -> [Conversation] {
|
||||
(try? store?.searchConversations(term)) ?? []
|
||||
}
|
||||
@@ -341,7 +345,29 @@ final class StudioModel: ObservableObject {
|
||||
}
|
||||
|
||||
static var workspaceDirectory: URL {
|
||||
URL.applicationSupportDirectory.appending(path: "AIStudio", directoryHint: .isDirectory)
|
||||
if let path = UserDefaults.standard.string(forKey: "workspaceLocation"), !path.isEmpty {
|
||||
return URL(fileURLWithPath: path, isDirectory: true)
|
||||
}
|
||||
return URL.applicationSupportDirectory.appending(path: "AIStudio", directoryHint: .isDirectory)
|
||||
}
|
||||
|
||||
func relocateWorkspace(to folder: URL, defaults: UserDefaults = .standard) throws {
|
||||
guard !running, !importingDocument else { throw StudioError("Wait for the current operation to finish.") }
|
||||
let url = folder.appending(path: "studio.sqlite")
|
||||
try database().exportWorkspace(to: url)
|
||||
let relocated = try Store(url: url)
|
||||
_ = try relocated.conversations()
|
||||
store = relocated
|
||||
defaults.set(folder.path, forKey: "workspaceLocation")
|
||||
try refreshWorkspace()
|
||||
}
|
||||
|
||||
func importMstyChats(from url: URL) throws -> Int {
|
||||
guard !running, !importingDocument else { throw StudioError("Wait for the current operation to finish.") }
|
||||
let count = try database().importMstyChats(from: url)
|
||||
conversations = try database().conversations()
|
||||
if selected == nil { selected = conversations.first?.id }
|
||||
return count
|
||||
}
|
||||
|
||||
func exportWorkspace(to url: URL) throws {
|
||||
@@ -412,9 +438,22 @@ final class StudioModel: ObservableObject {
|
||||
} catch { workspaceStatus = error.localizedDescription }
|
||||
}
|
||||
|
||||
func saveSnippet(id: UUID, kind: WorkspaceSnippet.Kind, title: String, content: String) {
|
||||
func promptVersions(_ id: UUID) -> [PromptVersion] {
|
||||
(try? database().promptVersions(id)) ?? []
|
||||
}
|
||||
|
||||
func saveSnippet(id: UUID, kind: WorkspaceSnippet.Kind, title: String, content: String,
|
||||
notes: String = "", tags: String = "") {
|
||||
do {
|
||||
try database().saveSnippet(id: id, kind: kind, title: String(title.prefix(100)), content: String(content.prefix(12000)))
|
||||
let store = try database()
|
||||
let title = String(title.prefix(100))
|
||||
let content = String(content.prefix(12000))
|
||||
if kind == .prompt {
|
||||
try store.savePrompt(id: id, title: title, content: content,
|
||||
notes: String(notes.prefix(1000)), tags: String(tags.prefix(250)))
|
||||
} else {
|
||||
try store.saveSnippet(id: id, kind: kind, title: title, content: content)
|
||||
}
|
||||
try refreshWorkspace()
|
||||
workspaceStatus = ""
|
||||
} catch { workspaceStatus = error.localizedDescription }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import XCTest
|
||||
import AppKit
|
||||
import SQLite3
|
||||
@testable import AIStudio
|
||||
|
||||
final class StudioTests: XCTestCase {
|
||||
@@ -335,6 +336,36 @@ final class ExpandedStudioTests: XCTestCase {
|
||||
}
|
||||
|
||||
final class WorkspaceExperienceTests: XCTestCase {
|
||||
func testMstyImportAndPromptHistory() 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 source = folder.appending(path: "msty.db")
|
||||
var db: OpaquePointer?
|
||||
XCTAssertEqual(sqlite3_open(source.path, &db), SQLITE_OK)
|
||||
let sql = """
|
||||
CREATE TABLE conversationTexts(id,title,createdAt);
|
||||
CREATE TABLE conversationTextChatSplits(id,conversationId,createdAt);
|
||||
CREATE TABLE conversationTextMessages(chatSplitId,role,content,createdAt);
|
||||
INSERT INTO conversationTexts VALUES('chat','Imported','1');
|
||||
INSERT INTO conversationTextChatSplits VALUES('split','chat','1');
|
||||
INSERT INTO conversationTextMessages VALUES('split','user','Question','1'),('split','assistant','Answer','2');
|
||||
"""
|
||||
let result = sqlite3_exec(db, sql, nil, nil, nil)
|
||||
sqlite3_close(db)
|
||||
XCTAssertEqual(result, SQLITE_OK)
|
||||
let store = try Store(url: folder.appending(path: "studio.sqlite"))
|
||||
XCTAssertEqual(try store.importMstyChats(from: source), 1)
|
||||
XCTAssertEqual(try store.importMstyChats(from: source), 0)
|
||||
let chat = try XCTUnwrap(store.conversations().first)
|
||||
XCTAssertEqual(try store.messages(in: chat.id).map(\.content), ["Question", "Answer"])
|
||||
let prompt = UUID()
|
||||
try store.savePrompt(id: prompt, title: "Prompt", content: "First", notes: "", tags: "")
|
||||
try store.savePrompt(id: prompt, title: "Prompt", content: "Second", notes: "Edited", tags: "swift")
|
||||
XCTAssertEqual(try store.snippets().first?.tags, "swift")
|
||||
XCTAssertEqual(try store.promptVersions(prompt).map(\.content), ["Second", "First"])
|
||||
}
|
||||
|
||||
func testPromptBuilderRendersOnlyPopulatedSectionsInOrder() {
|
||||
var draft = PromptDraft()
|
||||
draft.role = " Teacher "
|
||||
@@ -421,6 +452,21 @@ final class CompatibleEndpointTests: XCTestCase {
|
||||
XCTAssertNoThrow(try CompatibleEndpoint(endpoint: "http://127.0.0.1:1234/v1"))
|
||||
}
|
||||
|
||||
func testLiveLMStudioDiscoveryAndStreaming() async throws {
|
||||
let env = ProcessInfo.processInfo.environment
|
||||
guard let endpoint = env["AISTUDIO_TEST_LM_STUDIO_URL"],
|
||||
let model = env["AISTUDIO_TEST_LM_STUDIO_MODEL"] else {
|
||||
throw XCTSkip("Configure a running LM Studio server and loaded model.")
|
||||
}
|
||||
let client = try CompatibleEndpoint(endpoint: endpoint, token: "")
|
||||
let models = try await client.models()
|
||||
XCTAssertTrue(models.contains(model))
|
||||
let output = try await collect(client.generate(InferenceRequest(model: model, messages: [
|
||||
Message(role: .user, content: "Reply with only OK. /no_think")
|
||||
], thinking: .off, parameters: GenerationParameters(temperature: 0, maxTokens: 64))))
|
||||
XCTAssertTrue(output.contains { if case .answer(let answer) = $0 { return !answer.isEmpty }; return false })
|
||||
}
|
||||
|
||||
func testAuthenticatedDiscoveryAndStreaming() async throws {
|
||||
guard let endpoint = ProcessInfo.processInfo.environment["AISTUDIO_TEST_COMPATIBLE_URL"] else {
|
||||
throw XCTSkip("Set AISTUDIO_TEST_COMPATIBLE_URL to the compatible endpoint fixture.")
|
||||
@@ -850,6 +896,30 @@ final class ConnectedChatTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testWorkspaceRelocationPreservesDatabase() throws {
|
||||
let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
||||
let defaults = try XCTUnwrap(UserDefaults(suiteName: root.lastPathComponent))
|
||||
defer {
|
||||
defaults.removePersistentDomain(forName: root.lastPathComponent)
|
||||
try? FileManager.default.removeItem(at: root)
|
||||
}
|
||||
let studio = StudioModel()
|
||||
let original = root.appending(path: "original.sqlite")
|
||||
studio.open(databaseURL: original)
|
||||
studio.newChat()
|
||||
let first = try XCTUnwrap(studio.selected)
|
||||
let target = root.appending(path: "Relocated")
|
||||
try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)
|
||||
try studio.relocateWorkspace(to: target, defaults: defaults)
|
||||
XCTAssertEqual(defaults.string(forKey: "workspaceLocation"), target.path)
|
||||
let copy = target.appending(path: "studio.sqlite")
|
||||
XCTAssertTrue(Store.isWorkspaceBackup(copy))
|
||||
XCTAssertEqual(try Store(url: copy).conversations().map(\.id), [first])
|
||||
XCTAssertEqual(try Store(url: original).conversations().map(\.id), [first])
|
||||
XCTAssertThrowsError(try studio.relocateWorkspace(to: target, defaults: defaults))
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testDeleteChatTargetsRequestedConversation() throws {
|
||||
let folder = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
|
||||
|
||||
Reference in New Issue
Block a user