Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ public extension TextViewController {
textView.replaceCharacters(in: span, with: rebuilt, skipUpdateSelection: true)
}

// A key command's edit, as Vim's are: a plain replace that leaves undo grouping and the selection to the text view,
// with no typing filters and no suggestion triggers.
func replaceCharactersUnfiltered(in range: NSRange, with string: String) {
guard let textView else { return }
let wasUnfiltered = isApplyingUnfilteredEdits
isApplyingUnfilteredEdits = true
defer { isApplyingUnfilteredEdits = wasUnfiltered }
textView.replaceCharacters(in: range, with: string)
}

// A command's replacement, unlike `setText`, keeps the undo history: one undo group, no typing filters, no
// suggestion triggers. The binding gets the text before this returns, so a run right after reads it.
@discardableResult
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ public class TextViewController: NSViewController {
/// The gutter's width is reserved on the clip view, so the clip view's own origin moves whenever the gutter shows,
/// hides or gains a digit. This is the position ``SourceEditorState`` records and restores, so a saved position
/// means the same text regardless.
var scrollPosition: CGPoint {
public var scrollPosition: CGPoint {
get {
let origin = scrollView.contentView.bounds.origin
return CGPoint(x: origin.x + scrollView.floatingSubviewInsets.left, y: origin.y)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import AppKit
@testable import TableProEditorKit
import TableProTextEngine
import Testing

@MainActor
struct ReplaceCharactersUnfilteredTests {
@Test("A key command's open bracket over a character replaces it and wraps nothing")
func openBracketReplacesTheCharacter() {
let controller = Mock.loadedTextViewController(string: "a x b")
controller.replaceCharactersUnfiltered(in: NSRange(location: 2, length: 1), with: "(")
#expect(controller.textView.string == "a ( b")
}

@Test("A key command's delete of an open bracket leaves the closing one")
func deletingAnOpenBracketKeepsTheCloser() {
let controller = Mock.loadedTextViewController(string: "COUNT()")
controller.replaceCharactersUnfiltered(in: NSRange(location: 5, length: 1), with: "")
#expect(controller.textView.string == "COUNT)")
}

@Test("Typing after a key command's edit still runs the typing filters")
func typingAfterwardIsFiltered() {
let controller = Mock.loadedTextViewController(string: "")
controller.replaceCharactersUnfiltered(in: NSRange(location: 0, length: 0), with: "\t")
#expect(controller.textView.string == "\t")

controller.textView.replaceCharacters(in: NSRange(location: 1, length: 0), with: "\t")
#expect(controller.textView.string == "\t ")
}

@Test("A key command's edit is undoable")
func editIsUndoable() {
let (window, controller) = Mock.focusedTextViewController(string: "a x b")
defer { window.orderOut(nil) }
controller.replaceCharactersUnfiltered(in: NSRange(location: 2, length: 1), with: "(")
controller.textView.undoManager?.undo()
#expect(controller.textView.string == "a x b")
}
}
18 changes: 15 additions & 3 deletions apple/TablePro/Core/AI/Chat/ChatToolArgumentDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,19 @@
import Foundation
import TableProMCP

/// Typed decoders for `JsonValue` input arguments coming from the AI.
/// Mirrors `MCPArgumentDecoder` for the MCP protocol but operates on the
/// chat-side `JsonValue` enum.
enum ChatToolArgumentDecoder {
// Refused, not ignored: the approval card reads the input, so an ignored key can name a target the call never uses.
static func rejectUnknownKeys(_ args: JsonValue, declaredBy schema: JsonValue) throws {
guard case .object(let dict) = args else { return }
// Undeclared, and `ChatToolTarget` refuses any connection but the session's.
var allowed: Set<String> = ["connection_id"]
if case .object(let root) = schema, case .object(let properties)? = root["properties"] {
allowed.formUnion(properties.keys)
}
let unknown = dict.keys.filter { !allowed.contains($0) }.sorted()
guard unknown.isEmpty else { throw ChatToolArgumentError.unknownKeys(unknown) }
}

static func requireString(_ args: JsonValue, key: String) throws -> String {
guard case .object(let dict) = args, let value = dict[key], case .string(let str) = value else {
throw ChatToolArgumentError.missingOrInvalid(key: key, expected: "string")
Expand Down Expand Up @@ -60,11 +69,14 @@ enum ChatToolArgumentDecoder {

enum ChatToolArgumentError: Error, LocalizedError {
case missingOrInvalid(key: String, expected: String)
case unknownKeys([String])

var errorDescription: String? {
switch self {
case .missingOrInvalid(let key, let expected):
return "Argument '\(key)' is missing or not a \(expected)"
case .unknownKeys(let keys):
return "Unknown argument(s): \(keys.joined(separator: ", ")). Pass only the arguments this tool declares."
}
}
}
28 changes: 26 additions & 2 deletions apple/TablePro/Core/AI/Chat/ChatToolCallRepair.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@

import Foundation

// Providers reject a request in which a tool call has no result. A stopped round, or a transcript
// saved by a build that left one open, must still be sendable.
// Providers reject a request in which a tool call has no result, or a result has no call. A stopped round, a
// transcript saved by a build that left one open, or one cut short on disk must still be sendable.
enum ChatToolCallRepair {
static let interruptedContent = "This tool call was interrupted before it returned a result."
static let stoppedBeforeRunContent = "The user stopped the response before this tool call ran."
Expand All @@ -18,6 +18,9 @@ enum ChatToolCallRepair {

for (index, original) in turns.enumerated() {
var turn = original
if turn.role == .user {
turn.blocks = droppingOrphanResults(turn.blocks, after: repaired.last)
}
if !owed.isEmpty {
if turn.role == .user, !toolResultIds(in: turn).isEmpty {
turn.blocks.insert(contentsOf: owed.map { .toolResult($0) }, at: 0)
Expand All @@ -26,6 +29,8 @@ enum ChatToolCallRepair {
}
owed = []
}
// A turn that held only results for calls no longer in the transcript has nothing left to send.
if turn.blocks.isEmpty, !original.blocks.isEmpty { continue }
repaired.append(turn)
guard turn.role == .assistant else { continue }
owed = unansweredResults(for: turn, next: index + 1 < turns.count ? turns[index + 1] : nil)
Expand Down Expand Up @@ -89,6 +94,25 @@ enum ChatToolCallRepair {
}
}

// A result answers a call only in the turn right after it.
private static func droppingOrphanResults(
_ blocks: [ChatContentBlockWire],
after previous: ChatTurnWire?
) -> [ChatContentBlockWire] {
let calls = previous?.role == .assistant ? toolUseIds(in: previous) : []
return blocks.filter { block in
guard case .toolResult(let result) = block.kind else { return true }
return calls.contains(result.toolUseId)
}
}

private static func toolUseIds(in turn: ChatTurnWire?) -> Set<String> {
Set((turn?.blocks ?? []).compactMap { block -> String? in
guard case .toolUse(let call) = block.kind else { return nil }
return call.id
})
}

private static func toolResultIds(in turn: ChatTurnWire) -> Set<String> {
Set(turn.blocks.compactMap { block -> String? in
guard case .toolResult(let result) = block.kind else { return nil }
Expand Down
6 changes: 6 additions & 0 deletions apple/TablePro/Core/AI/Chat/ChatToolRegistry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ final class ChatToolRegistry {
allTools(for: mode).map(\.spec)
}

// An outside server's tool is `.readOnly` only so every mode offers it; it may write anything.
func onlyReads(toolName: String) -> Bool {
guard let tool = tools[toolName], !(tool is MCPRemoteToolAdapter) else { return false }
return tool.mode == .readOnly
}

func requiresApproval(toolName: String) -> Bool {
guard let tool = tools[toolName] else { return true }
return tool.mode.requiresApproval
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,26 @@ struct ConfirmDestructiveOperationChatTool: ChatTool {
"query": ChatToolSchemaBuilder.string(description: "The destructive query to execute"),
"confirmation_phrase": ChatToolSchemaBuilder.string(
description: "Must be exactly: I understand this is irreversible"
),
"database": ChatToolSchemaBuilder.string(
description: "Run against this database. Pass null to use current.",
optional: true
),
"schema": ChatToolSchemaBuilder.string(
description: "Run against this schema. Pass null to use current.",
optional: true
)
],
required: ["query", "confirmation_phrase"]
]
)
let mode: ChatToolMode = .agentOnly

func execute(input: JsonValue, context: ChatToolContext) async throws -> ChatToolResult {
try ChatToolArgumentDecoder.rejectUnknownKeys(input, declaredBy: inputSchema)
let query = try ChatToolArgumentDecoder.requireString(input, key: "query")
let confirmationPhrase = try ChatToolArgumentDecoder.requireString(input, key: "confirmation_phrase")
// The approval card names these, so the statement runs where the card says.
let database = ChatToolArgumentDecoder.optionalString(input, key: "database")
let schema = ChatToolArgumentDecoder.optionalString(input, key: "schema")

guard confirmationPhrase == Self.requiredPhrase else {
return ChatToolResult(
Expand Down Expand Up @@ -73,8 +84,8 @@ struct ConfirmDestructiveOperationChatTool: ChatTool {
let maxRows = MCPLimitResolver.resolveMaxRows(requested: nil, settings: mcpSettings)
let scope = try await context.bridge.resolveScope(
connectionId: connectionId,
database: nil,
schema: nil
database: database,
schema: schema
)
let planned = try await context.bridge.plannedScript(scope: scope, query: query, maxRows: maxRows)
let operation = try await context.authPolicy.checkSafeModeDialog(
Expand Down
10 changes: 7 additions & 3 deletions apple/TablePro/Core/Compare/CompareObjectResult.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ internal struct CompareObjectResult: Identifiable, Hashable, Sendable {
internal let definitionMatches: Bool
// What the source recorded for a routine or trigger, such as MySQL's sql_mode, set around its CREATE.
internal let sourceCreationScope: PluginStatementScope?
// Why the row is compared but never scripted, such as a definition read from another schema than the target's.
internal let scriptRefusal: String?

internal init(
identity: CompareObjectIdentity,
Expand All @@ -73,7 +75,8 @@ internal struct CompareObjectResult: Identifiable, Hashable, Sendable {
sourceIndexes: [EditableIndexDefinition]? = nil,
targetIndexes: [EditableIndexDefinition]? = nil,
definitionMatches: Bool = false,
sourceCreationScope: PluginStatementScope? = nil
sourceCreationScope: PluginStatementScope? = nil,
scriptRefusal: String? = nil
) {
self.identity = identity
self.status = status
Expand All @@ -86,6 +89,7 @@ internal struct CompareObjectResult: Identifiable, Hashable, Sendable {
self.targetIndexes = targetIndexes
self.definitionMatches = definitionMatches
self.sourceCreationScope = sourceCreationScope
self.scriptRefusal = scriptRefusal
}

// PluginStatementScope is only Equatable; equal results share an identity.
Expand All @@ -110,7 +114,7 @@ internal struct CompareObjectResult: Identifiable, Hashable, Sendable {
internal var isComparable: Bool { comparisonError == nil }

internal var suggestedAction: TableSyncAction {
guard comparisonError == nil else { return .skip }
guard comparisonError == nil, scriptRefusal == nil else { return .skip }
switch status {
case .onlyInSource: return .create
case .onlyInTarget: return .drop
Expand All @@ -120,7 +124,7 @@ internal struct CompareObjectResult: Identifiable, Hashable, Sendable {
}

internal var availableActions: [TableSyncAction] {
guard comparisonError == nil else { return [.skip] }
guard comparisonError == nil, scriptRefusal == nil else { return [.skip] }
switch status {
case .onlyInSource: return [.skip, .create]
case .onlyInTarget: return [.skip, .drop]
Expand Down
10 changes: 8 additions & 2 deletions apple/TablePro/Core/Compare/CompareRunner+Data.swift
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,14 @@ internal extension CompareRunner {
try Task.checkCancellation()

let options = session.structureOptions
let sourceSchema = StructureCompareOptions.listedSchema(
endpoint: context.source.schema, tableSchemas: sourceReads.map(\.table.schema)
)
let targetSchema = StructureCompareOptions.listedSchema(
endpoint: context.target.schema, tableSchemas: targetReads.map(\.table.schema)
)
let targetByKey = Dictionary(
targetReads.map { (options.matchKey(name: $0.table.name, schema: $0.table.schema), $0) },
targetReads.map { (options.matchKey(name: $0.table.name, schema: $0.table.schema, listedIn: targetSchema), $0) },
uniquingKeysWith: { first, _ in first }
)
let previous = Dictionary(
Expand All @@ -204,7 +210,7 @@ internal extension CompareRunner {
var plans: [DataComparePlan] = []
for read in sourceReads {
guard read.failure == nil else { continue }
let pairKey = options.matchKey(name: read.table.name, schema: read.table.schema)
let pairKey = options.matchKey(name: read.table.name, schema: read.table.schema, listedIn: sourceSchema)
guard let counterpart = targetByKey[pairKey], counterpart.failure == nil else { continue }
let plan = makePlan(
read: read,
Expand Down
55 changes: 47 additions & 8 deletions apple/TablePro/Core/Compare/CompareRunner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -328,21 +328,42 @@ internal struct CompareRunner {
$0.snapshot?.droppingCatalogSpellings(ownSchema: context.target.schema)
}

let engine = StructureDiffEngine(options: session.structureOptions)
let tableReport = engine.compare(source: sourceSnapshots, target: targetSnapshots)
let options = session.structureOptions
let sourceSchema = StructureCompareOptions.listedSchema(
endpoint: context.source.schema, tableSchemas: sourceTables.map(\.table.schema)
)
let targetSchema = StructureCompareOptions.listedSchema(
endpoint: context.target.schema, tableSchemas: targetTables.map(\.table.schema)
)
let tableReport = StructureDiffEngine(options: options).compare(
source: sourceSnapshots,
target: targetSnapshots,
sourceSchema: sourceSchema,
targetSchema: targetSchema,
unreadableSource: sourceTables.filter { $0.failure != nil }.map { (name: $0.table.name, schema: $0.table.schema) },
unreadableTarget: targetTables.filter { $0.failure != nil }.map { (name: $0.table.name, schema: $0.table.schema) }
)

let sourceByName = Dictionary(
sourceSnapshots.map { ($0.qualifiedName, $0) }, uniquingKeysWith: { first, _ in first }
)
let targetByName = Dictionary(
targetSnapshots.map { ($0.qualifiedName, $0) }, uniquingKeysWith: { first, _ in first }
)
// A pair across two schemas carries the source's name, so its target is found the way the engine paired it.
let targetByKey = Dictionary(
targetSnapshots.map { (options.matchKey(name: $0.name, schema: $0.schema, listedIn: targetSchema), $0) },
uniquingKeysWith: { first, _ in first }
)

var results = tableReport.results.map { result -> CompareObjectResult in
CompareObjectResult.from(
let target = result.status == .onlyInTarget
? targetByName[result.id]
: targetByKey[options.matchKey(name: result.tableName, schema: result.schema, listedIn: sourceSchema)]
return CompareObjectResult.from(
result,
sourceDefinition: sourceByName[result.id].map(TableDefinitionRenderer.lines) ?? [],
targetDefinition: targetByName[result.id].map(TableDefinitionRenderer.lines) ?? []
targetDefinition: target.map(TableDefinitionRenderer.lines) ?? []
)
}
results += unreadableResults(sourceTables, targetTables)
Expand Down Expand Up @@ -407,7 +428,7 @@ internal struct CompareRunner {
async let targetDefinitions = metadataService.viewDefinitions(
for: context.target, connection: context.targetConnection, views: targetViews
)
results += try await diffEngine.compare(source: sourceDefinitions, target: targetDefinitions)
results += try await Self.compare(sourceDefinitions, targetDefinitions, with: diffEngine, context)
}

if includedKinds.contains(.procedure) || includedKinds.contains(.function) {
Expand All @@ -417,7 +438,7 @@ internal struct CompareRunner {
async let targetRoutines = metadataService.routineReads(
for: context.target, connection: context.targetConnection
)
results += try await diffEngine.compare(source: sourceRoutines, target: targetRoutines)
results += try await Self.compare(sourceRoutines, targetRoutines, with: diffEngine, context)
}

if includedKinds.contains(.trigger) {
Expand All @@ -432,12 +453,26 @@ internal struct CompareRunner {
connection: context.targetConnection,
tables: targetReads.map(\.table.name)
)
results += try await diffEngine.compare(source: sourceTriggers, target: targetTriggers)
results += try await Self.compare(sourceTriggers, targetTriggers, with: diffEngine, context)
}

return results.filter { includedKinds.contains($0.identity.kind) }
}

private static func compare(
_ source: [RoutineSourceRead],
_ target: [RoutineSourceRead],
with engine: SourceObjectDiffEngine,
_ context: Context
) -> [CompareObjectResult] {
engine.compare(
source: source,
target: target,
sourceSchema: StructureCompareOptions.listedSchema(endpoint: context.source.schema, tableSchemas: source.map(\.schema)),
targetSchema: StructureCompareOptions.listedSchema(endpoint: context.target.schema, tableSchemas: target.map(\.schema))
)
}

private func structureStatements(_ context: Context) async throws -> [SyncStatement] {
guard let report = session.report else { return [] }
let snapshots = session.sourceSnapshots
Expand All @@ -449,7 +484,11 @@ internal struct CompareRunner {
case .skip: return nil
case .create:
guard let snapshot = snapshots[result.identity.qualifiedName] else { return nil }
return .createTable(snapshot)
return .createTable(snapshot.placingReferences(
from: snapshot.schema ?? context.source.schema,
into: context.target.schema,
options: session.structureOptions
))
case .drop:
return .dropTable(name: result.identity.name, schema: result.identity.schema)
case .alter:
Expand Down
Loading
Loading