Skip to content
Merged
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
2 changes: 1 addition & 1 deletion Android/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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]*}))

Expand Down
4 changes: 3 additions & 1 deletion App/AgentInstaller.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions App/CommandPaletteView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ extension AppStore {
case "settings":
openSettings(part: rest)
case "connect-agent":
connectAgentPlace = rest
connectAgentAsked = true
page = .agents
case "add-engine":
Expand Down
9 changes: 8 additions & 1 deletion App/Insights.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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: " · ") }
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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
}
Expand Down
6 changes: 5 additions & 1 deletion App/InsightsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()
Expand Down
28 changes: 25 additions & 3 deletions App/Proxy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -374,16 +392,18 @@ 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
}

/// An exchange of an MCP Proxy: the same passing on, with the tool calls read off it instead of the tokens.
init(client: any ProxyClient, mcp route: MCPRoute) {
self.client = client
self.route = route.passing
peer = nil
mcp = route
}

Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion App/StatusJSON.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
2 changes: 2 additions & 0 deletions App/Store.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
101 changes: 101 additions & 0 deletions App/UnnamedCallers.swift
Original file line number Diff line number Diff line change
@@ -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[..<percent]) }
if text.hasPrefix("::ffff:"), text.contains(".") { text = String(text.dropFirst(7)) }
return text
}

/// What an address most likely is: Docker and Podman give their containers 172.16 to 172.31 unless told
/// otherwise; anything else is a VM or another computer. A guess from the address, and told as one.
static func place(_ address: String) -> (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
}
}
2 changes: 1 addition & 1 deletion Linux/kde/app/AppVersion.js
Original file line number Diff line number Diff line change
Expand Up @@ -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"
4 changes: 2 additions & 2 deletions Linux/kde/app/main.qml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Linux/kde/mock/machines.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion Linux/kde/mock/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"addresses": [
"192.168.1.20"
],
"version": "0.9.12",
"version": "0.9.13",
"shareHistory": false,
"footprint": {
"cpuPercent": 0.4,
Expand Down
Loading
Loading