diff --git a/Android/build.sh b/Android/build.sh index 20e38cd..6915c19 100755 --- a/Android/build.sh +++ b/Android/build.sh @@ -20,7 +20,7 @@ platform=${ANDROID_PLATFORM:-35} jar=$sdk/platforms/android-$platform/android.jar [ -f "$jar" ] || { echo "No $jar: install the platform with sdkmanager \"platforms;android-$platform\"." >&2; exit 1; } tools=$(ls -d "$sdk"/build-tools/* | sort -V | tail -1) -version=${APP_VERSION:-0.9.12} +version=${APP_VERSION:-0.9.13} IFS=. read -r major minor patch <<<"$version.0.0" code=$((major * 10000 + minor * 100 + ${patch%%[^0-9]*})) diff --git a/App/AgentInstaller.swift b/App/AgentInstaller.swift index 83565de..a09b406 100644 --- a/App/AgentInstaller.swift +++ b/App/AgentInstaller.swift @@ -417,9 +417,11 @@ struct AgentSettings: View { private func takeConnectAsk() { guard store.connectAgentAsked else { return } store.connectAgentAsked = false + let place: AgentSetupTarget.Place = store.connectAgentPlace == "docker" ? .docker : store.connectAgentPlace == "remote" ? .remote : .here + store.connectAgentPlace = "" let reporters = AgentReporter.all let here = reporters.filter { $0.state != .agentMissing } - setup = AgentSetupTarget(agent: here.first?.id ?? reporters.first?.id ?? "claude-code", place: .here) + setup = AgentSetupTarget(agent: here.first?.id ?? reporters.first?.id ?? "claude-code", place: place) } @ViewBuilder private func hereRow(_ reporter: AgentReporter) -> some View { diff --git a/App/CommandPaletteView.swift b/App/CommandPaletteView.swift index 77f1714..c6f5e14 100644 --- a/App/CommandPaletteView.swift +++ b/App/CommandPaletteView.swift @@ -27,6 +27,7 @@ extension AppStore { case "settings": openSettings(part: rest) case "connect-agent": + connectAgentPlace = rest connectAgentAsked = true page = .agents case "add-engine": diff --git a/App/Insights.swift b/App/Insights.swift index 9d5bed2..8a86d35 100644 --- a/App/Insights.swift +++ b/App/Insights.swift @@ -129,6 +129,9 @@ struct Insight: Codable, Equatable, Identifiable { /// The connected machine it was found on, by name; nil on this machine. Set where the fleet's findings are /// put together, never by the machine that found it. var machine: String? = nil + /// What the finding's own button does, as the command palette names actions ("connect-agent:docker"); nil + /// for a finding with nothing to do but look. + var action: String? = nil /// "Qwen3-Coder-30B · llama.cpp · localhost:8080", and "· on spark" for another machine's. var subject: String { ([model, engine, server] + [machine.map { "on \($0)" } ?? ""]).filter { !$0.isEmpty }.joined(separator: " · ") } @@ -164,6 +167,8 @@ enum Insights { var footprint: [FootprintRules.Finding] = [] /// What the cost rules found (spikes, new keys, caps), with their factors as evidence. var spending: [Insight] = [] + /// Callers of an Engine Proxy that no agent's reporter names (see `UnnamedCallers`). + var unnamed: [Insight] = [] } struct Result: Equatable { @@ -206,6 +211,7 @@ enum Insights { found += queuing(input) found += FootprintRules.insights(input.footprint, now: input.now) found += input.spending + found += input.unnamed return Result(found: found, learning: learning) } @@ -529,7 +535,8 @@ enum Insights { let result = Insights.detect(Insights.Input(rows: RequestLogStore.shared.rows(since: earliest), servers: EngineMonitor.shared.servers.map(StatusReport.server), now: now, sensitivity: level, widened: widened, changes: changes, - footprint: SelfWatch.shared.findings, spending: SpendLedger.shared.findings(now: now))) + footprint: SelfWatch.shared.findings, spending: SpendLedger.shared.findings(now: now), + unnamed: ProxyStore.shared.unnamed(now: now))) apply(result.found, now: now) learning = result.learning } diff --git a/App/InsightsView.swift b/App/InsightsView.swift index 575f61e..444338a 100644 --- a/App/InsightsView.swift +++ b/App/InsightsView.swift @@ -592,7 +592,7 @@ struct InsightCard: View { var body: some View { VStack(alignment: .leading, spacing: 10) { HStack(alignment: .firstTextBaseline, spacing: 8) { - Text(insight.source == "engine" ? "Engine reports" : "Anomaly") + Text(insight.kind == "unnamed" ? "The proxy saw" : insight.source == "engine" ? "Engine reports" : "Anomaly") .font(.sized(.caption2).weight(.semibold)).padding(.horizontal, 7).padding(.vertical, 2) .background(Capsule().fill(tint.opacity(0.18))).foregroundStyle(tint) Text(insight.priority >= 2 ? "High priority" : "Worth knowing").font(.sized(.caption)).foregroundStyle(.secondary) @@ -618,6 +618,10 @@ struct InsightCard: View { Button("Investigate in Doctor") { AppStore.shared.server = "here" } .help(doctor.map { "The Doctor: \($0.title)" } ?? "") } + if let action = insight.action, insight.machine == nil, insight.isOpen { + Button(action.hasPrefix("connect-agent") ? "Connect the Agent…" : "Open") { AppStore.shared.perform(action) } + .buttonStyle(.borderedProminent) + } }.controlSize(.small) } .card() diff --git a/App/Proxy.swift b/App/Proxy.swift index 083b2c8..f649c92 100644 --- a/App/Proxy.swift +++ b/App/Proxy.swift @@ -94,6 +94,9 @@ final class ProxyStore: ObservableObject { /// The address each proxy's latest connection came from, and when, by listen port: Connect an Agent's /// "a request reached the model from the container". private(set) var peers: [Int: (address: String, time: Date)] = [:] + /// Who called the proxies from another address than this machine's, in this run of Tokenmeter: what Insights' + /// "isn't named" finding is made from. + private(set) var callers: [ProxyCaller] = [] #if canImport(Network) private var listeners: [UUID: NWListener] = [:] private let queue = DispatchQueue(label: "tokenmeter.proxy") @@ -167,6 +170,19 @@ final class ProxyStore: ObservableObject { /// Notes where a connection to a proxy came from. func heard(_ address: String, listenPort: Int) { peers[listenPort] = (address, Date()) } + /// Notes a request a proxy passed on for another address than this machine's own. + func called(from address: String, listenPort: Int, server: String, model: String, at: Date) { + guard !LocalHost.isThisMac(UnnamedCallers.plain(address)) else { return } + callers = UnnamedCallers.noted(callers, address: address, listenPort: listenPort, server: server, model: model, at: at) + } + + /// The callers no agent's reporter names, as findings. Other machines that run Tokenmeter name their own agents. + func unnamed(now: Date) -> [Insight] { + let machines = Set(FleetStore.shared.peers.map { UnnamedCallers.plain(FleetStore.hostOnly($0.address)) }) + return UnnamedCallers.findings(callers: callers, agents: ElsewhereStore.shared.agents, + known: { LocalHost.isThisMac($0) || machines.contains($0) }, now: now) + } + /// Notes that a proxy passed on a request from `client`. func saw(_ client: String, listenPort: Int, server: String, at: Date) { sightings.removeAll { at.timeIntervalSince($0.last) > Topology.span } @@ -258,7 +274,7 @@ final class ProxyStore: ObservableObject { Task { @MainActor in ProxyStore.shared.heard(peer, listenPort: route.listenPort) } } connection.start(queue: queue) - ProxyExchange(client: connection, route: route).readRequest(Data()) + ProxyExchange(client: connection, route: route, peer: Self.address(connection.endpoint)).readRequest(Data()) } listener.start(queue: queue) listeners[route.id] = listener @@ -301,7 +317,7 @@ final class ProxyStore: ObservableObject { if route.network, !ProxyRoute.letsIn(connection.peer) { return connection.cancel() } let peer = connection.peer Task { @MainActor in ProxyStore.shared.heard(peer, listenPort: route.listenPort) } - ProxyExchange(client: connection, route: route).readRequest(Data()) + ProxyExchange(client: connection, route: route, peer: peer).readRequest(Data()) } listeners[route.id] = listener problems[route.id] = nil @@ -346,6 +362,8 @@ final class ProxyExchange: NSObject, URLSessionDataDelegate, @unchecked Sendable private let client: any ProxyClient private let route: ProxyRoute + /// The address the client connected from (Engine Proxy only). + private let peer: String? private let started = Date() private var firstByte: Date? private var sniffer = ProxySniffer() @@ -374,9 +392,10 @@ final class ProxyExchange: NSObject, URLSessionDataDelegate, @unchecked Sendable /// This request's number in the waterfall, while Watch live is on (`LiveTap`); touched on the session's queue. private var live: Int? - init(client: any ProxyClient, route: ProxyRoute) { + init(client: any ProxyClient, route: ProxyRoute, peer: String? = nil) { self.client = client self.route = route + self.peer = peer mcp = nil } @@ -384,6 +403,7 @@ final class ProxyExchange: NSObject, URLSessionDataDelegate, @unchecked Sendable init(client: any ProxyClient, mcp route: MCPRoute) { self.client = client self.route = route.passing + peer = nil mcp = route } @@ -643,7 +663,9 @@ final class ProxyExchange: NSObject, URLSessionDataDelegate, @unchecked Sendable timing.cacheWritten = sniffer.cacheWritten timing.key = keyPrint let port = self.route.listenPort + let peer = self.peer Task { @MainActor in + if let peer { ProxyStore.shared.called(from: peer, listenPort: port, server: note.server, model: note.model, at: now) } if note.tokens > 0 { RequestLedger.shared.note(note) } RequestLogStore.shared.addOutside(timing) ProxyStore.shared.saw(note.client, listenPort: port, server: note.server, at: now) diff --git a/App/StatusJSON.swift b/App/StatusJSON.swift index f18d276..eb0f3b7 100644 --- a/App/StatusJSON.swift +++ b/App/StatusJSON.swift @@ -440,7 +440,7 @@ struct LocalResponse { extension StatusReport { /// Tokenmeter's version. The Mac app reads it from its Info.plist, which build-library-app.sh writes; the /// Linux service has no Info.plist, so it uses `releaseVersion`. Keep that in step with the build scripts. - static let releaseVersion = "0.9.12" + static let releaseVersion = "0.9.13" static var appVersion: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? releaseVersion } diff --git a/App/Store.swift b/App/Store.swift index 19376f8..402a511 100644 --- a/App/Store.swift +++ b/App/Store.swift @@ -81,6 +81,8 @@ final class AppStore: ObservableObject { @Published var paletteOpen = false /// Connect an Agent was asked for from the Monitor or the palette: the Agents settings open its sheet. @Published var connectAgentAsked = false + /// Where Connect an Agent opens: "docker" or "remote" when Insights found a caller that isn't named, else here. + var connectAgentPlace = "" /// A task the Doctor linked to: the Sessions page opens its session, then clears it. @Published var taskAsked: DoctorFinding.TaskLink? /// A stretch picked on the Machine Room's replay to send again ("Test a Workload Like This"): the Tuning Lab sets diff --git a/App/UnnamedCallers.swift b/App/UnnamedCallers.swift new file mode 100644 index 0000000..77b0fd0 --- /dev/null +++ b/App/UnnamedCallers.swift @@ -0,0 +1,101 @@ +import Foundation + +/// Who called an Engine Proxy from another address than this machine's, by address, port and model. Read off +/// requests that were passed on anyway; nothing is sent to find it out. +struct ProxyCaller: Codable, Equatable { + var address: String + var listenPort: Int + /// The server the proxy passed its requests on to, as `UsageStore.serverKey` names it. + var server: String + var model: String + var requests: Int + var first: Date + var last: Date +} + +/// Notices a container, a VM or another computer that uses a model through an Engine Proxy while no agent there +/// reports to Tokenmeter, so its requests have no name. Insights says so and offers Connect an Agent. +enum UnnamedCallers { + /// Requests older than this no longer count as "is using". + static let window: TimeInterval = 3_600 + /// A caller is told of from this many requests on: one or two is somebody trying an address. + static let enough = 3 + /// Callers are forgotten after a day without a request. + static let kept: TimeInterval = 86_400 + + /// The callers with one more request noted, and those past `kept` dropped. + static func noted(_ callers: [ProxyCaller], address: String, listenPort: Int, server: String, model: String, at: Date) -> [ProxyCaller] { + var callers = callers.filter { at.timeIntervalSince($0.last) <= kept } + let address = plain(address) + if let index = callers.firstIndex(where: { $0.address == address && $0.listenPort == listenPort && $0.model == model }) { + callers[index].requests += 1 + callers[index].last = at + callers[index].server = server + } else { + callers.append(ProxyCaller(address: address, listenPort: listenPort, server: server, model: model, requests: 1, first: at, last: at)) + } + return callers + } + + /// An address as it is compared: no brackets, no zone, and an IPv4 address written as IPv6 as itself. + static func plain(_ address: String) -> String { + var text = address.lowercased() + if text.hasPrefix("[") { text = String(text.dropFirst().prefix { $0 != "]" }) } + if let percent = text.firstIndex(of: "%") { text = String(text[.. (noun: String, place: String) { + let parts = plain(address).split(separator: ".").compactMap { Int($0) } + if parts.count == 4, parts[0] == 172, (16...31).contains(parts[1]) { return ("A container", "docker") } + return ("A VM or another computer", "remote") + } + + /// "just now", "5 min ago", "2 h ago". + static func ago(_ seconds: TimeInterval) -> String { + seconds < 60 ? "just now" : seconds < 3_600 ? "\(Int(seconds / 60)) min ago" : "\(Int(seconds / 3_600)) h ago" + } + + /// A finding for each address that sent `enough` requests, the last within `window`, and has no reporter: none said + /// hello from that address, and none that reports without an address (through a shared folder) sent a + /// named request in that time. `known` says whether an address is this machine or another machine that + /// runs Tokenmeter, whose agents are named there. + static func findings(callers: [ProxyCaller], agents: [ElsewhereAgent], known: (String) -> Bool, now: Date) -> [Insight] { + let recent = callers.filter { now.timeIntervalSince($0.last) <= window && !known($0.address) } + let named = Set(agents.compactMap { $0.address.map(plain) }) + let folderReporter = agents.contains { $0.address == nil && ($0.lastRequest.map { now.timeIntervalSince($0) <= window } ?? false) } + var found: [Insight] = [] + for address in Set(recent.map(\.address)).sorted() where !named.contains(address) && !folderReporter { + let rows = recent.filter { $0.address == address }.sorted { ($0.requests, $1.model) > ($1.requests, $0.model) } + let requests = rows.reduce(0) { $0 + $1.requests } + guard requests >= enough, let most = rows.first, let opened = rows.map(\.first).min(), let last = rows.map(\.last).max() else { continue } + let (noun, place) = Self.place(address) + let model = most.model.isEmpty ? "a model" : most.model + let others = rows.count - 1 + var evidence = InsightEvidence(asOf: last) + evidence.observed = [ + InsightLine(label: "Requests from \(address)", value: "\(requests), the last \(ago(now.timeIntervalSince(last)))", grade: .timed), + InsightLine(label: "Through the Engine Proxy on port", value: rows.map { String($0.listenPort) }.reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } }.joined(separator: ", "), grade: .timed), + InsightLine(label: "Reporters that said hello from \(address)", value: "none", grade: .timed), + ] + if rows.count > 1 { + evidence.observed.append(InsightLine(label: "Models", value: rows.map { $0.model.isEmpty ? "unnamed" : $0.model }.joined(separator: ", "), grade: .timed)) + } + evidence.inferred = [InsightLine(label: "What it is", value: place == "docker" ? "a container, from its address (172.16 to 172.31 is what Docker and Podman hand out)" + : "a VM or another computer, from its address", grade: .inferred)] + evidence.missing = ["Which agent it is, its sessions, tasks and tool calls: only an agent's reporter says those."] + evidence.alternatives = ["A script or an app that isn't a coding agent, which has no reporter to install", + "An agent whose reporter writes to a folder this machine doesn't read"] + if place == "remote" { evidence.alternatives.append("A machine that runs Tokenmeter itself but isn't in this one's mesh: its agents are named there") } + found.append(Insight(id: "unnamed|\(address)", rule: "unnamed|\(address)", kind: "unnamed", state: "open", priority: 1, + title: "\(noun) is using \(model) but isn't named", + summary: "\(requests) request\(requests == 1 ? "" : "s") came from \(address) through the Engine Proxy\(others > 0 ? ", for \(rows.count) models" : ""), and no agent there reports to Tokenmeter. Connect it and its requests get a name, sessions and tasks.", + model: most.model, engine: "", server: most.server, source: "engine", + opened: opened, updated: last, resolved: nil, evidence: evidence, action: "connect-agent:\(place)")) + } + return found + } +} diff --git a/Linux/kde/app/AppVersion.js b/Linux/kde/app/AppVersion.js index 19cb650..87bdc17 100644 --- a/Linux/kde/app/AppVersion.js +++ b/Linux/kde/app/AppVersion.js @@ -3,4 +3,4 @@ // update keeps saying the version it is, while the service reports its own (backend.snapshot.version). // scripts/package-linux.sh and package-flatpak.sh write it from the package's version; keep it in step with // StatusReport.releaseVersion when bumping (a unit test checks it). -var version = "0.9.12" +var version = "0.9.13" diff --git a/Linux/kde/app/main.qml b/Linux/kde/app/main.qml index 5221b0d..5e437dd 100644 --- a/Linux/kde/app/main.qml +++ b/Linux/kde/app/main.qml @@ -199,7 +199,7 @@ ApplicationWindow { break case "connect-agent": current = "agents"; agentsSlot.active = true - Qt.callLater(function () { agentsSlot.item.connectAgent() }) + Qt.callLater(function () { agentsSlot.item.connectAgent(rest) }) break case "watch-live": current = "performance"; performanceSlot.active = true @@ -836,7 +836,7 @@ ApplicationWindow { } LazyPage { id: sessionsSlot; sourceComponent: SessionsPage { backend: window.service; active: sessionsSlot.current && window.shown } } LazyPage { id: labSlot; sourceComponent: LabPage { backend: window.service; active: labSlot.current && window.shown } } - LazyPage { sourceComponent: InsightsPage { backend: window.service; onDoctorRequested: window.current = "server:here" } } + LazyPage { sourceComponent: InsightsPage { backend: window.service; onDoctorRequested: window.current = "server:here"; onActionRequested: function (action) { window.perform(action) } } } LazyPage { id: agentsSlot; sourceComponent: AgentsPage { backend: window.service; active: agentsSlot.current && window.shown } } LazyPage { id: meshSlot diff --git a/Linux/kde/mock/machines.json b/Linux/kde/mock/machines.json index 69acab4..4be0d81 100644 --- a/Linux/kde/mock/machines.json +++ b/Linux/kde/mock/machines.json @@ -7,7 +7,7 @@ "report": { "schema": 1, "app": "Tokenmeter", - "version": "0.9.12", + "version": "0.9.13", "host": "studio", "chip": "Apple M3 Ultra", "time": "2026-11-13T19:00:00Z", diff --git a/Linux/kde/mock/settings.json b/Linux/kde/mock/settings.json index 5cabef3..e200f34 100644 --- a/Linux/kde/mock/settings.json +++ b/Linux/kde/mock/settings.json @@ -15,7 +15,7 @@ "addresses": [ "192.168.1.20" ], - "version": "0.9.12", + "version": "0.9.13", "shareHistory": false, "footprint": { "cpuPercent": 0.4, diff --git a/Linux/kde/plasmoid/metadata.json b/Linux/kde/plasmoid/metadata.json index 82a460e..ff060cb 100644 --- a/Linux/kde/plasmoid/metadata.json +++ b/Linux/kde/plasmoid/metadata.json @@ -7,7 +7,7 @@ "Icon": "tokenmeter", "Category": "System Information", "License": "Apache-2.0", - "Version": "0.9.12", + "Version": "0.9.13", "Website": "https://github.com/tokenmeter1/Tokenmeter" }, "X-Plasma-API-Minimum-Version": "6.0", diff --git a/Linux/kde/ui/AgentsPage.qml b/Linux/kde/ui/AgentsPage.qml index 9e8edbe..54fccda 100644 --- a/Linux/kde/ui/AgentsPage.qml +++ b/Linux/kde/ui/AgentsPage.qml @@ -35,11 +35,13 @@ Flickable { setupDialog.choosingFolder = place === "folder" setupDialog.open() } - // Connect an Agent, on the first agent found here (from Welcome and the command palette). - function connectAgent() { + // Connect an Agent, on the first agent found here (from Welcome and the command palette), or in a container or + // on another computer when Insights found one that isn't named ("docker" or "remote"). + function connectAgent(place) { var reporters = backend.agents.reporters || [] var here = reporters.filter(function (r) { return r.state !== "missing" }) - openSetup(here.length > 0 ? here[0].id : reporters.length > 0 ? reporters[0].id : "claude-code", "here") + openSetup(here.length > 0 ? here[0].id : reporters.length > 0 ? reporters[0].id : "claude-code", + place === "docker" || place === "remote" ? place : "here") } // The MCP servers the agents named, and where each runs (`GET /tools`). diff --git a/Linux/kde/ui/InsightCard.qml b/Linux/kde/ui/InsightCard.qml index 21253c3..8d5c4b8 100644 --- a/Linux/kde/ui/InsightCard.qml +++ b/Linux/kde/ui/InsightCard.qml @@ -14,6 +14,8 @@ Card { property bool doctor: false property Backend backend signal doctorRequested() + // The finding's own button was pressed: its action, as the command palette names them ("connect-agent:docker"). + signal actionRequested(string action) readonly property var tones: Format.tones(palette.window) readonly property color tint: insight.priority >= 2 ? tones.amber : tones.blue accent: tint @@ -27,7 +29,7 @@ Card { Rectangle { radius: 9; color: Qt.rgba(card.tint.r, card.tint.g, card.tint.b, 0.18) implicitWidth: kind.implicitWidth + 14; implicitHeight: kind.implicitHeight + 4 - Label { id: kind; anchors.centerIn: parent; text: card.insight.source === "engine" ? "Engine reports" : "Anomaly"; color: card.tint; font.pixelSize: Look.px(10); font.weight: Font.DemiBold } + Label { id: kind; anchors.centerIn: parent; text: card.insight.kind === "unnamed" ? "The proxy saw" : card.insight.source === "engine" ? "Engine reports" : "Anomaly"; color: card.tint; font.pixelSize: Look.px(10); font.weight: Font.DemiBold } } Label { text: card.insight.priority >= 2 ? "High priority" : "Worth knowing"; font.pixelSize: Look.px(11); opacity: Look.dim(0.6) } Item { Layout.fillWidth: true } @@ -54,6 +56,13 @@ Card { ToolTip.text: "Says this is normal for it: the finding closes and this rule needs twice the gap before it opens again." } Button { visible: card.doctor; text: "Investigate in Doctor"; onClicked: card.doctorRequested() } + Button { + objectName: "insightAction" + visible: !!card.insight.action && !card.insight.machine && card.insight.state === "open" + text: String(card.insight.action || "").indexOf("connect-agent") === 0 ? "Connect the Agent…" : "Open" + highlighted: true + onClicked: card.actionRequested(card.insight.action) + } Label { visible: card.insight.source === "anomaly" && !!card.insight.machine text: "Found on " + (card.insight.machine || "") + ": mark it normal there." diff --git a/Linux/kde/ui/InsightsPage.qml b/Linux/kde/ui/InsightsPage.qml index 9d1c879..0bb1bab 100644 --- a/Linux/kde/ui/InsightsPage.qml +++ b/Linux/kde/ui/InsightsPage.qml @@ -13,6 +13,7 @@ Flickable { property Backend backend property string tab: "overview" signal doctorRequested() + signal actionRequested(string action) readonly property var tones: Format.tones(palette.window) readonly property var report: backend.insights || ({}) readonly property var open: report.open || [] @@ -246,6 +247,7 @@ Flickable { doctor: page.hasDoctor(modelData) backend: page.backend onDoctorRequested: page.doctorRequested() + onActionRequested: function (action) { page.actionRequested(action) } } } // MARK: Which connected machines are in it, and which keep theirs to themselves. diff --git a/Package.swift b/Package.swift index 430ad31..124e71b 100644 --- a/Package.swift +++ b/Package.swift @@ -55,7 +55,7 @@ let sources = [ "App/AgentTrace.swift", "App/ToolStats.swift", "App/Facility.swift", - "App/Insights.swift", "App/Changes.swift", "App/Forecasts.swift", "App/Visibility.swift", "App/Topology.swift", + "App/Insights.swift", "App/UnnamedCallers.swift", "App/Changes.swift", "App/Forecasts.swift", "App/Visibility.swift", "App/Topology.swift", "App/Fleet.swift", "App/Mesh.swift", "App/MeshCrypto.swift", diff --git a/Tests/Tests.swift b/Tests/Tests.swift index 43fd08e..a372904 100644 --- a/Tests/Tests.swift +++ b/Tests/Tests.swift @@ -131,6 +131,7 @@ enum Tests { confidence() telemetryCoverage() insights() + unnamedCallers() changes() forecasts() visibility() diff --git a/Tests/UnnamedCallersTests.swift b/Tests/UnnamedCallersTests.swift new file mode 100644 index 0000000..0c0e22f --- /dev/null +++ b/Tests/UnnamedCallersTests.swift @@ -0,0 +1,68 @@ +import Foundation + +/// Insights' "isn't named" finding: a container or another computer that uses a model through an Engine Proxy +/// while no agent there reports. +extension Tests { + static func unnamedCallers() { + let now = Date(timeIntervalSince1970: 1_800_000_000) + func called(_ list: [ProxyCaller], _ address: String, _ minutesAgo: Double, model: String = "qwen3-coder", port: Int = 18080) -> [ProxyCaller] { + UnnamedCallers.noted(list, address: address, listenPort: port, server: "localhost:8080", model: model, at: now.addingTimeInterval(-minutesAgo * 60)) + } + func find(_ callers: [ProxyCaller], agents: [ElsewhereAgent] = [], known: Set = []) -> [Insight] { + UnnamedCallers.findings(callers: callers, agents: agents, known: { known.contains($0) }, now: now) + } + + // MARK: A container that calls a model, with no reporter. + var callers: [ProxyCaller] = [] + callers = called(callers, "172.17.0.2", 20) + callers = called(callers, "172.17.0.2", 10) + equal(find(callers).count, 0, "two requests are somebody trying an address") + callers = called(callers, "::ffff:172.17.0.2", 5) + equal(callers.count, 1, "an IPv4 address written as IPv6 is the same caller") + equal(callers.first?.requests, 3, "its requests are counted") + let found = find(callers) + equal(found.count, 1, "three requests from a container without a reporter open a finding") + equal(found.first?.title, "A container is using qwen3-coder but isn't named", "it names the model") + equal(found.first?.action, "connect-agent:docker", "its button opens Connect an Agent for a container") + equal(found.first?.kind, "unnamed", "its kind") + equal(found.first?.source, "engine", "a fact, not a drift: it can't be marked normal") + equal(found.first?.server, "localhost:8080", "the server the proxy passes on to") + equal(found.first?.evidence.observed.first?.value, "3, the last 5 min ago", "the count and how fresh it is") + equal(found.first?.evidence.inferred.first?.grade, .inferred, "that it is a container is a guess from the address") + + // MARK: Who is left alone. + let hello = ElsewhereAgent(agent: "claude-code", machine: "devbox", place: "docker", setUp: now.addingTimeInterval(-600), address: "172.17.0.2") + equal(find(callers, agents: [hello]).count, 0, "a reporter said hello from there: it is named") + var folder = ElsewhereAgent(agent: "oh-my-pi", machine: "colima", place: "docker", setUp: now.addingTimeInterval(-86_400)) + equal(find(callers, agents: [folder]).count, 1, "a reporter elsewhere that sent nothing lately doesn't cover it") + folder.lastRequest = now.addingTimeInterval(-120) + equal(find(callers, agents: [folder]).count, 0, "a reporter that writes to a shared folder and just named a request may be the one") + equal(find(callers, known: ["172.17.0.2"]).count, 0, "this machine and the mesh's machines are left alone") + equal(UnnamedCallers.findings(callers: callers, agents: [], known: { _ in false }, now: now.addingTimeInterval(3_700)).count, 0, + "an hour without a request and it stops using the model") + + // MARK: A VM, with two models. + var vm: [ProxyCaller] = [] + for minute in [9.0, 8.0, 7.0] { vm = called(vm, "192.168.64.5", minute, model: "gemma-3") } + vm = called(vm, "192.168.64.5", 6, model: "qwen3") + let other = find(vm + callers) + equal(other.count, 2, "each address is its own finding") + let remote = other.first { $0.rule == "unnamed|192.168.64.5" } + equal(remote?.title, "A VM or another computer is using gemma-3 but isn't named", "the model it asks most") + equal(remote?.action, "connect-agent:remote", "its button opens Connect an Agent for another computer") + expect(remote?.summary.contains("4 requests came from 192.168.64.5") == true, "the summary counts all its requests") + expect(remote?.evidence.observed.contains { $0.label == "Models" && $0.value == "gemma-3, qwen3" } == true, "both models are listed") + + // MARK: Kept a day. + let old = called([], "172.17.0.9", 25 * 60) + equal(called(old, "172.17.0.2", 0).map(\.address), ["172.17.0.2"], "a caller silent for a day is forgotten") + equal(UnnamedCallers.place("172.31.4.4").place, "docker", "Docker's range ends at 172.31") + equal(UnnamedCallers.place("172.32.0.1").place, "remote", "past it is another computer") + equal(UnnamedCallers.place("10.0.2.15").place, "remote", "so is a VM's address") + + // MARK: A finding that goes when the reporter arrives. + let opened = InsightStore.merge([], found, now: now) + let closed = InsightStore.merge(opened, [], now: now.addingTimeInterval(60)) + equal(closed.first?.state, "resolved", "once named, the finding resolves") + } +} diff --git a/build-library-app.sh b/build-library-app.sh index caae381..2e74258 100755 --- a/build-library-app.sh +++ b/build-library-app.sh @@ -18,7 +18,7 @@ for word in "$@"; do esac done app="$project_dir/Tokenmeter.app" -version=${APP_VERSION:-0.9.12} +version=${APP_VERSION:-0.9.13} build=${APP_BUILD:-1} # SwiftUI's @State is a compiler macro in the macOS 26 SDK. The Command Line Tools ship that SDK without diff --git a/docs/wiki/Coding-Agents.md b/docs/wiki/Coding-Agents.md index 522a788..712c767 100644 --- a/docs/wiki/Coding-Agents.md +++ b/docs/wiki/Coding-Agents.md @@ -29,7 +29,7 @@ For an agent whose reporter can't time requests, or to see every request whateve ## Connect an Agent -**Connect an Agent…** (on the Agents page) puts everything an agent needs in one place. Pick the agent and where it runs: **On This Computer** (On This Mac), **In a Docker Container**, or **On a VM or Another Computer**. +**Connect an Agent…** (on the Agents page) puts everything an agent needs in one place. Pick the agent and where it runs: **On This Computer** (On This Mac), **In a Docker Container**, or **On a VM or Another Computer**. When Insights notices a container or another computer calling a model without a reporter, its finding opens this at the right place. 1. **Point the agent at the model.** It shows the model's address to use as the agent's base URL from there. Inside a container, `127.0.0.1` is the container itself: on Linux the address is Docker's bridge (`172.17.0.1`), or `host.docker.internal` when the container was started with `--add-host=host.docker.internal:host-gateway`; on a Mac, `host.docker.internal`. A VM or another computer gets this computer's network addresses. On Linux, Tokenmeter also sees when the model listens on `127.0.0.1` only, which a container or VM can't reach, and offers to open its [proxy](Proxy-Mode.md) in front of the model to them, with **Undo**. 2. **Let it report who is calling.** On this computer, install the reporter (or choose the agent's folder). In a container or a VM, the steps below. diff --git a/docs/wiki/Features.md b/docs/wiki/Features.md index a3d61f3..37b1287 100644 --- a/docs/wiki/Features.md +++ b/docs/wiki/Features.md @@ -83,6 +83,8 @@ Insights is what Tokenmeter notices on its own. It learns each model's normal on - **History:** every finding's moments and every change seen, day by day: restarts, new engine versions and context sizes, models loaded for the first time, machines that stopped answering. It is kept 90 days by default; Settings changes that to 30, 180 or 365. - **Visibility:** a row for each engine on each machine with how much of each group of figures Tokenmeter can see (request activity, throughput, latency, queue, memory, cache and the machine's own hardware), then a step for every row that would show more, the biggest first: a server flag to switch on, sending an engine through the [proxy](Proxy-Mode.md) on its machine, or nothing left to switch on; and switching on Share Usage History on a machine that doesn't share. Tokenmeter never takes these steps for you. Last, what each engine and model, on whichever machine, can never show. +**Callers without a name.** When a Docker container, a VM or another computer uses a model through an [Engine Proxy](Proxy-Mode.md) and no agent there reports to Tokenmeter, Insights says so: "A container is using Qwen3-Coder but isn't named", with how many requests came from which address. **Connect the Agent…** opens [Connect an Agent](Coding-Agents.md#connect-an-agent) at the step for a container or another computer. It is read off requests the proxy passed on anyway; nothing is sent to find it out. It takes three requests within the hour, goes away once a reporter there says hello, and leaves this machine and the machines of your mesh alone. That it is a container is a guess from the address (172.16 to 172.31), and the evidence says so. + **Across the fleet.** Every tab covers the connected machines that share their usage history as well as this one: their findings, the models they are still learning, their forecasts, track record and Capacity outlook, and their History, each marked with the machine it comes from. A finding from another machine is marked normal on that machine. Each machine keeps its own sensitivity and its own History length. **Sensitivity** (Conservative, Normal, Aggressive) sets how big and how lasting a drift must be before it is a finding. Changing it looks over the stored history again. High-priority findings can send a [notification](Alerts.md), and so can a forecast of a kind that has held often enough; the Monitor, the menu bar, the Plasma widget and [Gizmo](Gizmo.md) say the most pressing one, and coding agents can ask through the [MCP server](MCP-Server.md#the-tools). diff --git a/scripts/package-flatpak.sh b/scripts/package-flatpak.sh index d88ec2f..b1a394a 100755 --- a/scripts/package-flatpak.sh +++ b/scripts/package-flatpak.sh @@ -7,7 +7,7 @@ # Needs flatpak and flatpak-builder; the KDE runtime and SDK are fetched from Flathub. set -eu project_dir=$(cd "$(dirname "$0")/.." && pwd) -version=${APP_VERSION:-0.9.12} +version=${APP_VERSION:-0.9.13} arch=$(uname -m) id=io.github.tokenmeter1.tokenmeter name="Tokenmeter-$version-linux-$arch" diff --git a/scripts/package-linux.sh b/scripts/package-linux.sh index 8457b48..f5f7995 100755 --- a/scripts/package-linux.sh +++ b/scripts/package-linux.sh @@ -4,7 +4,7 @@ # and install.sh. Needs the Swift toolchain; run it on Linux. set -eu project_dir=$(cd "$(dirname "$0")/.." && pwd) -version=${APP_VERSION:-0.9.12} +version=${APP_VERSION:-0.9.13} arch=$(uname -m) name="Tokenmeter-$version-linux-$arch" diff --git a/scripts/package-service.sh b/scripts/package-service.sh index 934d7e4..d8378ba 100755 --- a/scripts/package-service.sh +++ b/scripts/package-service.sh @@ -18,7 +18,7 @@ # On a Mac, SIGN_IDENTITY signs the program with a Developer ID; without it the program is ad-hoc signed. set -eu project_dir=$(cd "$(dirname "$0")/.." && pwd) -version=${APP_VERSION:-0.9.12} +version=${APP_VERSION:-0.9.13} case "$(uname -s)" in Darwin) os=macos ;; Linux) os=linux ;; diff --git a/scripts/package.sh b/scripts/package.sh index 7d86e71..315ce0b 100755 --- a/scripts/package.sh +++ b/scripts/package.sh @@ -16,7 +16,7 @@ set -euo pipefail project_dir=${0:A:h:h} app="$project_dir/Tokenmeter.app" dist="$project_dir/dist" -export APP_VERSION=${APP_VERSION:-0.9.12} +export APP_VERSION=${APP_VERSION:-0.9.13} identity=${SIGN_IDENTITY:-} profile=${NOTARY_PROFILE:-}