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
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@ search, recoverable trash, maintenance, and restore.
Use `docbank backup create` to include retained content held only in secondary
stores. See the [backup guide](docs/usage/backup.md) for the full rules.

## Telemetry

The daemon sends anonymous `daemon_started` and `daemon_active` events each
time it starts, `daemon_active` once a day while it runs, and an `app_opened`
event when the web app opens (about once a day per browser and daemon run). Events
carry a random per-vault install ID, the version and commit, and the operating system and
architecture, and never document content, names, paths or queries.
`DOCBANK_TELEMETRY_ENABLED=0` turns both off; see
[anonymous usage telemetry](docs/configuration.md#anonymous-usage-telemetry).

## Documentation

- [Documentation homepage](https://docbank.ai) and [visual tour](docs/tour.md)
Expand Down
18 changes: 18 additions & 0 deletions cmd/docbank/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ import (
"go.kenn.io/docbank/internal/pdfstamp"
"go.kenn.io/docbank/internal/processing"
"go.kenn.io/docbank/internal/store"
"go.kenn.io/docbank/internal/telemetry"
"go.kenn.io/docbank/internal/vectorworker"
"go.kenn.io/docbank/internal/version"
docweb "go.kenn.io/docbank/internal/web"
)

Expand Down Expand Up @@ -217,6 +219,13 @@ func runServe(ctx context.Context) (retErr error) {
if err := blobs.CleanTmp(); err != nil {
return err
}
telemetryReporter := telemetry.New(telemetry.Options{Dir: layout.Root, Version: version.Version, Commit: version.Commit, Logger: logger})
// Registered before the supervisor's drain defer so it runs after the heartbeat has finished.
defer func() {
if err := telemetryReporter.Close(); err != nil {
logger.Warn("telemetry close failed", "error", err)
}
}()
jobSupervisor := jobs.New(sigCtx, logger)
defer func() {
shutdownCtx, cancel := context.WithTimeout(
Expand Down Expand Up @@ -483,6 +492,14 @@ func runServe(ctx context.Context) (retErr error) {
if err := photoImports.Resume(sigCtx, jobSupervisor); err != nil {
return err
}
if telemetryReporter.Enabled() {
if err := jobSupervisor.Start(telemetry.HeartbeatJobName, func(ctx context.Context) error {
telemetry.RunHeartbeat(ctx, telemetryReporter, logger)
return nil
}); err != nil {
logger.Warn("telemetry heartbeat not started", "error", err)
}
}
srv := api.NewServer(api.Deps{
Store: s, Blobs: blobs, VaultRoot: layout.Root, Cfg: cfg, Logger: logger,
RequestEmailPDF: requestEmailPDF,
Expand All @@ -493,6 +510,7 @@ func runServe(ctx context.Context) (retErr error) {
PublishEmailDocuments: processing.PublishEmailDocuments,
PageRuntime: pageRuntime,
Exports: exportWorker,
TelemetryCapture: telemetry.CaptureHandler(telemetryReporter),
})
defer srv.Close()
newHTTPServer := func() *http.Server {
Expand Down
4 changes: 3 additions & 1 deletion cmd/docbank/daemon_lifecycle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.kenn.io/kit/telemetry/posthog"

"go.kenn.io/docbank/internal/api"
"go.kenn.io/docbank/internal/daemonconn"
Expand All @@ -37,7 +38,7 @@ func buildDocbankVersion(tb testing.TB, v string) string {
name += ".exe"
}
bin := filepath.Join(tb.TempDir(), name)
args := []string{"build", "-tags", "fts5"}
args := []string{"build", "-tags", "fts5,kit_posthog_disabled"}
if v != "" {
args = append(args, "-ldflags", "-X go.kenn.io/docbank/internal/version.Version="+v)
}
Expand Down Expand Up @@ -85,6 +86,7 @@ func TestLifecycleStartStatusRestartStop(t *testing.T) {
require.NoError(t, err, out)
t.Cleanup(func() { _, _ = daemonconn.Stop(context.Background(), dir) })
startPID := parsePID(t, out)
require.NoFileExists(t, filepath.Join(dir, posthog.InstallFileName))
out, err = run("daemon", "status")
require.NoError(t, err, out)
assert.Contains(t, out, "running")
Expand Down
89 changes: 89 additions & 0 deletions cmd/docbank/daemon_telemetry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package main

import (
"context"
"io"
"net/http"
"path/filepath"
"strings"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.kenn.io/kit/telemetry/posthog"

"go.kenn.io/docbank/internal/daemonconn"
"go.kenn.io/docbank/internal/telemetry"
)

type telemetryTestDaemon struct {
root string
baseURL string
apiKey string
}

func startTelemetryTestDaemon(t *testing.T) telemetryTestDaemon {
t.Helper()
root, err := filepath.EvalSymlinks(t.TempDir())
require.NoError(t, err)
t.Setenv("DOCBANK_HOME", root)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- runServe(ctx) }()
t.Cleanup(func() {
cancel()
select {
case err := <-done:
require.NoError(t, err)
case <-time.After(10 * time.Second):
require.FailNow(t, "daemon did not stop")
}
})
var found telemetryTestDaemon
require.Eventually(t, func() bool {
rec, _, ok, findErr := daemonconn.Find(ctx, root)
if findErr != nil || !ok {
return false
}
found = telemetryTestDaemon{root: root, baseURL: "http://" + rec.Address, apiKey: rec.Metadata["api_key"]}
return true
}, 30*time.Second, 25*time.Millisecond)
return found
}

func (d telemetryTestDaemon) do(t *testing.T, method, path, body string) (int, string) {
t.Helper()
req, err := http.NewRequestWithContext(t.Context(), method, d.baseURL+path, strings.NewReader(body))
require.NoError(t, err)
req.Header.Set("X-Api-Key", d.apiKey)
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer func() { require.NoError(t, resp.Body.Close()) }()
data, err := io.ReadAll(resp.Body)
require.NoError(t, err)
return resp.StatusCode, string(data)
}

func (d telemetryTestDaemon) requireNoHeartbeatOrInstallFile(t *testing.T) {
t.Helper()
status, jobs := d.do(t, http.MethodGet, "/api/v1/jobs", "")
require.Equal(t, http.StatusOK, status, jobs)
assert.NotContains(t, jobs, telemetry.HeartbeatJobName)
assert.NoFileExists(t, filepath.Join(d.root, posthog.InstallFileName))
}

func TestServeAcceptsAppOpenedWhenTelemetryOptedOut(t *testing.T) {
t.Setenv(telemetry.EnabledEnv, "0")
t.Setenv(posthog.GenericEnabledEnv, "1")
d := startTelemetryTestDaemon(t)
status, body := d.do(t, http.MethodPost, "/api/daemon/telemetry/events", `{"event":"app_opened"}`)
require.Equal(t, http.StatusAccepted, status, body)
assert.JSONEq(t, `{"status":"disabled"}`, body)
status, body = d.do(t, http.MethodPost, "/api/daemon/telemetry/events", `{"event":"search_run"}`)
assert.Equal(t, http.StatusBadRequest, status, body)
d.requireNoHeartbeatOrInstallFile(t)
}
3 changes: 3 additions & 0 deletions cmd/docbank/edit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.kenn.io/kit/telemetry/posthog"

"go.kenn.io/docbank/internal/api"
"go.kenn.io/docbank/internal/apiclient"
Expand Down Expand Up @@ -226,6 +227,8 @@ func TestMain(m *testing.M) {
if os.Getenv("DOCBANK_EDIT_TEST_HELPER") == "1" {
os.Exit(runEditHelper())
}
// In-process daemons here must never reach PostHog.
posthog.DisableProcess()
os.Exit(m.Run())
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/docbank/email_pdf_real_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func TestEmailPDFRealDaemonCLI(t *testing.T) {
require.NoError(t, os.Mkdir(vault, 0700))
invoke := func(ctx context.Context, args ...string) ([]byte, error) {
cmd := exec.CommandContext(ctx, binary, args...) //nolint:gosec // Explicit qualification binary; arguments are synthetic test inputs.
cmd.Env = []string{"PATH=/usr/local/bin:/usr/bin:/bin", "LANG=C.UTF-8", "DOCBANK_HOME=" + vault}
cmd.Env = []string{"PATH=/usr/local/bin:/usr/bin:/bin", "LANG=C.UTF-8", "DOCBANK_HOME=" + vault, "DOCBANK_TELEMETRY_ENABLED=0"}
for _, key := range []string{"XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS"} {
if value := os.Getenv(key); value != "" {
cmd.Env = append(cmd.Env, key+"="+value)
Expand Down
3 changes: 3 additions & 0 deletions docs/architecture/daemon.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,9 @@ Every daemon runs three jobs that derive information from retained content:

`process:renditions` runs only when a rendition provider is bound to the daemon.
Its presence in `docbank jobs` means the daemon can process renditions.
`telemetry:heartbeat` runs only while anonymous usage telemetry is on. It sends
`daemon_started` and `daemon_active` at each daemon start, then `daemon_active`
on the first hourly check of each later UTC day. It touches no vault data.
Configured watched inboxes add one `watch:<name>` runner each.

All derived-data writes take the ordinary mutation side of the daemon operation
Expand Down
10 changes: 7 additions & 3 deletions docs/architecture/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -786,10 +786,14 @@ its own shutdown token. The hidden `POST /api/daemon/web-session` exchanges
that master authority for a random daemon-lifetime browser token, an
independent upload-proof secret, and the fresh loopback origin dedicated to
that daemon lifetime, while
`DELETE /api/daemon/web-session` revokes the calling browser session. Those
tokens authenticate only the explicit routes used by the built-in document,
`DELETE /api/daemon/web-session` revokes the calling browser session.
`POST /api/daemon/telemetry/events` takes one anonymous web application event,
such as `app_opened`, from a browser session or the API key. The daemon answers
400 for any event its allowlist omits and sends nothing when telemetry is off;
see [anonymous usage telemetry](../configuration.md#anonymous-usage-telemetry).
Browser session tokens authenticate only the explicit routes used by the built-in document,
tag-definition/assignment, saved-definition, recoverable-trash, storage, job,
configured-backup, and verified-download workflows; they are intentionally not another general API
configured-backup, verified-download, and usage-event workflows; they are intentionally not another general API
credential. Browser file bytes use the
hidden `/api/daemon/web-upload` WebSocket instead. The page verifies a
challenge proof over the upload secret before sending bytes, binds the socket
Expand Down
9 changes: 9 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ may still evolve, but vaults created by v0.9.0 and later are within the

## Unreleased

### New features

- The daemon now sends anonymous usage telemetry: `daemon_started` and
`daemon_active` at each daemon start and daily while it runs, and
`app_opened` when the web app opens. Each vault has its own random install
ID, and no document content, names, paths or queries leave the machine. Set
`DOCBANK_TELEMETRY_ENABLED=0` to turn it off; see
[anonymous usage telemetry](configuration.md#anonymous-usage-telemetry).

## [v0.13.0](https://github.com/kenn-io/docbank/tree/v0.13.0) — 2026-08-18

### New features
Expand Down
3 changes: 2 additions & 1 deletion docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1414,7 +1414,8 @@ Running tasks have no finish timestamp; terminal task records remain visible
until the daemon restarts. `--json` emits `{"items": [...]}` for automation.
Every daemon registers `extract:plain-text`, `extract:source-metadata`, and
`maintenance:auxiliary-checksums`; `process:renditions` appears only when a
rendition provider is bound, and configured watched inboxes add `watch:<name>`
rendition provider is bound, `telemetry:heartbeat` appears while anonymous
usage telemetry is on, and configured watched inboxes add `watch:<name>`
tasks. See [Daemon](architecture/daemon.md) for what each job does.

## docbank media
Expand Down
54 changes: 54 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ The directory layout is created on first use:
├── logs/ # JSON logs from background daemons
├── web-launch/ # owner-private browser authentication handoff
├── web-downloads/ # private, temporary verified browser downloads
├── telemetry-install.json # anonymous telemetry install ID (with its .lock); created only while telemetry is on, kept if it is later turned off
├── config.toml # optional; see below
├── vault.lock # advisory lock, held by a daemon or target restore
└── daemon.<pid>.json # runtime record of a live daemon
Expand All @@ -72,6 +73,9 @@ running processes. You can omit them from backups. Delete them only when no
daemon or restore is running. `docbank daemon stop` removes its own runtime
record on graceful shutdown.

Deleting `telemetry-install.json` while the daemon is stopped gives the vault a new
anonymous install ID.

Use `docbank backup create` to capture every retained blob from a verified
location, including content held only in a secondary store. The resulting
backup can restore without recreating the original store layout.
Expand Down Expand Up @@ -608,3 +612,53 @@ The daemon validates its listening address at startup. An invalid setting makes
| `DOCBANK_HOME` | Vault location; see [Vault location](#vault-location) above. |
| `DOCBANK_LOCK_DIR` | Absolute lock-registry directory for an isolated environment whose account home is unwritable. Defaults to the operating-system account home's `.local/state/docbank/target-locks`, independent of `HOME` and XDG settings. All processes sharing or restoring overlapping vault trees must use the same directory; stop them before changing this setting. Keep it outside vaults and restore targets. Never delete it while any participating process runs. |
| `DOCBANK_LOG_LEVEL` | Log level (`debug`, `info`, `warn`, `error`) for `docbank daemon run` and `docbank mcp`, foreground or background. Invalid values are ignored and fall back to `info`. |
| `DOCBANK_TELEMETRY_ENABLED` | `0`, `false`, `no` or `off` turns off anonymous usage telemetry. Read when the daemon starts; restart the daemon after changing it. |
| `TELEMETRY_ENABLED` | The same values have the same effect; shared with other Kenn tools. |

## Anonymous usage telemetry

The daemon reports anonymous usage events so the Docbank team can count
vaults whose daemon runs and vaults whose web app gets opened. Counts are per
vault, not per person: one person with three vaults counts three times. It sends them in HTTPS
batches to PostHog's US ingest endpoint (PostHog project 434713). The browser
never contacts PostHog: the web app posts its event to its own daemon, which
sends it.

Docbank sends three events:

- `daemon_started` and `daemon_active` at each daemon start, then
`daemon_active` on the first hourly check of each later UTC day. Days when
the machine sleeps are not backfilled. A background daemon exits
after `idle_timeout` (30 minutes by default) and starts again on the next
command, so most of these go out at a daemon start, and `daemon_started`
counts starts rather than installs.
- `app_opened` when the web app loads, and again on the first window focus of
a later UTC day. The browser remembers the day for the daemon's address, so
it sends about one per UTC day until the daemon restarts on a new address.

Each event carries exactly these fields:

- the event name, a random event UUID, and a timestamp
- `distinct_id`: a random install ID generated on this machine
- `application=docbank`, `source=daemon`, the Docbank `version` and `commit`,
`goos`, `goarch`, and `install_age_hours` (whole hours since the install ID
was created)
- `$process_person_profile=false` and `$geoip_disable=true`
- fields the PostHog Go library adds: `$lib`, `$lib_version`, `$os`,
`$os_version`, `$os_distro` (Linux only), and `$go_version`

Usage telemetry never carries document content, filenames, paths, hashes,
tags, queries, the vault ID, account names, the hostname, or configuration
values. PostHog does see the request's source IP address; Docbank asks it not
to geolocate. Separately configured document providers are unrelated to usage
telemetry and unchanged by it.

The install ID lives in `telemetry-install.json` at the vault root (see the
[layout](#vault-location) above). The daemon creates it the first time it runs
with telemetry on, and never while telemetry is off. Each vault has its own ID.

To opt out, set `DOCBANK_TELEMETRY_ENABLED=0` (or `TELEMETRY_ENABLED=0`) in the
environment that starts the daemon, then run `docbank daemon restart`. A CLI
command that starts the daemon automatically passes its own environment, so
set the variable in your shell profile. Go applications that embed a vault
in-process send nothing.
5 changes: 5 additions & 0 deletions docs/internal/daemon-api-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ Auth-exempt health, ping, docs, and OpenAPI routes establish discovery and
contract access only. Every data route and the hidden shutdown route requires
the effective key; shutdown additionally requires its token.

The daemon owns usage telemetry. The browser posts allowlisted events to its
own daemon with its session; the daemon stamps identity and version and sends
them. The browser holds no analytics key and loads no provider script. Only
`cmd/docbank` constructs the reporter, so embedded vaults send nothing.

## Node identity, paths, and revisions

Node IDs are stable. Paths are mutable names that can be reused. Single-node
Expand Down
1 change: 1 addition & 0 deletions docs/internal/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ lists the checks contributors must preserve.
| `internal/daemonconn` | daemon convergence and receipt validation for the generated client | opening SQLite or blobs |
| `internal/home` | vault layout, privacy, and portable vault/tree locking | data operations |
| `internal/config` | strict config parsing and security validation | runtime discovery |
| `internal/telemetry` | the daemon's PostHog reporter options, event allowlist and its wiring of kit's install ID and heartbeat | vault data, HTTP auth, embedded vault paths |
| `document/mistral` | Mistral OCR, capability evidence, unit limits, and the optional office render-to-PDF route | generic format detection, office conversion, or storage authority |
| `cmd/docbank` | Cobra ergonomics and human output | store business logic |
| root package `docbank` | lifecycle and bounded public operations for one exclusively owned embedded vault | standalone CLI paths or a second storage implementation |
Expand Down
8 changes: 4 additions & 4 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"generate:api": "orval --config orval.config.ts"
},
"dependencies": {
"@kenn-io/kit-ui": "git+https://github.com/kenn-io/kit-ui.git#b35e4ca7df66969f4650327d6e315986afef8716",
"@kenn-io/kit-ui": "git+https://github.com/kenn-io/kit-ui.git#49ea5cde2814f4e4ac577d1da1b735fd4255b3b3",
"@lucide/svelte": "1.24.0",
"@noble/hashes": "^2.2.0",
"svelte": "5.56.4",
Expand Down
1 change: 1 addition & 0 deletions frontend/screenshots/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ selection, packed-storage status, and independently verified permanent-audit
evidence. The processing plan, partial semantic coverage, and sanitized Markdown
rendition are captured separately under `.superpowers/processing-screenshots/`
for pull request review. Generated images are intentionally not committed to the main branch.
The Playwright config sets `DOCBANK_TELEMETRY_ENABLED=0` for every spec, so harness daemons send no usage telemetry.

The command must produce the complete set listed in `scripts/docs-assets.txt`.
Documentation builds consume a reviewed set and never run this harness.
Expand Down
Loading
Loading