Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(teamhub): store, serve, and act on Local Computer models
Dongdong Chen34a832461e31
diff --git a/apps/teamhub/AGENTS.md b/apps/teamhub/AGENTS.mdindex 88be69f9..2214ace6 100644--- a/apps/teamhub/AGENTS.md+++ b/apps/teamhub/AGENTS.md@@ -158,5 +158,19 @@ Go service owning Human HTTP/SSE, Agent callbacks, and active product state.environment key over one saved in the product (`voice_provider_keys`, sealedwith `TEAMHUB_SECRET_ENCRYPTION_KEY`), so a save applies without a restarton every replica. A save wakes the Node Services voice workers best effort.+- Local models: `local_computer_model_snapshots` keeps each Computer's latest+ model library snapshot and the last host any snapshot carried; removing the+ Computer deletes the row in the same transaction. Recording a snapshot+ publishes a `local-models` invalidation (id is the Computer ID) to the+ owner's Tenant. Any member of the Computer's Tenant reads the library;+ `used_by` lists active Agents on runtime `pi` on that Computer whose+ `runtime_model` equals the model's `pi_model` exactly (loaded or not), limited to the+ Agents the reader sees in the Agent directory. Only the owner acts+ (`LOCAL_MODEL_ACTION_FORBIDDEN`), and only while the Computer is online by+ the Computers page's 60-second rule (`LOCAL_COMPUTER_OFFLINE`). A connected+ Computer that has not decided within the action's 10 seconds answers 504+ `LOCAL_MODEL_ACTION_UNCONFIRMED`: it may still act, and the snapshots show+ the outcome. The Computer's refusal codes map to `LocalModelsErrorCode` in+ `internal/app/handlers_local_models.go`.- Do not add write-only audit, event, or provenance tables. A new audit tableneeds a named product or compliance reader in the same pull request.diff --git a/apps/teamhub/internal/agentruntimestate/local_models.go b/apps/teamhub/internal/agentruntimestate/local_models.gonew file mode 100644index 00000000..c3eea4e6--- /dev/null+++ b/apps/teamhub/internal/agentruntimestate/local_models.go@@ -0,0 +1,122 @@+package agentruntimestate++import (+ "context"+ "encoding/json"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/realtime"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"+)++// maxLocalModelsSnapshotBytes bounds one stored snapshot. The contract caps a+// snapshot at 256 models and 65 pools, which stays far below it.+const maxLocalModelsSnapshotBytes = 4 << 20++// RecordLocalModelsInput is the latest model library a Computer reported.+// Snapshot is the JSON object the Agent Service forwarded and Host its host+// object, empty when the snapshot carries none.+type RecordLocalModelsInput struct {+ ComputerID string+ Snapshot json.RawMessage+ Host json.RawMessage+ ObservedAt time.Time+}++// LocalModelUser is an active Agent on runtime pi placed on the Computer.+type LocalModelUser struct {+ AgentID string+ Name string+ RuntimeModel string+}++// LocalModelsRecord is what TeamHub keeps about a Computer's model library:+// the Computer row, its latest snapshot (nil when it never sent one), the+// last host a snapshot carried, and the Agents on runtime pi the viewer may+// see.+type LocalModelsRecord struct {+ ComputerID string+ DisplayName string+ Owner LocalComputerOwner+ Status string+ LastSeenAt *time.Time+ Snapshot json.RawMessage+ Host json.RawMessage+ Users []LocalModelUser+}++// RecordLocalModels replaces a Computer's stored model library and tells the+// owner's Tenant to refetch it. Ordering is the Agent Service's job: it+// forwards one Computer's snapshots one at a time, newest last.+func (s *Service) RecordLocalModels(ctx context.Context, input RecordLocalModelsInput) error {+ if !validComputerID(input.ComputerID) || input.ObservedAt.IsZero() ||+ !jsonObject(input.Snapshot) || (len(input.Host) > 0 && !jsonObject(input.Host)) {+ return ErrInvalid+ }+ _, err := executeLocalComputerTx(ctx, s, func(ctx context.Context, _ pgx.Tx, queries *store.Queries) (struct{}, *LocalComputerOwner, error) {+ computer, err := queries.LockAgentRuntimeLocalComputer(ctx, input.ComputerID)+ if isNoRows(err) || (err == nil && computer.Status == "removed") {+ return struct{}{}, nil, ErrNotFound+ }+ if err != nil {+ return struct{}{}, nil, err+ }+ if err := queries.UpsertLocalComputerModelSnapshot(ctx, store.UpsertLocalComputerModelSnapshotParams{+ ComputerID: input.ComputerID, Snapshot: input.Snapshot, Host: input.Host, ObservedAt: timestamptz(input.ObservedAt),+ }); err != nil {+ return struct{}{}, nil, err+ }+ return struct{}{}, nil, realtime.Invalidate(ctx, queries, realtime.Invalidation{+ TenantID: computer.OwnerTenantID, Resource: realtime.InvalidateLocalModels, ID: input.ComputerID,+ })+ })+ return err+}++// LocalModels reads a Computer's stored model library for a member of the+// Computer's Tenant. A Computer of another Tenant, or a removed one, is+// ErrNotFound.+func (s *Service) LocalModels(ctx context.Context, tenantID, viewerActorID, computerID string) (LocalModelsRecord, error) {+ if s == nil || s.pool == nil || !validComputerID(computerID) || tenantID == "" || viewerActorID == "" {+ return LocalModelsRecord{}, ErrInvalid+ }+ queries := store.New(s.pool)+ computer, err := queries.GetAgentRuntimeLocalComputer(ctx, computerID)+ if isNoRows(err) || (err == nil && (computer.Status == "removed" || computer.OwnerTenantID != tenantID)) {+ return LocalModelsRecord{}, ErrNotFound+ }+ if err != nil {+ return LocalModelsRecord{}, err+ }+ record := LocalModelsRecord{+ ComputerID: computer.ComputerID, DisplayName: computer.DisplayName, Status: computer.Status,+ Owner: LocalComputerOwner{TenantID: computer.OwnerTenantID, OwnerActorID: computer.OwnerActorID},+ }+ if computer.LastSeenAt.Valid {+ lastSeenAt := computer.LastSeenAt.Time.UTC()+ record.LastSeenAt = &lastSeenAt+ }+ snapshot, err := queries.GetLocalComputerModelSnapshot(ctx, computerID)+ if err != nil && !isNoRows(err) {+ return LocalModelsRecord{}, err+ }+ if err == nil {+ record.Snapshot, record.Host = snapshot.Snapshot, snapshot.Host+ }+ users, err := queries.ListLocalModelUsersOnComputer(ctx, store.ListLocalModelUsersOnComputerParams{+ TenantID: tenantID, ComputerID: computerID, ViewerActorID: viewerActorID,+ })+ if err != nil {+ return LocalModelsRecord{}, err+ }+ record.Users = make([]LocalModelUser, len(users))+ for index, user := range users {+ record.Users[index] = LocalModelUser{AgentID: user.AgentID, Name: user.DisplayName, RuntimeModel: user.RuntimeModel}+ }+ return record, nil+}++func jsonObject(value json.RawMessage) bool {+ return len(value) > 0 && len(value) <= maxLocalModelsSnapshotBytes && value[0] == '{' && json.Valid(value)+}diff --git a/apps/teamhub/internal/agentruntimestate/runner.go b/apps/teamhub/internal/agentruntimestate/runner.goindex 4ccf3c8e..c15aa190 100644--- a/apps/teamhub/internal/agentruntimestate/runner.go+++ b/apps/teamhub/internal/agentruntimestate/runner.go@@ -252,6 +252,9 @@ func (s *Service) RemoveLocalComputer(ctx context.Context, input LocalComputerCrif err := queries.PurgeAgentRuntimeLocalComputerEnrollmentsByComputer(ctx, input.ComputerID); err != nil {return "", nil, err}+ if err := queries.DeleteLocalComputerModelSnapshot(ctx, input.ComputerID); err != nil {+ return "", nil, err+ }if _, err := queries.RemoveAgentRuntimeLocalComputer(ctx, input.ComputerID); err != nil {return "", nil, err}diff --git a/apps/teamhub/internal/app/handlers_local_models.go b/apps/teamhub/internal/app/handlers_local_models.goindex 6903b297..5dcb6a8e 100644--- a/apps/teamhub/internal/app/handlers_local_models.go+++ b/apps/teamhub/internal/app/handlers_local_models.go@@ -1,27 +1,308 @@package appimport (+ "encoding/json"+ "errors""net/http"+ "regexp"+ "slices"+ "time""github.com/gin-gonic/gin"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentregistry"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentruntimestate"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/ids"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/roomagent"+ "github.com/simplexai-labs/linger/contracts-go/teamhubinternal"+ httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic")-// The Local models endpoints are mounted so the route table matches the-// contracts; they answer NOT_IMPLEMENTED until TeamHub stores snapshots and-// forwards actions.+// localModelActionLifetime bounds how long the Computer may take to accept+// an action; it stays inside the Agent management client's timeout.+const localModelActionLifetime = 10 * time.Second+var localModelIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$`)++// localModelRefusalCodes maps the Computer's refusals a Human can act on to+// their own public code; every other refusal is LOCAL_MODEL_ACTION_FAILED.+var localModelRefusalCodes = map[string]httpapi.LocalModelsErrorCode{+ "TOOL_NOT_INSTALLED": httpapi.LocalModelsErrorCodeLOCALMODELSUNAVAILABLE,+ "TOOL_FAILED": httpapi.LocalModelsErrorCodeLOCALMODELSUNAVAILABLE,+ "MODEL_UNKNOWN": httpapi.LocalModelsErrorCodeLOCALMODELUNKNOWN,+ "INVALID_STATE": httpapi.LocalModelsErrorCodeLOCALMODELINVALIDSTATE,+ "JOB_RUNNING": httpapi.LocalModelsErrorCodeLOCALMODELJOBRUNNING,+ "LOAD_NO_ROOM": httpapi.LocalModelsErrorCodeLOCALMODELNOROOM,+ "MEMORY_INSUFFICIENT": httpapi.LocalModelsErrorCodeLOCALMODELMEMORYINSUFFICIENT,+ "DISK_INSUFFICIENT": httpapi.LocalModelsErrorCodeLOCALMODELDISKINSUFFICIENT,+ "PLATFORM_UNSUPPORTED": httpapi.LocalModelsErrorCodeLOCALMODELPLATFORMUNSUPPORTED,+}++var localModelsErrorMessages = map[httpapi.LocalModelsErrorCode]string{+ httpapi.LocalModelsErrorCodeLOCALCOMPUTEROFFLINE: "Local Computer is offline",+ httpapi.LocalModelsErrorCodeLOCALMODELACTIONFORBIDDEN: "Only the Computer's owner can change its models",+ httpapi.LocalModelsErrorCodeLOCALMODELSUNAVAILABLE: "The Computer has no usable model library",+ httpapi.LocalModelsErrorCodeLOCALMODELUNKNOWN: "The Computer does not know this model",+ httpapi.LocalModelsErrorCodeLOCALMODELINVALIDSTATE: "The model cannot do that in its current state",+ httpapi.LocalModelsErrorCodeLOCALMODELJOBRUNNING: "The Computer is already working on this model",+ httpapi.LocalModelsErrorCodeLOCALMODELNOROOM: "There is not enough free memory to load this model",+ httpapi.LocalModelsErrorCodeLOCALMODELMEMORYINSUFFICIENT: "The Computer does not have enough memory for this model",+ httpapi.LocalModelsErrorCodeLOCALMODELDISKINSUFFICIENT: "The Computer does not have enough disk space for this model",+ httpapi.LocalModelsErrorCodeLOCALMODELPLATFORMUNSUPPORTED: "The model does not run on this Computer",+ httpapi.LocalModelsErrorCodeLOCALMODELACTIONFAILED: "The Computer could not start this action",+ httpapi.LocalModelsErrorCodeLOCALMODELACTIONUNCONFIRMED: "The Computer did not confirm the action in time",+ httpapi.LocalModelsErrorCodeLOCALMODELSSERVICEUNAVAILABLE: "Local models are unavailable",+}++var localModelsErrorStatuses = map[httpapi.LocalModelsErrorCode]int{+ httpapi.LocalModelsErrorCodeLOCALCOMPUTEROFFLINE: http.StatusServiceUnavailable,+ httpapi.LocalModelsErrorCodeLOCALMODELACTIONFORBIDDEN: http.StatusForbidden,+ httpapi.LocalModelsErrorCodeLOCALMODELACTIONFAILED: http.StatusBadGateway,+ httpapi.LocalModelsErrorCodeLOCALMODELACTIONUNCONFIRMED: http.StatusGatewayTimeout,+ httpapi.LocalModelsErrorCodeLOCALMODELSSERVICEUNAVAILABLE: http.StatusServiceUnavailable,+}++// storedLocalModelsSnapshot reads a stored snapshot into the public shapes,+// which match the internal ones field for field.+type storedLocalModelsSnapshot struct {+ Available bool `json:"available"`+ Reason *httpapi.LocalModelsViewUnavailableReason `json:"reason"`+ ObservedAt *time.Time `json:"observed_at"`+ ToolVersion *string `json:"tool_version"`+ Pools []httpapi.LocalModelPool `json:"pools"`+ Models []httpapi.LocalModel `json:"models"`+}++// getLocalComputerModels shows a Computer's last reported model library to+// any member of its Tenant; only the owner may act on it.func (a *App) getLocalComputerModels(c *gin.Context) {- a.writeLocalModelsNotImplemented(c)+ tenantID, computerID := c.Param("tenantId"), c.Param("computerId")+ viewerID, ok := a.spaceHuman(c, tenantID)+ if !ok {+ return+ }+ if a.agentRuntimeState == nil {+ a.writeLocalModelsError(c, httpapi.LocalModelsErrorCodeLOCALMODELSSERVICEUNAVAILABLE)+ return+ }+ record, err := a.agentRuntimeState.LocalModels(c.Request.Context(), tenantID, viewerID, computerID)+ switch {+ case errors.Is(err, agentruntimestate.ErrNotFound), errors.Is(err, agentruntimestate.ErrInvalid):+ a.writeError(c, http.StatusNotFound, "LOCAL_COMPUTER_NOT_FOUND", "Local Computer was not found")+ return+ case err != nil:+ a.internalError(c, "read Local Computer models", err)+ return+ }+ view, err := localModelsView(record, viewerID, time.Now())+ if err != nil {+ a.internalError(c, "project Local Computer models", err)+ return+ }+ c.Header("Cache-Control", "no-store")+ c.JSON(http.StatusOK, view)}+func localModelsView(record agentruntimestate.LocalModelsRecord, viewerID string, now time.Time) (httpapi.LocalModelsView, error) {+ view := httpapi.LocalModelsView{+ Computer: httpapi.LocalModelsComputer{+ ComputerId: record.ComputerID, DisplayName: record.DisplayName,+ Status: httpapi.LocalModelsComputerOffline, LastSeenAt: record.LastSeenAt,+ },+ ViewerIsOwner: record.Owner.OwnerActorID == viewerID,+ Pools: []httpapi.LocalModelPool{}, Models: []httpapi.LocalModelView{},+ }+ if localComputerOnline(record.Status, record.LastSeenAt, now) {+ view.Computer.Status = httpapi.LocalModelsComputerOnline+ }+ if len(record.Host) > 0 {+ var host httpapi.LocalModelHost+ if err := json.Unmarshal(record.Host, &host); err != nil {+ return httpapi.LocalModelsView{}, err+ }+ view.Computer.Host = &host+ }+ if len(record.Snapshot) == 0 {+ view.Reason = &httpapi.LocalModelsViewUnavailableReason{Code: httpapi.LocalModelsViewNotReported}+ return view, nil+ }+ var snapshot storedLocalModelsSnapshot+ if err := json.Unmarshal(record.Snapshot, &snapshot); err != nil {+ return httpapi.LocalModelsView{}, err+ }+ view.Available, view.Reason, view.ObservedAt, view.ToolVersion = snapshot.Available, snapshot.Reason, snapshot.ObservedAt, snapshot.ToolVersion+ if snapshot.Pools != nil {+ view.Pools = snapshot.Pools+ }+ for _, model := range snapshot.Models {+ users := []httpapi.LocalModelUser{}+ // An Agent on runtime pi stores the model's pi_model, which the model+ // keeps while it is on the Computer, loaded or not.+ if model.PiModel != nil {+ for _, user := range record.Users {+ if user.RuntimeModel == *model.PiModel {+ users = append(users, httpapi.LocalModelUser{AgentId: user.AgentID, Name: user.Name})+ }+ }+ }+ view.Models = append(view.Models, httpapi.LocalModelView{Model: model, UsedBy: users})+ }+ return view, nil+}++// localComputerOnline applies the Computers page rule: online only while the+// Runner Gateway's last observation is fresh.+func localComputerOnline(status string, lastSeenAt *time.Time, now time.Time) bool {+ return status == "online" && lastSeenAt != nil && !lastSeenAt.After(now) &&+ now.Sub(*lastSeenAt) <= agentregistry.LocalComputerObservationFreshness+}++// actOnLocalComputerModel forwards the owner's action to their connected+// Computer and answers with the Computer's immediate accept or refusal.func (a *App) actOnLocalComputerModel(c *gin.Context) {- a.writeLocalModelsNotImplemented(c)+ var request httpapi.LocalModelActionRequest+ modelID := c.Param("modelId")+ if err := decodeJSON(c, &request); err != nil || !validLocalModelAction(modelID, request) {+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Local model action is invalid")+ return+ }+ tenantID, computerID := c.Param("tenantId"), c.Param("computerId")+ viewerID, ok := a.spaceHuman(c, tenantID)+ if !ok {+ return+ }+ if a.agentRuntimeState == nil || a.localComputers == nil {+ a.writeLocalModelsError(c, httpapi.LocalModelsErrorCodeLOCALMODELSSERVICEUNAVAILABLE)+ return+ }+ computer, err := a.agentRuntimeState.GetLocalComputer(c.Request.Context(), computerID)+ switch {+ case errors.Is(err, agentruntimestate.ErrNotFound), errors.Is(err, agentruntimestate.ErrInvalid),+ err == nil && computer.Owner.TenantID != tenantID:+ a.writeError(c, http.StatusNotFound, "LOCAL_COMPUTER_NOT_FOUND", "Local Computer was not found")+ return+ case err != nil:+ a.internalError(c, "read Local Computer for a model action", err)+ return+ }+ if computer.Owner.OwnerActorID != viewerID {+ a.writeLocalModelsError(c, httpapi.LocalModelsErrorCodeLOCALMODELACTIONFORBIDDEN)+ return+ }+ if !localComputerOnline(computer.Status, computer.LastSeenAt, time.Now()) {+ a.writeLocalModelsError(c, httpapi.LocalModelsErrorCodeLOCALCOMPUTEROFFLINE)+ return+ }+ command := roomagent.LocalModelActionCommand{+ TenantID: tenantID, OwnerActorID: viewerID, ComputerID: computerID,+ RequestID: ids.New("local_model_action"), Action: string(request.Action), ModelID: modelID,+ ExpiresAt: time.Now().UTC().Add(localModelActionLifetime),+ }+ if request.UnloadFirst != nil {+ command.UnloadFirst = *request.UnloadFirst+ }+ refusal, err := a.localComputers.ActOnLocalModels(c.Request.Context(), command)+ switch {+ case err == nil && refusal == nil:+ c.JSON(http.StatusAccepted, httpapi.LocalModelActionAccepted{+ ComputerId: computerID, ModelId: modelID, Action: httpapi.LocalModelActionAcceptedAction(request.Action),+ })+ case err == nil:+ code, known := localModelRefusalCodes[refusal.Code]+ if !known {+ a.logger.Warn("local_models.action_refused", "computer_id", computerID, "action", command.Action, "refusal_code", refusal.Code)+ code = httpapi.LocalModelsErrorCodeLOCALMODELACTIONFAILED+ }+ a.writeLocalModelsError(c, code)+ case errors.Is(err, roomagent.ErrLocalComputerNotFound):+ a.writeError(c, http.StatusNotFound, "LOCAL_COMPUTER_NOT_FOUND", "Local Computer was not found")+ case errors.Is(err, roomagent.ErrLocalComputerOffline):+ a.writeLocalModelsError(c, httpapi.LocalModelsErrorCodeLOCALCOMPUTEROFFLINE)+ case errors.Is(err, roomagent.ErrLocalModelsTimeout):+ // The Computer is connected but had not decided; it may still act.+ a.writeLocalModelsError(c, httpapi.LocalModelsErrorCodeLOCALMODELACTIONUNCONFIRMED)+ case errors.Is(err, roomagent.ErrLocalModelsUnsupported):+ a.writeLocalModelsError(c, httpapi.LocalModelsErrorCodeLOCALMODELSUNAVAILABLE)+ default:+ a.logger.Error("local_models.action_failed", "computer_id", computerID, "action", command.Action, "error", err)+ a.writeLocalModelsError(c, httpapi.LocalModelsErrorCodeLOCALMODELSSERVICEUNAVAILABLE)+ }+}++func validLocalModelAction(modelID string, request httpapi.LocalModelActionRequest) bool {+ if !localModelIDPattern.MatchString(modelID) || !request.Action.Valid() {+ return false+ }+ if request.UnloadFirst == nil {+ return true+ }+ unloadFirst := *request.UnloadFirst+ if request.Action != httpapi.LocalModelActionRequestLoad || len(unloadFirst) == 0 || len(unloadFirst) > 64 {+ return false+ }+ for index, id := range unloadFirst {+ if !localModelIDPattern.MatchString(id) || id == modelID || slices.Contains(unloadFirst[:index], id) {+ return false+ }+ }+ return true+}++func (a *App) writeLocalModelsError(c *gin.Context, code httpapi.LocalModelsErrorCode) {+ status, found := localModelsErrorStatuses[code]+ if !found {+ status = http.StatusConflict+ }+ a.writeError(c, status, string(code), localModelsErrorMessages[code])}+// recordAgentRuntimeLocalModels stores a Computer's latest model library as+// the Agent Service forwarded it.func (a *App) recordAgentRuntimeLocalModels(c *gin.Context) {- a.writeLocalModelsNotImplemented(c)+ var request teamhubinternal.RecordLocalModelsRequest+ if !a.decodeAgentRuntimeStateBody(c, &request) {+ return+ }+ if !validLocalModelsSnapshot(request.Snapshot) {+ a.writeAgentRuntimeStateError(c, "decode Local Computer models", agentruntimestate.ErrInvalid)+ return+ }+ snapshot, err := json.Marshal(request.Snapshot)+ var host []byte+ if err == nil && request.Snapshot.Host != nil {+ host, err = json.Marshal(request.Snapshot.Host)+ }+ if err != nil {+ a.writeAgentRuntimeStateError(c, "encode Local Computer models", err)+ return+ }+ err = a.agentRuntimeState.RecordLocalModels(c.Request.Context(), agentruntimestate.RecordLocalModelsInput{+ ComputerID: request.ComputerId, Snapshot: snapshot, Host: host, ObservedAt: request.Snapshot.ObservedAt,+ })+ if a.writeAgentRuntimeStateError(c, "record Local Computer models", err) {+ return+ }+ c.Status(http.StatusNoContent)}-func (a *App) writeLocalModelsNotImplemented(c *gin.Context) {- a.writeError(c, http.StatusNotImplemented, "NOT_IMPLEMENTED", "Local models are not available yet")+// validLocalModelsSnapshot checks what the public view relies on: the+// unavailable reason travels only with an unavailable library, and every+// enum the Web branches on is known.+func validLocalModelsSnapshot(snapshot teamhubinternal.LocalModelsSnapshot) bool {+ if snapshot.ObservedAt.IsZero() || len(snapshot.Pools) > 65 || len(snapshot.Models) > 256 ||+ snapshot.Available != (snapshot.Reason == nil) || (snapshot.Reason != nil && !snapshot.Reason.Code.Valid()) {+ return false+ }+ for _, pool := range snapshot.Pools {+ if !pool.Kind.Valid() {+ return false+ }+ }+ seen := make(map[string]bool, len(snapshot.Models))+ for _, model := range snapshot.Models {+ if !localModelIDPattern.MatchString(model.Id) || seen[model.Id] || !model.State.Valid() || !model.Fit.Valid() {+ return false+ }+ seen[model.Id] = true+ }+ return true}diff --git a/apps/teamhub/internal/app/handlers_local_models_test.go b/apps/teamhub/internal/app/handlers_local_models_test.gonew file mode 100644index 00000000..a563969b--- /dev/null+++ b/apps/teamhub/internal/app/handlers_local_models_test.go@@ -0,0 +1,156 @@+package app++import (+ "encoding/json"+ "testing"+ "time"++ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentruntimestate"+ "github.com/simplexai-labs/linger/contracts-go/teamhubinternal"+ httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"+)++const storedLocalModelsSnapshotJSON = `{"available":true,"observed_at":"2026-11-13T10:00:00Z","tool_version":"2.0.0",+"pools":[{"id":"gpu:0","kind":"gpu","gpu_index":0,"total_bytes":100,"used_bytes":40,"holders":[]}],+"models":[+ {"id":"qwen3-4b:Q4_K_M","name":"Qwen3 4B","description":"","quant":"Q4_K_M","context_tokens":32768,"vision":false,+ "download_bytes":10,"memory_bytes":40,"fit":"gpu","recommended":false,"availability":{"downloadable":true},+ "pool":"gpu:0","state":"loaded","endpoint":{"base_url":"http://127.0.0.1:18100/v1"},"pi_model":"localmodels-library/localmodels-lib-qwen3-8-27b-iq3s-ud-iq3-s/Qwen3.8-27B-UD-IQ3_S"},+ {"id":"quick-install:Q4","name":"Quick Install","description":"","quant":"Q4","context_tokens":8192,"vision":false,+ "download_bytes":10,"memory_bytes":30,"fit":"gpu","recommended":false,"availability":{"downloadable":true},+ "pool":"gpu:0","state":"loaded","endpoint":{"base_url":"http://127.0.0.1:18101/v1"},"pi_model":"localmodels/localmodels-agent"},+ {"id":"idle:Q4","name":"Idle","description":"","quant":"Q4","context_tokens":8192,"vision":false,+ "download_bytes":10,"memory_bytes":30,"fit":"gpu","recommended":false,"availability":{"downloadable":true},+ "pool":"gpu:0","state":"idle","pi_model":"localmodels-library/localmodels-lib-idle-q4/Idle-Q4"},+ {"id":"too-big:Q8","name":"Too Big","description":"","quant":"Q8","context_tokens":8192,"vision":false,+ "download_bytes":10,"memory_bytes":3000,"fit":"none","recommended":false,+ "availability":{"downloadable":false,"reason":{"code":"MEMORY_INSUFFICIENT","need_bytes":3000,"have_bytes":100}},"state":"absent"},+ {"id":"gemma-3:Q4","name":"Gemma 3","description":"","quant":"Q4","context_tokens":8192,"vision":true,+ "download_bytes":10,"memory_bytes":30,"fit":"gpu","recommended":true,"availability":{"downloadable":true},+ "pool":"gpu:0","state":"absent"}]}`++// pi_model is <pi provider>/<pi model id>, what an Agent on runtime pi+// stores as its runtime model; only an exact match uses the model, loaded or+// not.+func TestLocalModelsViewMatchesAgentsToModelsOnTheComputer(t *testing.T) {+ now := time.Date(2026, 11, 13, 10, 0, 30, 0, time.UTC)+ seen := now.Add(-20 * time.Second)+ record := agentruntimestate.LocalModelsRecord{+ ComputerID: "computer_1", DisplayName: "Studio", Status: "online", LastSeenAt: &seen,+ Owner: agentruntimestate.LocalComputerOwner{TenantID: "tenant_1", OwnerActorID: "actor_owner"},+ Snapshot: json.RawMessage(storedLocalModelsSnapshotJSON),+ Host: json.RawMessage(`{"platform":"linux","arch":"x86_64","os_label":"Ubuntu","engine_label":"llama.cpp","ram_total_bytes":1,"disk_free_bytes":1,"gpus":[]}`),+ Users: []agentruntimestate.LocalModelUser{+ {AgentID: "agent_1", Name: "Ada", RuntimeModel: "localmodels-library/localmodels-lib-qwen3-8-27b-iq3s-ud-iq3-s/Qwen3.8-27B-UD-IQ3_S"},+ {AgentID: "agent_2", Name: "Bea", RuntimeModel: "localmodels/localmodels-agent"},+ {AgentID: "agent_3", Name: "Cy", RuntimeModel: "localmodels-lib-qwen3-8-27b-iq3s-ud-iq3-s/Qwen3.8-27B-UD-IQ3_S"},+ {AgentID: "agent_4", Name: "Di", RuntimeModel: "pi-default"},+ {AgentID: "agent_5", Name: "Eve", RuntimeModel: "localmodels-library/localmodels-lib-idle-q4/Idle-Q4"},+ },+ }+ view, err := localModelsView(record, "actor_owner", now)+ if err != nil {+ t.Fatal(err)+ }+ if !view.ViewerIsOwner || !view.Available || view.Reason != nil || view.Computer.Status != httpapi.LocalModelsComputerOnline ||+ view.Computer.Host == nil || view.Computer.Host.OsLabel != "Ubuntu" || view.ToolVersion == nil || *view.ToolVersion != "2.0.0" ||+ view.ObservedAt == nil || len(view.Pools) != 1 || len(view.Models) != 5 {+ t.Fatalf("view=%+v", view)+ }+ if users := view.Models[0].UsedBy; len(users) != 1 || users[0].AgentId != "agent_1" || users[0].Name != "Ada" {+ t.Fatalf("loaded model users=%+v", users)+ }+ if users := view.Models[1].UsedBy; len(users) != 1 || users[0].AgentId != "agent_2" {+ t.Fatalf("Quick Install model users=%+v", users)+ }+ if users := view.Models[2].UsedBy; len(users) != 1 || users[0].AgentId != "agent_5" {+ t.Fatalf("idle model users=%+v", users)+ }+ if view.Models[3].Model.Pool != nil || view.Models[3].Model.Fit != "none" || len(view.Models[3].UsedBy) != 0 {+ t.Fatalf("a model that fits nowhere has no pool: %+v", view.Models[3])+ }+ if users := view.Models[4].UsedBy; users == nil || len(users) != 0 {+ t.Fatalf("a model not on the Computer has no users: %+v", users)+ }++ stale := now.Add(-2 * time.Minute)+ record.LastSeenAt = &stale+ view, err = localModelsView(record, "actor_member", now)+ if err != nil || view.ViewerIsOwner || view.Computer.Status != httpapi.LocalModelsComputerOffline {+ t.Fatalf("stale Computer for a member: view=%+v err=%v", view, err)+ }+}++func TestLocalModelsViewWithoutSnapshotIsNotReported(t *testing.T) {+ view, err := localModelsView(agentruntimestate.LocalModelsRecord{ComputerID: "computer_1", DisplayName: "Studio", Status: "offline"}, "actor_owner", time.Now())+ if err != nil || view.Available || view.Reason == nil || view.Reason.Code != httpapi.LocalModelsViewNotReported ||+ view.ObservedAt != nil || view.Pools == nil || view.Models == nil || view.Computer.Status != httpapi.LocalModelsComputerOffline {+ t.Fatalf("view=%+v err=%v", view, err)+ }+ encoded, err := json.Marshal(view)+ if err != nil {+ t.Fatal(err)+ }+ var shape map[string]any+ if err := json.Unmarshal(encoded, &shape); err != nil || shape["pools"] == nil || shape["models"] == nil {+ t.Fatalf("lists must encode as arrays: %s", encoded)+ }+}++func TestValidLocalModelAction(t *testing.T) {+ list := func(values ...string) *[]string { return &values }+ for _, test := range []struct {+ name string+ modelID string+ request httpapi.LocalModelActionRequest+ want bool+ }{+ {"download", "qwen3-4b:Q4_K_M", httpapi.LocalModelActionRequest{Action: "download"}, true},+ {"load making room", "qwen3-4b:Q4_K_M", httpapi.LocalModelActionRequest{Action: "load", UnloadFirst: list("a:1", "b:2")}, true},+ {"refresh is not public", "qwen3-4b:Q4_K_M", httpapi.LocalModelActionRequest{Action: "refresh"}, false},+ {"bad model id", "../etc", httpapi.LocalModelActionRequest{Action: "unload"}, false},+ {"unload_first only with load", "m:1", httpapi.LocalModelActionRequest{Action: "unload", UnloadFirst: list("a:1")}, false},+ {"empty unload_first", "m:1", httpapi.LocalModelActionRequest{Action: "load", UnloadFirst: list()}, false},+ {"duplicate unload_first", "m:1", httpapi.LocalModelActionRequest{Action: "load", UnloadFirst: list("a:1", "a:1")}, false},+ {"unloads itself", "m:1", httpapi.LocalModelActionRequest{Action: "load", UnloadFirst: list("m:1")}, false},+ } {+ if got := validLocalModelAction(test.modelID, test.request); got != test.want {+ t.Errorf("%s: got %v", test.name, got)+ }+ }+}++func TestValidLocalModelsSnapshot(t *testing.T) {+ var snapshot teamhubinternal.LocalModelsSnapshot+ if err := json.Unmarshal([]byte(storedLocalModelsSnapshotJSON), &snapshot); err != nil {+ t.Fatal(err)+ }+ if !validLocalModelsSnapshot(snapshot) {+ t.Fatal("a valid snapshot was refused")+ }+ reason := &teamhubinternal.LocalModelsUnavailableReason{Code: "TOOL_NOT_INSTALLED"}+ unavailable := teamhubinternal.LocalModelsSnapshot{ObservedAt: snapshot.ObservedAt, Reason: reason}+ if !validLocalModelsSnapshot(unavailable) {+ t.Fatal("an unavailable library with its reason was refused")+ }+ for name, mutate := range map[string]func(*teamhubinternal.LocalModelsSnapshot){+ "available with a reason": func(s *teamhubinternal.LocalModelsSnapshot) { s.Reason = reason },+ "unavailable, no reason": func(s *teamhubinternal.LocalModelsSnapshot) { s.Available = false },+ "no observation time": func(s *teamhubinternal.LocalModelsSnapshot) { s.ObservedAt = time.Time{} },+ "unknown state": func(s *teamhubinternal.LocalModelsSnapshot) { s.Models[0].State = "paused" },+ "duplicate model": func(s *teamhubinternal.LocalModelsSnapshot) { s.Models[1].Id = s.Models[0].Id },+ "unknown pool kind": func(s *teamhubinternal.LocalModelsSnapshot) { s.Pools[0].Kind = "tpu" },+ "unknown unavailable code": func(s *teamhubinternal.LocalModelsSnapshot) {+ s.Available, s.Reason = false, &teamhubinternal.LocalModelsUnavailableReason{Code: "X"}+ },+ } {+ var copied teamhubinternal.LocalModelsSnapshot+ if err := json.Unmarshal([]byte(storedLocalModelsSnapshotJSON), &copied); err != nil {+ t.Fatal(err)+ }+ mutate(&copied)+ if validLocalModelsSnapshot(copied) {+ t.Errorf("%s: accepted", name)+ }+ }+}diff --git a/apps/teamhub/internal/realtime/invalidation.go b/apps/teamhub/internal/realtime/invalidation.goindex f30b5a3d..d34ce44a 100644--- a/apps/teamhub/internal/realtime/invalidation.go+++ b/apps/teamhub/internal/realtime/invalidation.go@@ -38,12 +38,15 @@ const (// been revoked, so browsers drop cached Document bytes. The id is the// Document ID.InvalidateDocumentAccess = "document-access"+ // InvalidateLocalModels: a Local Computer's model library snapshot+ // changed. The id is the Computer ID.+ InvalidateLocalModels = "local-models")var invalidationResources = map[string]bool{InvalidateRoom: true, InvalidateDirectory: true, InvalidateAgents: true, InvalidateAnotherMe: true,InvalidateComputers: true, InvalidateConnections: true, InvalidateWorkItems: true, InvalidateDocument: true,- InvalidateDocumentAccess: true,+ InvalidateDocumentAccess: true, InvalidateLocalModels: true,}// ValidInvalidationResource reports whether resource is a published hint type.diff --git a/apps/teamhub/internal/roomagent/local_models.go b/apps/teamhub/internal/roomagent/local_models.gonew file mode 100644index 00000000..99f2f83e--- /dev/null+++ b/apps/teamhub/internal/roomagent/local_models.go@@ -0,0 +1,96 @@+package roomagent++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "time"++ "github.com/simplexai-labs/linger/contracts-go/nodeservicesinternal"+)++// Errors of a local-models action besides the Computer's own refusals.+var (+ // ErrLocalModelsUnsupported: the connected Computer has not reported a+ // model library on this connection, so it cannot take the action.+ ErrLocalModelsUnsupported = errors.New("Local Computer does not report a model library")+ // ErrLocalModelsTimeout: the Computer did not answer the action in time.+ ErrLocalModelsTimeout = errors.New("Local Computer did not answer the local-models action")+)++// LocalModelActionCommand asks the owner's connected Computer to act on its+// model library. ModelID is empty only for refresh; UnloadFirst is only for+// load.+type LocalModelActionCommand struct {+ TenantID, OwnerActorID, ComputerID string+ RequestID string+ Action string+ ModelID string+ UnloadFirst []string+ ExpiresAt time.Time+}++// LocalModelActionRefusal is the Computer's reason for not starting an+// action. Pool, NeedBytes and FreeBytes come with a refusal for room.+type LocalModelActionRefusal struct {+ Code, Detail, Pool string+ NeedBytes, FreeBytes *int64+}++// ActOnLocalModels forwards one local-models action and returns the+// Computer's immediate answer: nil when it started the action, else its+// refusal. Progress arrives later as stored snapshots.+func (g *HTTPGateway) ActOnLocalModels(ctx context.Context, command LocalModelActionCommand) (*LocalModelActionRefusal, error) {+ if !opaqueIDPattern.MatchString(command.TenantID) || !opaqueIDPattern.MatchString(command.OwnerActorID) || !opaqueIDPattern.MatchString(command.ComputerID) {+ return nil, ErrLocalComputerNotFound+ }+ request := nodeservicesinternal.LocalModelActionCommand{+ RequestId: command.RequestID, Action: nodeservicesinternal.LocalModelActionKind(command.Action),+ ExpiresAt: command.ExpiresAt.UTC(),+ }+ if command.ModelID != "" {+ request.ModelId = &command.ModelID+ }+ if len(command.UnloadFirst) > 0 {+ unloadFirst := append([]string(nil), command.UnloadFirst...)+ request.UnloadFirst = &unloadFirst+ }+ response, err := g.client.ActOnLocalComputerModelsWithResponse(ctx, command.TenantID, command.OwnerActorID, command.ComputerID, request)+ if err != nil {+ return nil, fmt.Errorf("local-models %s: %w", command.Action, err)+ }+ switch code := response.StatusCode(); {+ case code == http.StatusOK && response.JSON200 != nil && response.JSON200.RequestId == command.RequestID:+ ack := response.JSON200+ if ack.Outcome == nodeservicesinternal.LocalModelActionAccepted && ack.Refusal == nil {+ return nil, nil+ }+ if ack.Outcome == nodeservicesinternal.LocalModelActionRefused && ack.Refusal != nil {+ return localModelActionRefusal(*ack.Refusal), nil+ }+ case code == http.StatusNotFound:+ return nil, ErrLocalComputerNotFound+ case code == http.StatusConflict:+ return nil, ErrLocalModelsUnsupported+ case code == http.StatusServiceUnavailable && response.JSON503 != nil:+ switch response.JSON503.Error.Code {+ case "LOCAL_COMPUTER_OFFLINE":+ return nil, ErrLocalComputerOffline+ case "LOCAL_MODELS_ACTION_TIMEOUT":+ return nil, ErrLocalModelsTimeout+ }+ }+ return nil, fmt.Errorf("AgentManagement returned status %d for local-models %s", response.StatusCode(), command.Action)+}++func localModelActionRefusal(value nodeservicesinternal.LocalModelActionRefusal) *LocalModelActionRefusal {+ refusal := &LocalModelActionRefusal{Code: string(value.Code), NeedBytes: value.NeedBytes, FreeBytes: value.FreeBytes}+ if value.Detail != nil {+ refusal.Detail = *value.Detail+ }+ if value.Pool != nil {+ refusal.Pool = *value.Pool+ }+ return refusal+}diff --git a/apps/teamhub/internal/roomagent/local_models_test.go b/apps/teamhub/internal/roomagent/local_models_test.gonew file mode 100644index 00000000..d19cb904--- /dev/null+++ b/apps/teamhub/internal/roomagent/local_models_test.go@@ -0,0 +1,86 @@+package roomagent++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++func TestHTTPGatewayForwardsLocalModelActionAndReadsTheAnswer(t *testing.T) {+ answer := `{"request_id":"request_1","outcome":"accepted"}`+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost || r.URL.Path != "/v1/tenants/tenant_1/owners/actor_owner/local-computers/computer_1/local-model-actions" {+ t.Fatalf("%s %s", r.Method, r.URL.Path)+ }+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Fatal(err)+ }+ unloadFirst, _ := body["unload_first"].([]any)+ if len(body) != 5 || body["request_id"] != "request_1" || body["action"] != "load" || body["model_id"] != "qwen3-4b:Q4_K_M" ||+ len(unloadFirst) != 1 || unloadFirst[0] != "gemma-3:Q4" || body["expires_at"] != "2026-11-13T10:00:00Z" {+ t.Fatalf("body=%v", body)+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(answer))+ }))+ t.Cleanup(server.Close)+ gateway, err := NewHTTPGateway(server.URL, "service-secret", server.Client())+ if err != nil {+ t.Fatal(err)+ }+ command := LocalModelActionCommand{+ TenantID: "tenant_1", OwnerActorID: "actor_owner", ComputerID: "computer_1", RequestID: "request_1",+ Action: "load", ModelID: "qwen3-4b:Q4_K_M", UnloadFirst: []string{"gemma-3:Q4"},+ ExpiresAt: time.Date(2026, 11, 13, 18, 0, 0, 0, time.FixedZone("CST", 8*3600)),+ }+ refusal, err := gateway.ActOnLocalModels(context.Background(), command)+ if err != nil || refusal != nil {+ t.Fatalf("accepted answer read as refusal=%+v err=%v", refusal, err)+ }+ answer = `{"request_id":"request_1","outcome":"refused","refusal":{"code":"LOAD_NO_ROOM","pool":"gpu:1","need_bytes":10,"free_bytes":4}}`+ refusal, err = gateway.ActOnLocalModels(context.Background(), command)+ if err != nil || refusal == nil || refusal.Code != "LOAD_NO_ROOM" || refusal.Pool != "gpu:1" ||+ refusal.NeedBytes == nil || *refusal.NeedBytes != 10 || refusal.FreeBytes == nil || *refusal.FreeBytes != 4 {+ t.Fatalf("refusal=%+v err=%v", refusal, err)+ }+ answer = `{"request_id":"request_other","outcome":"accepted"}`+ if refusal, err = gateway.ActOnLocalModels(context.Background(), command); err == nil {+ t.Fatalf("an answer to another request was accepted: %+v", refusal)+ }+}++func TestHTTPGatewayMapsLocalModelActionFailures(t *testing.T) {+ for _, test := range []struct {+ status int+ body string+ want error+ }{+ {http.StatusNotFound, `{"error":{"code":"LOCAL_COMPUTER_NOT_FOUND","message":"x","request_id":"r"}}`, ErrLocalComputerNotFound},+ {http.StatusConflict, `{"error":{"code":"LOCAL_MODELS_UNSUPPORTED","message":"x","request_id":"r"}}`, ErrLocalModelsUnsupported},+ {http.StatusServiceUnavailable, `{"error":{"code":"LOCAL_COMPUTER_OFFLINE","message":"x","request_id":"r"}}`, ErrLocalComputerOffline},+ {http.StatusServiceUnavailable, `{"error":{"code":"LOCAL_MODELS_ACTION_TIMEOUT","message":"x","request_id":"r"}}`, ErrLocalModelsTimeout},+ } {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(test.status)+ _, _ = w.Write([]byte(test.body))+ }))+ gateway, err := NewHTTPGateway(server.URL, "service-secret", server.Client())+ if err != nil {+ t.Fatal(err)+ }+ _, err = gateway.ActOnLocalModels(context.Background(), LocalModelActionCommand{+ TenantID: "tenant_1", OwnerActorID: "actor_owner", ComputerID: "computer_1", RequestID: "request_1",+ Action: "unload", ModelID: "qwen3-4b:Q4_K_M", ExpiresAt: time.Now(),+ })+ server.Close()+ if !errors.Is(err, test.want) {+ t.Fatalf("status %d: err=%v want %v", test.status, err, test.want)+ }+ }+}diff --git a/apps/teamhub/internal/roomagent/types.go b/apps/teamhub/internal/roomagent/types.goindex a9926363..ffd9c42b 100644--- a/apps/teamhub/internal/roomagent/types.go+++ b/apps/teamhub/internal/roomagent/types.go@@ -92,6 +92,7 @@ type LocalComputerManagement interface {ScanLocalSkills(ctx context.Context, command LocalSkillScanCommand) (LocalSkillScan, error)ConnectLocalBrowser(ctx context.Context, command LocalBrowserConnectionCommand) (LocalBrowserConnectionStatus, error)LocalComputerPermissions(ctx context.Context, command LocalComputerPermissionCommand) (LocalComputerPermissionStatus, error)+ ActOnLocalModels(ctx context.Context, command LocalModelActionCommand) (*LocalModelActionRefusal, error)}// LocalBrowserConnectionAction selects how a browser connection command changes the Computer.diff --git a/apps/teamhub/internal/store/agent_runtime_state.sql.go b/apps/teamhub/internal/store/agent_runtime_state.sql.goindex 4c09976b..fd814c2d 100644--- a/apps/teamhub/internal/store/agent_runtime_state.sql.go+++ b/apps/teamhub/internal/store/agent_runtime_state.sql.go@@ -577,6 +577,16 @@ func (q *Queries) DeleteAgentRuntimeSessionAtConfigurationRevision(ctx context.Creturn result.RowsAffected(), nil}+const deleteLocalComputerModelSnapshot = `-- name: DeleteLocalComputerModelSnapshot :exec+DELETE FROM local_computer_model_snapshots+WHERE computer_id=$1::text+`++func (q *Queries) DeleteLocalComputerModelSnapshot(ctx context.Context, computerID string) error {+ _, err := q.db.Exec(ctx, deleteLocalComputerModelSnapshot, computerID)+ return err+}+const deletePendingAgentRuntimeLocalComputerEnrollments = `-- name: DeletePendingAgentRuntimeLocalComputerEnrollments :execDELETE FROM local_computer_enrollmentsWHERE tenant_id=$1::text@@ -1224,6 +1234,24 @@ func (q *Queries) GetLatestAgentRuntimeActivityEvent(ctx context.Context, arg Gereturn i, err}+const getLocalComputerModelSnapshot = `-- name: GetLocalComputerModelSnapshot :one+SELECT snapshot,host+FROM local_computer_model_snapshots+WHERE computer_id=$1::text+`++type GetLocalComputerModelSnapshotRow struct {+ Snapshot []byte `json:"snapshot"`+ Host []byte `json:"host"`+}++func (q *Queries) GetLocalComputerModelSnapshot(ctx context.Context, computerID string) (GetLocalComputerModelSnapshotRow, error) {+ row := q.db.QueryRow(ctx, getLocalComputerModelSnapshot, computerID)+ var i GetLocalComputerModelSnapshotRow+ err := row.Scan(&i.Snapshot, &i.Host)+ return i, err+}+const getMaterializableAgentRuntimeRegistrationByManagementID = `-- name: GetMaterializableAgentRuntimeRegistrationByManagementID :oneSELECT registration.actor_id,registration.tenant_id,registration.status,registration.agent_management_id,registration.configuration_revision,@@ -2346,6 +2374,65 @@ func (q *Queries) ListAgentRuntimeSteeringInputs(ctx context.Context, contextKeyreturn items, nil}+const listLocalModelUsersOnComputer = `-- name: ListLocalModelUsersOnComputer :many+SELECT registration.agent_management_id::text AS agent_id,+ agent.display_name,registration.runtime_model+FROM agent_registrations registration+JOIN actors agent+ ON agent.id=registration.actor_id AND agent.tenant_id=registration.tenant_id+WHERE registration.tenant_id=$1::text+ AND registration.computer_id=$2::text+ AND registration.status='active'+ AND registration.local_runtime_type='pi'+ AND (+ registration.visibility_scope='workspace' OR+ registration.created_by_actor_id=$3::text OR+ EXISTS (+ SELECT 1+ FROM active_room_members viewer_membership+ JOIN active_room_members agent_membership+ ON agent_membership.room_id=viewer_membership.room_id+ AND agent_membership.actor_id=registration.actor_id+ WHERE viewer_membership.actor_id=$3::text+ )+ )+ORDER BY agent.display_name,registration.agent_management_id+`++type ListLocalModelUsersOnComputerParams struct {+ TenantID string `json:"tenant_id"`+ ComputerID string `json:"computer_id"`+ ViewerActorID string `json:"viewer_actor_id"`+}++type ListLocalModelUsersOnComputerRow struct {+ AgentID string `json:"agent_id"`+ DisplayName string `json:"display_name"`+ RuntimeModel string `json:"runtime_model"`+}++// Active Agents on runtime pi placed on a Computer, limited to those the+// viewer sees in the Tenant Agent directory (ListTenantAgentsForAccount).+func (q *Queries) ListLocalModelUsersOnComputer(ctx context.Context, arg ListLocalModelUsersOnComputerParams) ([]ListLocalModelUsersOnComputerRow, error) {+ rows, err := q.db.Query(ctx, listLocalModelUsersOnComputer, arg.TenantID, arg.ComputerID, arg.ViewerActorID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListLocalModelUsersOnComputerRow{}+ for rows.Next() {+ var i ListLocalModelUsersOnComputerRow+ if err := rows.Scan(&i.AgentID, &i.DisplayName, &i.RuntimeModel); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listMaterializableAgentRuntimeRegistrationsAfter = `-- name: ListMaterializableAgentRuntimeRegistrationsAfter :manySELECT COALESCE(registration.agent_management_id,'')::text AS agent_management_idFROM agent_registrations registration@@ -4338,3 +4425,30 @@ func (q *Queries) UpsertAgentPerRoomMetaContext(ctx context.Context, arg UpsertA}return result.RowsAffected(), nil}++const upsertLocalComputerModelSnapshot = `-- name: UpsertLocalComputerModelSnapshot :exec+INSERT INTO local_computer_model_snapshots(computer_id,snapshot,host,observed_at,updated_at)+VALUES($1::text,$2::jsonb,$3::jsonb,+ $4::timestamptz,clock_timestamp())+ON CONFLICT (computer_id) DO UPDATE+SET snapshot=EXCLUDED.snapshot,+ host=COALESCE(EXCLUDED.host,local_computer_model_snapshots.host),+ observed_at=EXCLUDED.observed_at,updated_at=EXCLUDED.updated_at+`++type UpsertLocalComputerModelSnapshotParams struct {+ ComputerID string `json:"computer_id"`+ Snapshot []byte `json:"snapshot"`+ Host []byte `json:"host"`+ ObservedAt pgtype.Timestamptz `json:"observed_at"`+}++func (q *Queries) UpsertLocalComputerModelSnapshot(ctx context.Context, arg UpsertLocalComputerModelSnapshotParams) error {+ _, err := q.db.Exec(ctx, upsertLocalComputerModelSnapshot,+ arg.ComputerID,+ arg.Snapshot,+ arg.Host,+ arg.ObservedAt,+ )+ return err+}diff --git a/apps/teamhub/internal/store/models.go b/apps/teamhub/internal/store/models.goindex 5788c56a..12c01724 100644--- a/apps/teamhub/internal/store/models.go+++ b/apps/teamhub/internal/store/models.go@@ -858,6 +858,14 @@ type LocalComputerEnrollment struct {CreatedAt pgtype.Timestamptz `json:"created_at"`}+type LocalComputerModelSnapshot struct {+ ComputerID string `json:"computer_id"`+ Snapshot []byte `json:"snapshot"`+ Host []byte `json:"host"`+ ObservedAt pgtype.Timestamptz `json:"observed_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type MemoryIndexChunk struct {ID string `json:"id"`TenantID string `json:"tenant_id"`diff --git a/apps/teamhub/internal/store/queries/agent_runtime_state.sql b/apps/teamhub/internal/store/queries/agent_runtime_state.sqlindex 64a36a0b..87fe86f5 100644--- a/apps/teamhub/internal/store/queries/agent_runtime_state.sql+++ b/apps/teamhub/internal/store/queries/agent_runtime_state.sql@@ -1392,3 +1392,47 @@ WHERE message.id=sqlc.arg(message_id)::textAND message.room_id=sqlc.arg(room_id)::textAND message.tenant_id=context.tenant_idAND message.author_actor_id=context.agent_actor_id;++-- name: UpsertLocalComputerModelSnapshot :exec+INSERT INTO local_computer_model_snapshots(computer_id,snapshot,host,observed_at,updated_at)+VALUES(sqlc.arg(computer_id)::text,sqlc.arg(snapshot)::jsonb,sqlc.narg(host)::jsonb,+ sqlc.arg(observed_at)::timestamptz,clock_timestamp())+ON CONFLICT (computer_id) DO UPDATE+SET snapshot=EXCLUDED.snapshot,+ host=COALESCE(EXCLUDED.host,local_computer_model_snapshots.host),+ observed_at=EXCLUDED.observed_at,updated_at=EXCLUDED.updated_at;++-- name: DeleteLocalComputerModelSnapshot :exec+DELETE FROM local_computer_model_snapshots+WHERE computer_id=sqlc.arg(computer_id)::text;++-- name: GetLocalComputerModelSnapshot :one+SELECT snapshot,host+FROM local_computer_model_snapshots+WHERE computer_id=sqlc.arg(computer_id)::text;++-- name: ListLocalModelUsersOnComputer :many+-- Active Agents on runtime pi placed on a Computer, limited to those the+-- viewer sees in the Tenant Agent directory (ListTenantAgentsForAccount).+SELECT registration.agent_management_id::text AS agent_id,+ agent.display_name,registration.runtime_model+FROM agent_registrations registration+JOIN actors agent+ ON agent.id=registration.actor_id AND agent.tenant_id=registration.tenant_id+WHERE registration.tenant_id=sqlc.arg(tenant_id)::text+ AND registration.computer_id=sqlc.arg(computer_id)::text+ AND registration.status='active'+ AND registration.local_runtime_type='pi'+ AND (+ registration.visibility_scope='workspace' OR+ registration.created_by_actor_id=sqlc.arg(viewer_actor_id)::text OR+ EXISTS (+ SELECT 1+ FROM active_room_members viewer_membership+ JOIN active_room_members agent_membership+ ON agent_membership.room_id=viewer_membership.room_id+ AND agent_membership.actor_id=registration.actor_id+ WHERE viewer_membership.actor_id=sqlc.arg(viewer_actor_id)::text+ )+ )+ORDER BY agent.display_name,registration.agent_management_id;diff --git a/apps/teamhub/migrations/00874_local_computer_model_snapshots.sql b/apps/teamhub/migrations/00874_local_computer_model_snapshots.sqlnew file mode 100644index 00000000..798f38b9--- /dev/null+++ b/apps/teamhub/migrations/00874_local_computer_model_snapshots.sql@@ -0,0 +1,16 @@+-- +goose Up+-- The latest model library each Local Computer reported, so an offline+-- Computer still shows what it last reported. host is the last host any+-- snapshot carried, kept when a later one (an unavailable library) has none.+-- A removed Computer's row is deleted in the transaction that removes it; the+-- foreign key covers a Computer row that is deleted outright.+CREATE TABLE local_computer_model_snapshots (+ computer_id text PRIMARY KEY REFERENCES local_computers(computer_id) ON DELETE CASCADE,+ snapshot jsonb NOT NULL CHECK (jsonb_typeof(snapshot) = 'object'),+ host jsonb CHECK (host IS NULL OR jsonb_typeof(host) = 'object'),+ observed_at timestamp with time zone NOT NULL,+ updated_at timestamp with time zone DEFAULT now() NOT NULL+);++-- +goose Down+DROP TABLE local_computer_model_snapshots;diff --git a/apps/teamhub/tests/integration/local_computer_test.go b/apps/teamhub/tests/integration/local_computer_test.goindex cc400725..3c32deff 100644--- a/apps/teamhub/tests/integration/local_computer_test.go+++ b/apps/teamhub/tests/integration/local_computer_test.go@@ -45,6 +45,10 @@ func (r *recordingLocalComputers) LocalComputerPermissions(_ context.Context, _return roomagent.LocalComputerPermissionStatus{}, roomagent.ErrLocalComputerPermissionsUnsupported}+func (r *recordingLocalComputers) ActOnLocalModels(_ context.Context, _ roomagent.LocalModelActionCommand) (*roomagent.LocalModelActionRefusal, error) {+ return nil, roomagent.ErrLocalModelsUnsupported+}+func TestTenantAgentAvailabilityProjectsUnknownWhenRuntimeStatusIsMissing(t *testing.T) {allowParallelIntegrationTest(t)artifactRoot := integrationArtifactRoot(t)diff --git a/apps/teamhub/tests/integration/local_models_test.go b/apps/teamhub/tests/integration/local_models_test.gonew file mode 100644index 00000000..17902e8b--- /dev/null+++ b/apps/teamhub/tests/integration/local_models_test.go@@ -0,0 +1,224 @@+package integration_test++import (+ "bufio"+ "context"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/config"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/roomagent"+)++const localModelsLibraryPiModel = "localmodels-library/localmodels-lib-qwen3-8-27b-iq3s-ud-iq3-s/Qwen3.8-27B-UD-IQ3_S"++type localModelsComputers struct {+ recordingLocalComputers+ mu sync.Mutex+ commands []roomagent.LocalModelActionCommand+ refusal *roomagent.LocalModelActionRefusal+ err error+}++func (c *localModelsComputers) ActOnLocalModels(_ context.Context, command roomagent.LocalModelActionCommand) (*roomagent.LocalModelActionRefusal, error) {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.commands = append(c.commands, command)+ return c.refusal, c.err+}++// TestLocalComputerModelsStoreServeAndAct covers what needs PostgreSQL: the+// stored snapshot and its kept host, the invalidation committed with it, the+// used_by visibility rule, owner-only actions, and deletion with the Computer.+func TestLocalComputerModelsStoreServeAndAct(t *testing.T) {+ allowParallelIntegrationTest(t)+ databaseURL := newIntegrationDatabase(t)+ pool, err := pgxpool.New(context.Background(), databaseURL)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(pool.Close)+ computers := &localModelsComputers{}+ application, err := newTestApp(context.Background(), config.ForTest(func(c *config.Config) {+ c.DatabaseURL = databaseURL+ c.SessionTTL = time.Hour+ c.CookieName = "teamhub_session"+ c.TeamHubInternalToken = teamHubInternalToken+ c.NodeServicesInternalToken = nodeServicesInternalToken+ c.AgentRunTokenSecret = agentRunTokenSecret+ c.SSEHeartbeatInterval = 5 * time.Second+ c.SSEQueueCapacity = 8+ c.ArtifactStorageRoot = t.TempDir()+ }), withLocalComputers(computers))+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(application.Close)+ server := httptest.NewServer(application.Handler())+ registerIntegrationServerCleanup(t, server)+ env := &testEnv{t: t, databaseURL: databaseURL, pool: pool, server: server}+ alice := env.login("alice", alicePassword)+ bob := seedPeerHuman(t, env)+ const computerID = "computer_models"+ base := "/v0/tenants/" + acmeTenant + "/local-computers/" + computerID + "/local-models"++ if _, err := pool.Exec(t.Context(), `+INSERT INTO local_computers(computer_id,display_name,status,owner_tenant_id,owner_actor_id,last_seen_at)+VALUES ($1,'Studio','online','tenant_acme','actor_acme_alice',now()-interval '5 seconds')`, computerID); err != nil {+ t.Fatal(err)+ }+ // Bob sees Alice's workspace Agent but not her sponsor-only one; a codex+ // Agent with the same model id never uses a local model.+ if _, err := pool.Exec(t.Context(), `+INSERT INTO actors(id,tenant_id,kind,display_name,handle) VALUES+ ('actor_models_shared','tenant_acme','agent','Shared Pi','models_shared'),+ ('actor_models_private','tenant_acme','agent','Private Pi','models_private'),+ ('actor_models_codex','tenant_acme','agent','Codex','models_codex');+INSERT INTO agent_registrations(actor_id,tenant_id,agent_management_id,status,instructions,runtime_model,+ computer_id,local_runtime_type,workspace_grant_id,created_by_actor_id,visibility_scope) VALUES+ ('actor_models_shared','tenant_acme','agent_models_shared','active','Run','`+localModelsLibraryPiModel+`','computer_models','pi','grant_linger','actor_acme_alice','workspace'),+ ('actor_models_private','tenant_acme','agent_models_private','active','Run','`+localModelsLibraryPiModel+`','computer_models','pi','grant_linger','actor_acme_alice','sponsor'),+ ('actor_models_codex','tenant_acme','agent_models_codex','active','Run','`+localModelsLibraryPiModel+`','computer_models','codex','grant_linger','actor_acme_alice','workspace');+`); err != nil {+ t.Fatal(err)+ }++ var view struct {+ Computer struct {+ Status string `json:"status"`+ Host *struct {+ OsLabel string `json:"os_label"`+ } `json:"host"`+ } `json:"computer"`+ ViewerIsOwner bool `json:"viewer_is_owner"`+ Available bool `json:"available"`+ Reason *struct {+ Code string `json:"code"`+ } `json:"reason"`+ Models []struct {+ Model struct {+ ID string `json:"id"`+ } `json:"model"`+ UsedBy []struct {+ AgentID string `json:"agent_id"`+ } `json:"used_by"`+ } `json:"models"`+ }+ read := func(client *http.Client) {+ t.Helper()+ status, _, body := env.request(client, http.MethodGet, base, nil, "")+ if status != http.StatusOK {+ t.Fatalf("read Local models status=%d body=%s", status, body)+ }+ view.Computer.Host, view.Reason, view.Models = nil, nil, nil+ decode(t, body, &view)+ }+ read(alice)+ if !view.ViewerIsOwner || view.Available || view.Reason == nil || view.Reason.Code != "NOT_REPORTED" || view.Computer.Status != "online" {+ t.Fatalf("a Computer that never reported: %+v", view)+ }++ stream := openSSE(t, alice, server.URL+"/v0/events", 10*time.Second)+ defer stream.Body.Close()+ reader := bufio.NewReader(stream.Body)+ requireSSEReady(t, "alice", reader)+ record := func(snapshot map[string]any) {+ t.Helper()+ status, body := agentRuntimeStateRequest(t, server.Config.Handler, http.MethodPost,+ "/v0/agent-runtime/local-computers/local-models", teamHubInternalToken,+ map[string]any{"computer_id": computerID, "snapshot": snapshot})+ if status != http.StatusNoContent {+ t.Fatalf("record Local models status=%d body=%s", status, body)+ }+ awaitInvalidation(t, reader, "local-models", computerID)+ }+ record(map[string]any{+ "available": true, "observed_at": time.Now().UTC(), "tool_version": "2.0.0",+ "host": map[string]any{"platform": "linux", "arch": "x86_64", "os_label": "Ubuntu 24.04", "engine_label": "llama.cpp",+ "ram_total_bytes": 64 << 30, "disk_free_bytes": 100 << 30, "gpus": []any{}},+ "pools": []any{map[string]any{"id": "gpu:0", "kind": "gpu", "gpu_index": 0, "total_bytes": 24 << 30, "used_bytes": 8 << 30, "holders": []any{}}},+ "models": []any{map[string]any{+ "id": "qwen3.8-27b:IQ3_S", "name": "Qwen3.8 27B", "description": "", "quant": "IQ3_S", "context_tokens": 32768,+ "vision": false, "download_bytes": 12 << 30, "memory_bytes": 14 << 30, "fit": "gpu", "recommended": false,+ // An idle model keeps its pi_model, so its Agents stay listed.+ "availability": map[string]any{"downloadable": true}, "pool": "gpu:0", "state": "idle",+ "pi_model": localModelsLibraryPiModel,+ }},+ })+ read(alice)+ if !view.Available || len(view.Models) != 1 || len(view.Models[0].UsedBy) != 2 || view.Computer.Host == nil {+ t.Fatalf("owner view: %+v", view)+ }+ read(bob)+ if view.ViewerIsOwner || len(view.Models) != 1 || len(view.Models[0].UsedBy) != 1 || view.Models[0].UsedBy[0].AgentID != "agent_models_shared" {+ t.Fatalf("member view: %+v", view)+ }++ // An unavailable library carries no host; the Computer keeps the last one.+ record(map[string]any{"available": false, "reason": map[string]any{"code": "TOOL_FAILED"}, "observed_at": time.Now().UTC(), "pools": []any{}, "models": []any{}})+ read(alice)+ if view.Available || view.Reason == nil || view.Reason.Code != "TOOL_FAILED" || len(view.Models) != 0 ||+ view.Computer.Host == nil || view.Computer.Host.OsLabel != "Ubuntu 24.04" {+ t.Fatalf("unavailable view: %+v", view)+ }++ act := func(client *http.Client, body map[string]any) (int, []byte) {+ t.Helper()+ status, _, response := env.request(client, http.MethodPost, base+"/qwen3.8-27b:IQ3_S/actions", body, "")+ return status, response+ }+ if status, body := act(bob, map[string]any{"action": "unload"}); status != http.StatusForbidden || !containsJSONText(body, "LOCAL_MODEL_ACTION_FORBIDDEN") {+ t.Fatalf("member action status=%d body=%s", status, body)+ }+ if status, body := act(alice, map[string]any{"action": "load", "unload_first": []string{"gemma-3:Q4"}}); status != http.StatusAccepted ||+ !containsJSONText(body, `"action":"load"`) {+ t.Fatalf("owner action status=%d body=%s", status, body)+ }+ if len(computers.commands) != 1 || computers.commands[0].OwnerActorID != "actor_acme_alice" || computers.commands[0].ModelID != "qwen3.8-27b:IQ3_S" ||+ len(computers.commands[0].UnloadFirst) != 1 || computers.commands[0].RequestID == "" {+ t.Fatalf("forwarded commands=%+v", computers.commands)+ }+ computers.refusal = &roomagent.LocalModelActionRefusal{Code: "LOAD_NO_ROOM", Pool: "gpu:0"}+ if status, body := act(alice, map[string]any{"action": "load"}); status != http.StatusConflict || !containsJSONText(body, "LOCAL_MODEL_NO_ROOM") {+ t.Fatalf("refused action status=%d body=%s", status, body)+ }+ computers.refusal = &roomagent.LocalModelActionRefusal{Code: "CHECKSUM_MISMATCH"}+ if status, body := act(alice, map[string]any{"action": "download"}); status != http.StatusBadGateway || !containsJSONText(body, "LOCAL_MODEL_ACTION_FAILED") {+ t.Fatalf("failed action status=%d body=%s", status, body)+ }+ // A connected Computer that had not decided in time is not offline.+ computers.refusal, computers.err = nil, roomagent.ErrLocalModelsTimeout+ if status, body := act(alice, map[string]any{"action": "load"}); status != http.StatusGatewayTimeout || !containsJSONText(body, "LOCAL_MODEL_ACTION_UNCONFIRMED") {+ t.Fatalf("unconfirmed action status=%d body=%s", status, body)+ }+ computers.err = nil+ if _, err := pool.Exec(t.Context(), `UPDATE local_computers SET last_seen_at=now()-interval '2 minutes' WHERE computer_id=$1`, computerID); err != nil {+ t.Fatal(err)+ }+ if status, body := act(alice, map[string]any{"action": "unload"}); status != http.StatusServiceUnavailable || !containsJSONText(body, "LOCAL_COMPUTER_OFFLINE") {+ t.Fatalf("offline action status=%d body=%s", status, body)+ }+ if len(computers.commands) != 4 {+ t.Fatalf("an offline Computer was sent an action: %d commands", len(computers.commands))+ }++ if _, err := pool.Exec(t.Context(), `UPDATE agent_registrations SET status='revoked' WHERE computer_id=$1`, computerID); err != nil {+ t.Fatal(err)+ }+ status, body := agentRuntimeStateRequest(t, server.Config.Handler, http.MethodPost, "/v0/agent-runtime/local-computers/remove", teamHubInternalToken,+ map[string]any{"computer_id": computerID, "owner": map[string]any{"tenant_id": acmeTenant, "owner_actor_id": "actor_acme_alice"}})+ if status != http.StatusOK || !containsJSONText(body, `"removed"`) {+ t.Fatalf("remove Computer status=%d body=%s", status, body)+ }+ var snapshots int+ if err := pool.QueryRow(t.Context(), `SELECT count(*) FROM local_computer_model_snapshots WHERE computer_id=$1`, computerID).Scan(&snapshots); err != nil || snapshots != 0 {+ t.Fatalf("snapshot outlived its Computer: rows=%d err=%v", snapshots, err)+ }+ if status, _, body := env.request(alice, http.MethodGet, base, nil, ""); status != http.StatusNotFound {+ t.Fatalf("removed Computer models status=%d body=%s", status, body)+ }+}