Skip to content

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.

fix(teamhub): remind AnotherMe about a Profile setup left unfinished

muterC032600835a9d
diff --git a/apps/teamhub/internal/app/connection_authorization_workers.go b/apps/teamhub/internal/app/connection_authorization_workers.go
index 8787b515..d1bfe29a 100644
--- a/apps/teamhub/internal/app/connection_authorization_workers.go
+++ b/apps/teamhub/internal/app/connection_authorization_workers.go
@@ -24,3 +24,24 @@ func (*connectionAuthorizationSettleWorker) Timeout(*river.Job[externalsource.Co
func (w *connectionAuthorizationSettleWorker) Work(ctx context.Context, job *river.Job[externalsource.ConnectionAuthorizationSettleArgs]) error {
return w.app.typedCards.SettleConnectionAuthorizations(ctx, job.Args.ConnectionID)
}
+
+// profileSetupReminderWorker reminds AnotherMe about a Profile setup left
+// unfinished after a Connection's first activation, once the Room is quiet.
+type profileSetupReminderWorker struct {
+ river.WorkerDefaults[externalsource.ProfileSetupReminderArgs]
+ app *App
+}
+
+func (*profileSetupReminderWorker) Timeout(*river.Job[externalsource.ProfileSetupReminderArgs]) time.Duration {
+ return time.Minute
+}
+
+// A Room still in conversation snoozes the job until it has been quiet; a
+// snooze spends no attempt.
+func (w *profileSetupReminderWorker) Work(ctx context.Context, job *river.Job[externalsource.ProfileSetupReminderArgs]) error {
+ wait, err := w.app.typedCards.RemindProfileSetup(ctx, job.Args.ConnectionID, time.Now())
+ if err != nil || wait == 0 {
+ return err
+ }
+ return river.JobSnooze(wait)
+}
diff --git a/apps/teamhub/internal/app/feature_external_apps.go b/apps/teamhub/internal/app/feature_external_apps.go
index 1aa63bda..8aeafb76 100644
--- a/apps/teamhub/internal/app/feature_external_apps.go
+++ b/apps/teamhub/internal/app/feature_external_apps.go
@@ -65,6 +65,7 @@ func (a *App) registerExternalApps(ctx context.Context, cfg config.ExternalAppsC
func (a *App) addExternalAppJobs(features *featureSet, appListeners bool) {
externalsource.AddJobWorkers(features.workers, a.externalSources, a.connectedAppsConfigured)
river.AddWorker(features.workers, &connectionAuthorizationSettleWorker{app: a})
+ river.AddWorker(features.workers, &profileSetupReminderWorker{app: a})
features.schedule(a.connectedAppSweeps(features.workers)...)
if !appListeners {
return
diff --git a/apps/teamhub/internal/app/features_test.go b/apps/teamhub/internal/app/features_test.go
index 8561f74b..296e12cf 100644
--- a/apps/teamhub/internal/app/features_test.go
+++ b/apps/teamhub/internal/app/features_test.go
@@ -53,7 +53,7 @@ var externalAppKinds = []string{
"external.mail_connection", "external.mail_import", "external.mail_sync", "external.mail_sync_sweep",
"external.reauthorization",
"listener.poll", "listener.sweep", "maintenance.proactive_listener_sweep",
- "typedcard.connection_auth_reconcile", "typedcard.connection_auth_settle",
+ "typedcard.connection_auth_reconcile", "typedcard.connection_auth_settle", "typedcard.profile_setup_reminder",
}
var voiceRetentionTables = []string{
diff --git a/apps/teamhub/internal/externalsource/agent_grants.go b/apps/teamhub/internal/externalsource/agent_grants.go
index b1babacd..fb91b83a 100644
--- a/apps/teamhub/internal/externalsource/agent_grants.go
+++ b/apps/teamhub/internal/externalsource/agent_grants.go
@@ -3,6 +3,7 @@ package externalsource
import (
"context"
"errors"
+ "time"
"github.com/jackc/pgx/v5"
"github.com/riverqueue/river"
@@ -164,11 +165,37 @@ func (s *Service) connectionActivatedTx(ctx context.Context, tx pgx.Tx, accountI
return err
}
}
+ if len(agents) > 0 {
+ if err := jobs.InsertTx(ctx, tx, ProfileSetupReminderArgs{ConnectionID: connectionID},
+ &river.InsertOpts{ScheduledAt: time.Now().Add(ProfileSetupReminderDelay)}); err != nil {
+ return err
+ }
+ }
}
}
return jobs.InsertTx(ctx, tx, ConnectionAuthorizationSettleArgs{ConnectionID: connectionID}, nil)
}
+// ProfileSetupReminderDelay is how long after a Connection's first activation
+// AnotherMe is reminded about an unfinished Profile setup. It leaves a Human
+// who connected from the setup card time to finish the cards themselves.
+const ProfileSetupReminderDelay = 10 * time.Minute
+
+// ProfileSetupReminderArgs reminds the AnotherMe granted a newly active
+// Connection to offer the Human's Profile while setup is unfinished. The
+// transaction that first activates the Connection queues it.
+type ProfileSetupReminderArgs struct {
+ ConnectionID string `json:"connection_id"`
+}
+
+// Kind names the reminder job.
+func (ProfileSetupReminderArgs) Kind() string { return "typedcard.profile_setup_reminder" }
+
+// InsertOpts keeps one unfinished reminder per Connection.
+func (ProfileSetupReminderArgs) InsertOpts() river.InsertOpts {
+ return river.InsertOpts{Queue: jobs.QueueDefault, MaxAttempts: 5, UniqueOpts: jobs.UniqueUnfinished}
+}
+
func (s *Service) setAgentConnectionAccessInTx(ctx context.Context, tx pgx.Tx, accountID, connectionID, agentActorID string, granted bool) (AgentConnectionAccess, error) {
// Serialize the initially absent grant as well as updates to an existing grant.
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, "connection-grant:"+connectionID+":"+agentActorID); err != nil {
diff --git a/apps/teamhub/internal/store/decision.sql.go b/apps/teamhub/internal/store/decision.sql.go
index a5fe8c9a..47eb1db0 100644
--- a/apps/teamhub/internal/store/decision.sql.go
+++ b/apps/teamhub/internal/store/decision.sql.go
@@ -378,6 +378,46 @@ func (q *Queries) ListDecisionsByMessages(ctx context.Context, messageIds []stri
return items, nil
}
+const listProfileSetupReminderCards = `-- name: ListProfileSetupReminderCards :many
+SELECT decision.id AS decision_id,decision.room_id
+FROM external_connection_agent_grants grant_row
+JOIN external_connections connection
+ ON connection.id=grant_row.connection_id AND connection.status='active'
+JOIN decisions decision
+ ON decision.requested_by_actor_id=grant_row.agent_actor_id AND decision.tenant_id=grant_row.tenant_id
+ AND decision.decider_actor_id=grant_row.represented_human_actor_id
+ AND decision.kind IN ('profile_setup_apps','profile_setup_sources') AND decision.status='pending'
+WHERE grant_row.connection_id=$1::text AND grant_row.status='active'
+ORDER BY decision.id
+`
+
+type ListProfileSetupReminderCardsRow struct {
+ DecisionID string `json:"decision_id"`
+ RoomID string `json:"room_id"`
+}
+
+// The open AnotherMe setup cards whose AnotherMe holds an active grant to the
+// active Connection for the card's Human: the setups a reminder may concern.
+func (q *Queries) ListProfileSetupReminderCards(ctx context.Context, connectionID string) ([]ListProfileSetupReminderCardsRow, error) {
+ rows, err := q.db.Query(ctx, listProfileSetupReminderCards, connectionID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListProfileSetupReminderCardsRow{}
+ for rows.Next() {
+ var i ListProfileSetupReminderCardsRow
+ if err := rows.Scan(&i.DecisionID, &i.RoomID); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const locateDecision = `-- name: LocateDecision :one
SELECT tenant_id,room_id FROM decisions WHERE id=$1
`
@@ -393,3 +433,90 @@ func (q *Queries) LocateDecision(ctx context.Context, id string) (LocateDecision
err := row.Scan(&i.TenantID, &i.RoomID)
return i, err
}
+
+const lockPendingProfileSetupCard = `-- name: LockPendingProfileSetupCard :one
+SELECT decision.message_id,decision.tenant_id,decision.decider_actor_id,decision.requested_by_actor_id
+FROM decisions decision
+WHERE decision.id=$1::text AND decision.status='pending'
+ AND decision.kind IN ('profile_setup_apps','profile_setup_sources')
+FOR UPDATE
+`
+
+type LockPendingProfileSetupCardRow struct {
+ MessageID string `json:"message_id"`
+ TenantID string `json:"tenant_id"`
+ DeciderActorID string `json:"decider_actor_id"`
+ RequestedByActorID string `json:"requested_by_actor_id"`
+}
+
+// Locks one AnotherMe setup card while it is still open, after the Room
+// membership lock, as a decision answer does.
+func (q *Queries) LockPendingProfileSetupCard(ctx context.Context, decisionID string) (LockPendingProfileSetupCardRow, error) {
+ row := q.db.QueryRow(ctx, lockPendingProfileSetupCard, decisionID)
+ var i LockPendingProfileSetupCardRow
+ err := row.Scan(
+ &i.MessageID,
+ &i.TenantID,
+ &i.DeciderActorID,
+ &i.RequestedByActorID,
+ )
+ return i, err
+}
+
+const personalProfileNotStarted = `-- name: PersonalProfileNotStarted :one
+SELECT (
+ NOT EXISTS(SELECT 1 FROM personal_profile_currents
+ WHERE tenant_id=$1::text AND owner_actor_id=$2::text)
+ AND NOT EXISTS(SELECT 1 FROM personal_profile_builds
+ WHERE tenant_id=$1::text AND owner_actor_id=$2::text
+ AND expires_at>clock_timestamp())
+ AND NOT EXISTS(SELECT 1 FROM personal_profile_generations
+ WHERE tenant_id=$1::text AND owner_actor_id=$2::text
+ AND status IN ('queued','running'))
+)::boolean
+`
+
+type PersonalProfileNotStartedParams struct {
+ TenantID string `json:"tenant_id"`
+ OwnerActorID string `json:"owner_actor_id"`
+}
+
+// Whether the Human has no Personal Profile and none is being written.
+func (q *Queries) PersonalProfileNotStarted(ctx context.Context, arg PersonalProfileNotStartedParams) (bool, error) {
+ row := q.db.QueryRow(ctx, personalProfileNotStarted, arg.TenantID, arg.OwnerActorID)
+ var column_1 bool
+ err := row.Scan(&column_1)
+ return column_1, err
+}
+
+const profileOfferedInRoom = `-- name: ProfileOfferedInRoom :one
+SELECT EXISTS(
+ SELECT 1 FROM messages message
+ JOIN decisions decision
+ ON decision.message_id=message.card_context_message_id AND decision.room_id=message.room_id
+ AND decision.kind IN ('profile_setup_apps','profile_setup_sources')
+ WHERE message.room_id=$1::text AND message.author_actor_id=$2::text
+ AND message.message_kind='agent_runtime'
+ AND EXISTS(SELECT 1 FROM external_connection_agent_grants grant_row
+ WHERE grant_row.agent_actor_id=$3::text AND grant_row.tenant_id=decision.tenant_id
+ AND grant_row.created_at<=message.created_at
+ AND (grant_row.revoked_at IS NULL OR grant_row.revoked_at>message.created_at))
+)::boolean
+`
+
+type ProfileOfferedInRoomParams struct {
+ RoomID string `json:"room_id"`
+ HumanActorID string `json:"human_actor_id"`
+ AgentActorID string `json:"agent_actor_id"`
+}
+
+// Whether a setup status AnotherMe read already offered the Profile: one
+// written while the Human had an app granted to AnotherMe. A status written
+// with no app granted only told AnotherMe to wait. Links and files arrive only
+// with the status that finishes setup, after which no card is left to check.
+func (q *Queries) ProfileOfferedInRoom(ctx context.Context, arg ProfileOfferedInRoomParams) (bool, error) {
+ row := q.db.QueryRow(ctx, profileOfferedInRoom, arg.RoomID, arg.HumanActorID, arg.AgentActorID)
+ var column_1 bool
+ err := row.Scan(&column_1)
+ return column_1, err
+}
diff --git a/apps/teamhub/internal/store/queries/decision.sql b/apps/teamhub/internal/store/queries/decision.sql
index 98d7c86d..34b130f7 100644
--- a/apps/teamhub/internal/store/queries/decision.sql
+++ b/apps/teamhub/internal/store/queries/decision.sql
@@ -98,6 +98,60 @@ WHERE requested_by_actor_id=sqlc.arg(agent_actor_id)::text AND status='pending'
ORDER BY created_at DESC,id DESC
LIMIT 1;
+-- name: ListProfileSetupReminderCards :many
+-- The open AnotherMe setup cards whose AnotherMe holds an active grant to the
+-- active Connection for the card's Human: the setups a reminder may concern.
+SELECT decision.id AS decision_id,decision.room_id
+FROM external_connection_agent_grants grant_row
+JOIN external_connections connection
+ ON connection.id=grant_row.connection_id AND connection.status='active'
+JOIN decisions decision
+ ON decision.requested_by_actor_id=grant_row.agent_actor_id AND decision.tenant_id=grant_row.tenant_id
+ AND decision.decider_actor_id=grant_row.represented_human_actor_id
+ AND decision.kind IN ('profile_setup_apps','profile_setup_sources') AND decision.status='pending'
+WHERE grant_row.connection_id=sqlc.arg(connection_id)::text AND grant_row.status='active'
+ORDER BY decision.id;
+
+-- name: LockPendingProfileSetupCard :one
+-- Locks one AnotherMe setup card while it is still open, after the Room
+-- membership lock, as a decision answer does.
+SELECT decision.message_id,decision.tenant_id,decision.decider_actor_id,decision.requested_by_actor_id
+FROM decisions decision
+WHERE decision.id=sqlc.arg(decision_id)::text AND decision.status='pending'
+ AND decision.kind IN ('profile_setup_apps','profile_setup_sources')
+FOR UPDATE;
+
+-- name: ProfileOfferedInRoom :one
+-- Whether a setup status AnotherMe read already offered the Profile: one
+-- written while the Human had an app granted to AnotherMe. A status written
+-- with no app granted only told AnotherMe to wait. Links and files arrive only
+-- with the status that finishes setup, after which no card is left to check.
+SELECT EXISTS(
+ SELECT 1 FROM messages message
+ JOIN decisions decision
+ ON decision.message_id=message.card_context_message_id AND decision.room_id=message.room_id
+ AND decision.kind IN ('profile_setup_apps','profile_setup_sources')
+ WHERE message.room_id=sqlc.arg(room_id)::text AND message.author_actor_id=sqlc.arg(human_actor_id)::text
+ AND message.message_kind='agent_runtime'
+ AND EXISTS(SELECT 1 FROM external_connection_agent_grants grant_row
+ WHERE grant_row.agent_actor_id=sqlc.arg(agent_actor_id)::text AND grant_row.tenant_id=decision.tenant_id
+ AND grant_row.created_at<=message.created_at
+ AND (grant_row.revoked_at IS NULL OR grant_row.revoked_at>message.created_at))
+)::boolean;
+
+-- name: PersonalProfileNotStarted :one
+-- Whether the Human has no Personal Profile and none is being written.
+SELECT (
+ NOT EXISTS(SELECT 1 FROM personal_profile_currents
+ WHERE tenant_id=sqlc.arg(tenant_id)::text AND owner_actor_id=sqlc.arg(owner_actor_id)::text)
+ AND NOT EXISTS(SELECT 1 FROM personal_profile_builds
+ WHERE tenant_id=sqlc.arg(tenant_id)::text AND owner_actor_id=sqlc.arg(owner_actor_id)::text
+ AND expires_at>clock_timestamp())
+ AND NOT EXISTS(SELECT 1 FROM personal_profile_generations
+ WHERE tenant_id=sqlc.arg(tenant_id)::text AND owner_actor_id=sqlc.arg(owner_actor_id)::text
+ AND status IN ('queued','running'))
+)::boolean;
+
-- name: HumanWroteInRoom :one
-- Whether the Human has written in the Room themselves: published
-- conversation Messages that are not a card's recorded result.
diff --git a/apps/teamhub/internal/typedcard/profile_setup.go b/apps/teamhub/internal/typedcard/profile_setup.go
index 04efa5a5..244000a4 100644
--- a/apps/teamhub/internal/typedcard/profile_setup.go
+++ b/apps/teamhub/internal/typedcard/profile_setup.go
@@ -7,10 +7,12 @@ import (
"fmt"
"net/url"
"strings"
+ "time"
"github.com/jackc/pgx/v5"
idgen "github.com/simplexai-labs/linger/apps/teamhub/internal/ids"
"github.com/simplexai-labs/linger/apps/teamhub/internal/messagecreation"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/reminder"
"github.com/simplexai-labs/linger/apps/teamhub/internal/store"
)
@@ -92,7 +94,8 @@ func (s *Service) SetOnboarding(writer OnboardingHandoffWriter, connections Onbo
// OnboardingProgressTx writes the hidden status that goes ahead of the
// Human's first own Message in AnotherMe's Direct Room while a setup card is
// still open, so AnotherMe answers the Message knowing what setup has
-// collected. It reports false, writing nothing, in every other case. The
+// collected. It reports false, writing nothing, in every other case, and once
+// a status in the Room has offered the Profile. The
// caller publishes it before the Human's Message, in that Message's
// transaction.
func (s *Service) OnboardingProgressTx(ctx context.Context, tx pgx.Tx, queries *store.Queries, room store.Room, human store.Actor) (messagecreation.Persisted, bool, error) {
@@ -112,6 +115,12 @@ func (s *Service) OnboardingProgressTx(ctx context.Context, tx pgx.Tx, queries *
if err != nil {
return messagecreation.Persisted{}, false, err
}
+ // After a status that offered the Profile, such as the idle reminder, the
+ // Human's first Message is often the reply to it.
+ offered, err := queries.ProfileOfferedInRoom(ctx, store.ProfileOfferedInRoomParams{RoomID: room.ID, HumanActorID: human.ID, AgentActorID: room.DirectAgentActorID.String})
+ if err != nil || offered {
+ return messagecreation.Persisted{}, false, err
+ }
agent, err := queries.GetActor(ctx, store.GetActorParams{ID: room.DirectAgentActorID.String, TenantID: room.TenantID})
if err != nil {
return messagecreation.Persisted{}, false, err
@@ -144,6 +153,12 @@ type onboardingStatus struct {
files int
// chatted reports that the Human has written in the chat themselves.
chatted bool
+ // alreadyAsked reports that an earlier status offered the Profile, so the
+ // Human is not asked about the Profile again.
+ alreadyAsked bool
+ // idleReminder reports the reminder TeamHub writes once the Room is quiet
+ // while setup is unfinished; no Message of the Human's comes with it.
+ idleReminder bool
}
// onboardingStatusText is the hidden status AnotherMe reads: the facts, then
@@ -189,8 +204,12 @@ func onboardingStatusText(status onboardingStatus) string {
lines = append(lines, "Answer the Human's message first. Then mention once that they can still connect an app or share links and files in the setup cards above. Do not open the personal-profile Skill until they share something.")
case !shared:
lines = append(lines, "The Human shared nothing. Do not open the personal-profile Skill or bring up setup again. Say briefly that you will get to know them as you talk and that they can connect apps anytime, then talk normally.")
+ case status.idleReminder:
+ lines = append(lines, "The Human connected these apps but has not finished setup, and has no Profile yet; no message of theirs comes with this status. Tell them once that building their profile takes a while, and ask whether to start now from what is connected. Start it with the personal-profile Skill only if they agree. Mention that they can still share links and files in the setup card.")
case !status.finished:
lines = append(lines, "Answer the Human's message first. Then tell them once that building their profile takes a while, and ask whether to start now from what is connected so far. Start it with the personal-profile Skill only if they agree; otherwise wait until they finish the setup cards.")
+ case status.alreadyAsked:
+ lines = append(lines, "You already brought up their profile; do not ask the Human about it again. If their profile is started or done, add these sources to it with the personal-profile Skill; otherwise only acknowledge them briefly.")
case status.chatted:
lines = append(lines, "Building their profile takes a while, so ask the Human once whether to start now from these sources, and start it with the personal-profile Skill only after they agree. If their profile is already started or done, only offer to add the sources it does not cover yet.")
default:
@@ -327,9 +346,9 @@ func (s *Service) profileSetupOutcome(
return nil, err
}
if authority.Kind == DecisionKindProfileSetupSources {
- handoff, err := s.onboardingFinished(ctx, tx, queries, authority, answer, accountID, decisionID, human, agent)
- if err != nil {
- return nil, err
+ handoff, found, err := s.onboardingFinished(ctx, tx, queries, authority, answer, accountID, decisionID, human, agent)
+ if err != nil || !found {
+ return []messagecreation.Persisted{result}, err
}
return []messagecreation.Persisted{result, handoff}, nil
}
@@ -361,27 +380,125 @@ func (s *Service) onboardingFinished(
answer decisionAnswer,
accountID, decisionID string,
human, agent store.Actor,
-) (messagecreation.Persisted, error) {
+) (messagecreation.Persisted, bool, error) {
if s.onboardingHandoff == nil {
- return messagecreation.Persisted{}, errors.New("onboarding handoff writer is not configured")
+ return messagecreation.Persisted{}, false, errors.New("onboarding handoff writer is not configured")
+ }
+ // The Human is offered the Profile once: after a status that offered it,
+ // a sources card that shares nothing writes none, and new links or files
+ // are handed over without offering it again. A status that only said to
+ // wait for a source does not count.
+ offered, err := queries.ProfileOfferedInRoom(ctx, store.ProfileOfferedInRoomParams{RoomID: authority.RoomID, HumanActorID: human.ID, AgentActorID: agent.ID})
+ if err != nil || offered && len(answer.Links) == 0 && len(answer.AttachmentUploadIDs) == 0 {
+ return messagecreation.Persisted{}, false, err
}
connections, err := s.grantedConnections(ctx, tx, agent)
if err != nil {
- return messagecreation.Persisted{}, err
+ return messagecreation.Persisted{}, false, err
}
chatted, err := queries.HumanWroteInRoom(ctx, store.HumanWroteInRoomParams{RoomID: authority.RoomID, HumanActorID: human.ID})
if err != nil {
- return messagecreation.Persisted{}, err
+ return messagecreation.Persisted{}, false, err
}
text := onboardingStatusText(onboardingStatus{
finished: true, connections: connections, links: answer.Links,
- files: len(answer.AttachmentUploadIDs), chatted: chatted,
+ files: len(answer.AttachmentUploadIDs), chatted: chatted, alreadyAsked: offered,
})
- return s.onboardingHandoff(ctx, tx, queries, OnboardingHandoff{
+ handoff, err := s.onboardingHandoff(ctx, tx, queries, OnboardingHandoff{
TenantID: authority.TenantID, RoomID: authority.RoomID, AccountID: accountID,
Human: human, Agent: agent, CardMessageID: authority.MessageID,
IdempotencyKey: decisionID, Text: text, AttachmentUploadIDs: answer.AttachmentUploadIDs,
})
+ return handoff, err == nil, err
+}
+
+// RemindProfileSetup wakes the AnotherMe of each unfinished setup that a newly
+// active Connection serves, so a Human who connected an app but never reached
+// the cards' status, for example by starting by voice, is still offered a
+// Profile. Each setup is reminded once, when the Room has been quiet for
+// reminder.Window, and only while the Human has no Profile and no status has
+// offered one. It returns how long until a Room still in
+// conversation is quiet; the caller tries again then.
+func (s *Service) RemindProfileSetup(ctx context.Context, connectionID string, now time.Time) (time.Duration, error) {
+ cards, err := store.New(s.pool).ListProfileSetupReminderCards(ctx, connectionID)
+ if err != nil {
+ return 0, err
+ }
+ var wait time.Duration
+ for _, card := range cards {
+ next, err := s.remindProfileSetup(ctx, card, now)
+ if err != nil {
+ return 0, err
+ }
+ if next > 0 && (wait == 0 || next < wait) {
+ wait = next
+ }
+ }
+ return wait, nil
+}
+
+func (s *Service) remindProfileSetup(ctx context.Context, card store.ListProfileSetupReminderCardsRow, now time.Time) (time.Duration, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback(ctx)
+ queries := store.New(tx)
+ // The same lock order as a decision answer, so the Human's answer and the
+ // reminder never cross.
+ if err := queries.AcquireAdvisoryTransactionLock(ctx, "room-membership|"+card.RoomID); err != nil {
+ return 0, err
+ }
+ locked, err := queries.LockPendingProfileSetupCard(ctx, card.DecisionID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return 0, nil
+ }
+ if err != nil {
+ return 0, err
+ }
+ // The Human's Message path writes its status under the Room's delivery
+ // lock, so the checks below run after it and see that status and the
+ // Message itself.
+ if err := queries.LockTenantDeliveryRooms(ctx, store.LockTenantDeliveryRoomsParams{TenantID: locked.TenantID, RoomIds: []string{card.RoomID}}); err != nil {
+ return 0, err
+ }
+ offered, err := queries.ProfileOfferedInRoom(ctx, store.ProfileOfferedInRoomParams{RoomID: card.RoomID, HumanActorID: locked.DeciderActorID, AgentActorID: locked.RequestedByActorID})
+ if err != nil || offered {
+ return 0, err
+ }
+ notStarted, err := queries.PersonalProfileNotStarted(ctx, store.PersonalProfileNotStartedParams{TenantID: locked.TenantID, OwnerActorID: locked.DeciderActorID})
+ if err != nil || !notStarted {
+ return 0, err
+ }
+ last, err := queries.GetRoomLastConversationAt(ctx, card.RoomID)
+ if err != nil {
+ return 0, err
+ }
+ if wait := reminder.Wait(last, now, reminder.Window); wait > 0 {
+ return wait, nil
+ }
+ human, err := queries.GetActor(ctx, store.GetActorParams{ID: locked.DeciderActorID, TenantID: locked.TenantID})
+ if err != nil {
+ return 0, err
+ }
+ agent, err := queries.GetActor(ctx, store.GetActorParams{ID: locked.RequestedByActorID, TenantID: locked.TenantID})
+ if err != nil {
+ return 0, err
+ }
+ connections, err := s.grantedConnections(ctx, tx, agent)
+ if err != nil || len(connections) == 0 {
+ return 0, err
+ }
+ status, err := messagecreation.CardHandoff(ctx, queries, messagecreation.Draft{
+ TenantID: locked.TenantID, RoomID: card.RoomID, Author: human, CardContextMessageID: locked.MessageID,
+ }, agent, " "+onboardingStatusText(onboardingStatus{connections: connections, idleReminder: true}))
+ if err != nil {
+ return 0, err
+ }
+ if _, err := messagecreation.Publish(ctx, queries, status); err != nil {
+ return 0, err
+ }
+ return 0, tx.Commit(ctx)
}
// normalizeProfileSourcesAnswer takes the links and uploads a sources card
diff --git a/apps/teamhub/internal/typedcard/profile_setup_test.go b/apps/teamhub/internal/typedcard/profile_setup_test.go
index a223d4b3..e483fec0 100644
--- a/apps/teamhub/internal/typedcard/profile_setup_test.go
+++ b/apps/teamhub/internal/typedcard/profile_setup_test.go
@@ -20,6 +20,14 @@ func TestOnboardingStatusTextTellsAnotherMeWhatSetupCollected(t *testing.T) {
onboardingStatus{connections: gmail},
[]string{"- Gmail [email protected], connection connection_gmail", "ask whether to start now from what is connected so far"},
},
+ "finished with sources after asking": {
+ onboardingStatus{finished: true, links: []string{"https://ada.example"}, chatted: true, alreadyAsked: true},
+ []string{"Links: https://ada.example", "do not ask the Human about it again", "add these sources to it"},
+ },
+ "idle reminder": {
+ onboardingStatus{connections: gmail, idleReminder: true},
+ []string{"Setup cards: not finished", "- Gmail [email protected], connection connection_gmail", "no message of theirs comes with this status", "ask whether to start now from what is connected"},
+ },
"finished, nothing shared": {
onboardingStatus{finished: true, chatted: true},
[]string{"Setup cards: finished.", "Links: none.", "Files: none.", "The Human shared nothing. Do not open the personal-profile Skill"},
diff --git a/apps/teamhub/tests/integration/another_me_profile_setup_sync_test.go b/apps/teamhub/tests/integration/another_me_profile_setup_sync_test.go
new file mode 100644
index 00000000..ab383a44
--- /dev/null
+++ b/apps/teamhub/tests/integration/another_me_profile_setup_sync_test.go
@@ -0,0 +1,157 @@
+package integration_test
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/riverqueue/river"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/externalsource"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/jobs"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/typedcard"
+)
+
+// runProfileReminder runs the Profile setup reminder for the fixture's Gmail
+// now and waits until its attempt has finished or snoozed.
+func (f profileSetupFixture) runProfileReminder(t *testing.T) {
+ t.Helper()
+ tx, err := f.pool.Begin(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(t.Context())
+ if err := jobs.InsertTx(t.Context(), tx, externalsource.ProfileSetupReminderArgs{ConnectionID: "connection_onboarding_gmail"},
+ &river.InsertOpts{ScheduledAt: time.Now()}); err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Commit(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ deadline := time.Now().Add(15 * time.Second)
+ for countRows(t, f.env, `SELECT count(*) FROM river_job WHERE kind='typedcard.profile_setup_reminder'
+ AND state IN ('available','running') OR kind='typedcard.profile_setup_reminder' AND attempted_at IS NULL`) > 0 {
+ if time.Now().After(deadline) {
+ t.Fatal("Profile setup reminder did not run")
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+// quiet makes the Room look silent for longer than the quiet window. The
+// grants move back with the Messages, so what was granted when each status
+// was written stays the same.
+func (f profileSetupFixture) quiet(t *testing.T) {
+ t.Helper()
+ if _, err := f.pool.Exec(t.Context(), `UPDATE messages SET created_at=created_at-interval '10 minutes' WHERE room_id=$1`, f.roomID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.pool.Exec(t.Context(), `UPDATE external_connection_agent_grants SET created_at=created_at-interval '10 minutes' WHERE agent_actor_id=$1`, f.agentID); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func (f profileSetupFixture) statuses(t *testing.T) int {
+ t.Helper()
+ return countRows(t, f.env, `SELECT count(*) FROM messages WHERE room_id=$1 AND message_kind='agent_runtime'`, f.roomID)
+}
+
+// A Human who connected an app without finishing setup, for example in
+// Settings and then by voice, is reminded once the Room is quiet: AnotherMe
+// is woken once to offer the Profile, and the Human's reply carries no second
+// status. The setup card itself is left as it is.
+func TestAnotherMeProfileSetupReminderWakesAnotherMeOnceWhenQuiet(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ // Connected Apps list a grant only while Composio is configured.
+ f := newProfileSetupFixture(t, newFakeComposio(t).configure)
+ _, appsMessageID, _ := f.card(t, typedcard.DecisionKindProfileSetupApps)
+ f.grantGmail(t)
+ f.quiet(t)
+ f.runProfileReminder(t)
+
+ status := f.onboardingStatus(t, appsMessageID)
+ for _, want := range []string{"Setup cards: not finished", "- Gmail [email protected], connection connection_onboarding_gmail",
+ "no message of theirs comes with this status", "ask whether to start now from what is connected"} {
+ if !strings.Contains(status.body, want) {
+ t.Fatalf("reminder lacks %q: %s", want, status.body)
+ }
+ }
+ if got := f.disposition(t, status.id); got != "notify" {
+ t.Fatalf("reminder disposition=%s want notify", got)
+ }
+ if got := countRows(t, f.env, `SELECT count(*) FROM decisions WHERE room_id=$1 AND kind='profile_setup_apps' AND status='pending'`, f.roomID); got != 1 {
+ t.Fatalf("pending apps cards=%d want 1", got)
+ }
+
+ f.runProfileReminder(t)
+ reply := f.say(t, "yes, go ahead", "reminder-reply")
+ if got := f.statuses(t); got != 1 {
+ t.Fatalf("statuses=%d want 1", got)
+ }
+ if got := f.disposition(t, reply); got != "notify" {
+ t.Fatalf("reply disposition=%s want notify", got)
+ }
+}
+
+// While the Room is in conversation the reminder waits, writing nothing.
+func TestAnotherMeProfileSetupReminderWaitsForAQuietRoom(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ f := newProfileSetupFixture(t, newFakeComposio(t).configure)
+ f.grantGmail(t)
+ f.runProfileReminder(t)
+ if got := f.statuses(t); got != 0 {
+ t.Fatalf("statuses=%d want 0", got)
+ }
+ if got := countRows(t, f.env, `SELECT count(*) FROM river_job WHERE kind='typedcard.profile_setup_reminder' AND state='scheduled' AND scheduled_at>now()`); got != 1 {
+ t.Fatalf("snoozed reminders=%d want 1", got)
+ }
+}
+
+// A first status written while nothing was connected only told AnotherMe to
+// wait, so an app connected afterwards is still reminded about.
+func TestAnotherMeProfileSetupReminderFollowsAWaitingStatus(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ f := newProfileSetupFixture(t, newFakeComposio(t).configure)
+ f.say(t, "hello", "reminder-waiting")
+ f.grantGmail(t)
+ f.quiet(t)
+ f.runProfileReminder(t)
+ if got := f.statuses(t); got != 2 {
+ t.Fatalf("statuses=%d want the waiting status and the reminder", got)
+ }
+ if got := countRows(t, f.env, `SELECT count(*) FROM messages WHERE room_id=$1 AND message_kind='agent_runtime' AND body LIKE '%has not finished setup%'`, f.roomID); got != 1 {
+ t.Fatalf("reminders=%d want 1", got)
+ }
+}
+
+// No reminder once a Profile is being written, once a status has offered the
+// Profile, or once setup is finished.
+func TestAnotherMeProfileSetupReminderSkipsAHandledSetup(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ for name, prepare := range map[string]func(*testing.T, profileSetupFixture){
+ "profile being written": func(t *testing.T, f profileSetupFixture) {
+ if _, err := f.pool.Exec(t.Context(), `INSERT INTO personal_profile_builds(tenant_id,owner_actor_id,expires_at) VALUES($1,'actor_acme_alice',now()+interval '30 minutes')`, acmeTenant); err != nil {
+ t.Fatal(err)
+ }
+ },
+ "profile already offered": func(t *testing.T, f profileSetupFixture) { f.say(t, "hello", "reminder-hello") },
+ "setup finished": func(t *testing.T, f profileSetupFixture) {
+ f.decideApps(t, "skipped")
+ decisionID, _, version := f.card(t, typedcard.DecisionKindProfileSetupSources)
+ if status, body := f.decide(f.human, decisionID, version, map[string]any{"decision": "skipped"}, "reminder-finished"); status != 200 {
+ t.Fatalf("sources decision status=%d body=%s", status, body)
+ }
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newProfileSetupFixture(t, newFakeComposio(t).configure)
+ f.grantGmail(t)
+ prepare(t, f)
+ before := f.statuses(t)
+ f.quiet(t)
+ f.runProfileReminder(t)
+ if got := f.statuses(t); got != before {
+ t.Fatalf("statuses before=%d after=%d", before, got)
+ }
+ })
+ }
+}
diff --git a/apps/teamhub/tests/integration/another_me_profile_setup_test.go b/apps/teamhub/tests/integration/another_me_profile_setup_test.go
index 8191666a..7bb27c0b 100644
--- a/apps/teamhub/tests/integration/another_me_profile_setup_test.go
+++ b/apps/teamhub/tests/integration/another_me_profile_setup_test.go
@@ -442,8 +442,8 @@ func TestAnotherMeProfileSetupFinishedWithoutSourcesTellsAnotherMeToChat(t *test
}
// The Human's first own Message while setup is open carries the status just
-// ahead of it, once; later Messages do not. Finishing setup afterwards asks
-// before starting, since the Human is mid-conversation.
+// ahead of it, once; later Messages do not. Finishing setup with a new link
+// afterwards hands it over without asking about the Profile again.
func TestAnotherMeOnboardingStatusPrecedesTheHumansFirstMessage(t *testing.T) {
allowParallelIntegrationTest(t)
// Connected Apps list a grant only while Composio is configured.
@@ -476,15 +476,34 @@ func TestAnotherMeOnboardingStatusPrecedesTheHumansFirstMessage(t *testing.T) {
f.decideApps(t, "connected")
decisionID, sourcesMessageID, version := f.card(t, typedcard.DecisionKindProfileSetupSources)
- if status, body := f.decide(f.human, decisionID, version, map[string]any{"decision": "skipped"}, "onboarding-sources"); status != http.StatusOK {
+ // The link is handed over; the Profile is not offered a second time.
+ if status, body := f.decide(f.human, decisionID, version, map[string]any{"decision": "done", "links": []string{"https://alice.example"}}, "onboarding-sources"); status != http.StatusOK {
t.Fatalf("sources decision status=%d body=%s", status, body)
}
finished := f.onboardingStatus(t, sourcesMessageID)
- if !strings.Contains(finished.body, "Setup cards: finished.") || !strings.Contains(finished.body, "ask the Human once whether to start now") {
+ if !strings.Contains(finished.body, "Setup cards: finished.") || !strings.Contains(finished.body, "Links: https://alice.example") ||
+ !strings.Contains(finished.body, "do not ask the Human about it again") {
t.Fatalf("finished status=%s", finished.body)
}
}
+// After AnotherMe has read a status, a sources card that shares nothing adds
+// none.
+func TestAnotherMeEmptySourcesCardAddsNoSecondStatus(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ f := newProfileSetupFixture(t, newFakeComposio(t).configure)
+ f.grantGmail(t)
+ f.say(t, "hello", "empty-sources-first")
+ f.decideApps(t, "connected")
+ decisionID, _, version := f.card(t, typedcard.DecisionKindProfileSetupSources)
+ if status, body := f.decide(f.human, decisionID, version, map[string]any{"decision": "skipped"}, "empty-sources"); status != http.StatusOK {
+ t.Fatalf("sources decision status=%d body=%s", status, body)
+ }
+ if got := countRows(t, f.env, `SELECT count(*) FROM messages WHERE room_id=$1 AND message_kind='agent_runtime'`, f.roomID); got != 1 {
+ t.Fatalf("statuses=%d want 1", got)
+ }
+}
+
// Once setup is finished, the Human's Messages carry no status.
func TestAnotherMeOnboardingStatusOnlyWhileSetupIsOpen(t *testing.T) {
allowParallelIntegrationTest(t)
@@ -563,3 +582,53 @@ func TestAnotherMeDecisionResultsWakeOnlyThroughHandoff(t *testing.T) {
t.Fatalf("ordinary Message disposition=%s want notify", got)
}
}
+
+// A first status written while nothing was shared only tells AnotherMe to
+// wait, so connecting in the card and finishing setup still offers the
+// Profile, whether or not the sources card shares more.
+func TestAnotherMeSetupOffersTheProfileAfterAWaitingStatus(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ for name, answer := range map[string]map[string]any{
+ "skipped": {"decision": "skipped"},
+ "with link": {"decision": "done", "links": []string{"https://alice.example"}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newProfileSetupFixture(t, newFakeComposio(t).configure)
+ _, appsMessageID, _ := f.card(t, typedcard.DecisionKindProfileSetupApps)
+ f.say(t, "hello", "waiting-first")
+ if waiting := f.onboardingStatus(t, appsMessageID); !strings.Contains(waiting.body, "Do not open the personal-profile Skill until they share something") {
+ t.Fatalf("first status=%s", waiting.body)
+ }
+ f.grantGmail(t)
+ f.decideApps(t, "connected")
+ decisionID, sourcesMessageID, version := f.card(t, typedcard.DecisionKindProfileSetupSources)
+ if status, body := f.decide(f.human, decisionID, version, answer, "waiting-sources"); status != http.StatusOK {
+ t.Fatalf("sources decision status=%d body=%s", status, body)
+ }
+ finished := f.onboardingStatus(t, sourcesMessageID)
+ if !strings.Contains(finished.body, "- Gmail [email protected]") || !strings.Contains(finished.body, "ask the Human once whether to start now") {
+ t.Fatalf("finished status=%s", finished.body)
+ }
+ })
+ }
+}
+
+// A waiting status written on the sources card does not count as an offer
+// once that card shares a link: finishing setup still offers the Profile.
+func TestAnotherMeSourcesCardOffersTheProfileAfterAWaitingStatus(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ f := newProfileSetupFixture(t)
+ f.decideApps(t, "skipped")
+ decisionID, sourcesMessageID, version := f.card(t, typedcard.DecisionKindProfileSetupSources)
+ f.say(t, "hello", "sources-waiting-first")
+ if status, body := f.decide(f.human, decisionID, version, map[string]any{"decision": "done", "links": []string{"https://alice.example"}}, "sources-waiting-link"); status != http.StatusOK {
+ t.Fatalf("sources decision status=%d body=%s", status, body)
+ }
+ var finished string
+ if err := f.pool.QueryRow(t.Context(), `SELECT body FROM messages WHERE room_id=$1 AND message_kind='agent_runtime' AND card_context_message_id=$2 ORDER BY created_at DESC,id DESC LIMIT 1`, f.roomID, sourcesMessageID).Scan(&finished); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(finished, "Setup cards: finished.") || !strings.Contains(finished, "ask the Human once whether to start now") {
+ t.Fatalf("finished status=%s", finished)
+ }
+}
diff --git a/apps/teamhub/tests/integration/connected_apps_agent_grants_test.go b/apps/teamhub/tests/integration/connected_apps_agent_grants_test.go
index fd66487c..f8db219b 100644
--- a/apps/teamhub/tests/integration/connected_apps_agent_grants_test.go
+++ b/apps/teamhub/tests/integration/connected_apps_agent_grants_test.go
@@ -146,6 +146,11 @@ func TestConnectedAppsAgentGrantIsExplicitAccountScopedAndRevokedOnDisconnect(t
if got := countRows(t, env, `SELECT count(*) FROM river_job WHERE kind='typedcard.connection_auth_settle' AND args->>'connection_id'=$1`, pendingConnectionID); got != 1 {
t.Fatalf("activation queued %d card settlements", got)
}
+ // The first activation also queues one Profile setup reminder, due after
+ // the Human has had time to finish the setup cards.
+ if got := countRows(t, env, `SELECT count(*) FROM river_job WHERE kind='typedcard.profile_setup_reminder' AND args->>'connection_id'=$1 AND scheduled_at>now()+interval '9 minutes'`, pendingConnectionID); got != 1 {
+ t.Fatalf("activation queued %d Profile setup reminders", got)
+ }
if status, _, body = env.request(
alice,
http.MethodPut,