@fabriktor/fx 0.0.186 → 0.0.188

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -109,6 +109,9 @@ export type GlobalChatRoomsSession = {
109
109
  export interface ChatFXOperator {
110
110
  newSendQueue(opts: Omit<ChatSendQueueOptions, "chat">): ChatSendQueue;
111
111
  createChat(opts: CreateChatOptions): Promise<Chat>;
112
+ chatMessage(opts: Pick<Chat, "id" | "chat_room_id"> & {
113
+ signal?: AbortSignal;
114
+ }): Promise<Chat>;
112
115
  ensureChatRoom(opts: EnsureChatRoomOptions): Promise<string>;
113
116
  markChatObjectsUploaded(opts: MarkChatObjectsUploadedOptions): Promise<Chat>;
114
117
  clearChatObjects(opts: ClearChatObjectsOptions): Promise<Chat>;
@@ -130,6 +133,9 @@ export declare class ChatFX implements ChatFXOperator {
130
133
  private users;
131
134
  constructor(opts: ChatFXOptions);
132
135
  newSendQueue(opts: Omit<ChatSendQueueOptions, "chat">): ChatSendQueue;
136
+ chatMessage(opts: Pick<Chat, "id" | "chat_room_id"> & {
137
+ signal?: AbortSignal;
138
+ }): Promise<Chat>;
133
139
  createChat(opts: CreateChatOptions): Promise<Chat>;
134
140
  ensureChatRoom(opts: EnsureChatRoomOptions): Promise<string>;
135
141
  markChatObjectsUploaded(opts: MarkChatObjectsUploadedOptions): Promise<Chat>;
@@ -37,8 +37,24 @@ export class ChatFX {
37
37
  newSendQueue(opts) {
38
38
  return new ChatSendQueue({ ...opts, chat: this.chat });
39
39
  }
40
+ async chatMessage(opts) {
41
+ const out = await this.chat.queryChats({
42
+ query: queryParams({
43
+ id: opts.id,
44
+ chat_room_id: opts.chat_room_id,
45
+ }),
46
+ signal: opts.signal,
47
+ });
48
+ const chat = out.value?.find((entry) => entry.id === opts.id && entry.chat_room_id === opts.chat_room_id);
49
+ if (!chat)
50
+ throw errResolveFailed({ resource: resourceChat, msg: msgChatMissing });
51
+ return chat;
52
+ }
40
53
  async createChat(opts) {
41
- const out = await this.chat.insertOneChat(opts);
54
+ const out = await this.chat.insertOneChat({
55
+ ...opts,
56
+ in: { ...opts.in, is_talkie: opts.in.is_talkie ?? false },
57
+ });
42
58
  const id = requiredOperationID(out, msgCreatedChatIDMissing);
43
59
  return await this.findChat(id);
44
60
  }
@@ -4,6 +4,7 @@ export declare function newChatInput(opts: {
4
4
  text: string;
5
5
  quoted_message_id?: string;
6
6
  has_objects?: boolean;
7
+ is_talkie?: boolean;
7
8
  }): InChat;
8
9
  export declare function newOptimisticChat(opts: {
9
10
  owner_id: string;
@@ -9,6 +9,7 @@ export function newChatInput(opts) {
9
9
  mentions: [],
10
10
  has_objects: opts.has_objects ?? false,
11
11
  objects_uploaded: false,
12
+ is_talkie: opts.is_talkie ?? false,
12
13
  };
13
14
  }
14
15
  export function newOptimisticChat(opts) {
@@ -30,7 +31,8 @@ export function matchesOptimisticChat(chat, optimistic) {
30
31
  chat.chat_room_id === optimistic.chat_room_id &&
31
32
  chat.text === optimistic.text &&
32
33
  chat.quoted_message_id === optimistic.quoted_message_id &&
33
- chat.has_objects === optimistic.has_objects);
34
+ chat.has_objects === optimistic.has_objects &&
35
+ !!chat.is_talkie === !!optimistic.is_talkie);
34
36
  }
35
37
  /** Reconcile only the local outgoing bubbles. Server timestamps/IDs stay authoritative. */
36
38
  export function projectQueuedChats(chats, snapshot, ownerID, roomID) {
@@ -369,7 +369,10 @@ export class ChatSendQueue {
369
369
  requestSignal.throwIfAborted();
370
370
  requestStarted = true;
371
371
  const out = await this.opts.chat.insertOneChat({
372
- in: current.input,
372
+ in: {
373
+ ...current.input,
374
+ is_talkie: current.input.is_talkie ?? false,
375
+ },
373
376
  signal: requestSignal,
374
377
  idempotency_key: current.id,
375
378
  });
@@ -536,7 +539,8 @@ export class ChatSendQueue {
536
539
  }
537
540
  const stored = (await this.opts.store.list(owner)).find((value) => value.id === entry.id);
538
541
  if (!stored?.chat ||
539
- (stored.status !== ChatSendStatus.Queued && !chatSendNeedsRetry(stored))) {
542
+ (stored.status !== ChatSendStatus.Queued &&
543
+ !chatSendNeedsRetry(stored))) {
540
544
  return;
541
545
  }
542
546
  try {
@@ -0,0 +1,59 @@
1
+ import { type Notification } from "@fabriktor/schema";
2
+ import type { ChatFXOperator } from "./chat.js";
3
+ import type { ChatSendQueue } from "./send-queue.js";
4
+ import type { StorageFXOperator } from "../storage/storage.js";
5
+ export type Talkie = {
6
+ notification_id: string;
7
+ chat_id: string;
8
+ chat_room_id: string;
9
+ sender_id: string;
10
+ sender_name: string;
11
+ };
12
+ export type TalkieReply = Talkie & {
13
+ owner_id: string;
14
+ label: string;
15
+ members: number;
16
+ };
17
+ export declare function notificationTalkie(item: Notification): Talkie | undefined;
18
+ export type TalkiePlayer = {
19
+ load: (url: string) => void;
20
+ play: () => Promise<void>;
21
+ pause: () => void;
22
+ reset: () => void;
23
+ };
24
+ export type TalkieState = {
25
+ playing_id: string;
26
+ loading_id: string;
27
+ selecting_id: string;
28
+ reply?: TalkieReply;
29
+ };
30
+ export type TalkieSessionOptions = {
31
+ chat: Pick<ChatFXOperator, "chatMessage" | "chatRooms" | "chatRoomParticipants">;
32
+ storage: Pick<StorageFXOperator, "downloadObjects">;
33
+ queue: Pick<ChatSendQueue, "enqueue">;
34
+ player: TalkiePlayer;
35
+ mark_read: (id: string) => void;
36
+ on_change: (state: TalkieState) => void;
37
+ };
38
+ export declare class TalkieSession {
39
+ private readonly opts;
40
+ private owner;
41
+ private identity;
42
+ private playback;
43
+ private selection;
44
+ private loaded;
45
+ private value;
46
+ constructor(opts: TalkieSessionOptions);
47
+ get state(): TalkieState;
48
+ setOwner(owner_id: string, identity: string): void;
49
+ play(item: Notification): Promise<void>;
50
+ select(item: Notification): Promise<void>;
51
+ reply(file: File, target: TalkieReply): string;
52
+ clearReply(): void;
53
+ stop(): void;
54
+ ended(): void;
55
+ failed(): void;
56
+ clear(): void;
57
+ private resolve;
58
+ private patch;
59
+ }
@@ -0,0 +1,205 @@
1
+ import { ColStorageChat, MimePrefixAudio, NotifKChatChatsTalkieReceived, NotifChatIDKey, NotifChatRoomIDKey, NotifSenderIDKey, NotifSenderNameKey, } from "@fabriktor/schema";
2
+ import { newChatInput } from "./optimistic.js";
3
+ import { notifyObserver } from "../core/events.js";
4
+ import { resolvedID } from "../core/id.js";
5
+ import { errResolveFailed } from "../core/err.js";
6
+ export function notificationTalkie(item) {
7
+ if (item.notif_k !== NotifKChatChatsTalkieReceived)
8
+ return;
9
+ const data = item.custom_data;
10
+ const chat_id = resolvedID(data[NotifChatIDKey]);
11
+ const chat_room_id = resolvedID(data[NotifChatRoomIDKey]);
12
+ const sender_id = resolvedID(data[NotifSenderIDKey]);
13
+ if (!chat_id || !chat_room_id || !sender_id)
14
+ return;
15
+ return {
16
+ notification_id: item.id,
17
+ chat_id,
18
+ chat_room_id,
19
+ sender_id,
20
+ sender_name: data[NotifSenderNameKey] ?? "",
21
+ };
22
+ }
23
+ // Notification history supplies the entries. Resolve media only on user intent.
24
+ export class TalkieSession {
25
+ opts;
26
+ owner = "";
27
+ identity = "";
28
+ playback = new AbortController();
29
+ selection = 0;
30
+ loaded = "";
31
+ value = {
32
+ playing_id: "",
33
+ loading_id: "",
34
+ selecting_id: "",
35
+ };
36
+ constructor(opts) {
37
+ this.opts = opts;
38
+ }
39
+ get state() {
40
+ return this.value;
41
+ }
42
+ setOwner(owner_id, identity) {
43
+ if (this.identity === identity && this.owner === owner_id)
44
+ return;
45
+ this.clear();
46
+ this.owner = owner_id;
47
+ this.identity = identity;
48
+ }
49
+ async play(item) {
50
+ const talkie = this.resolve(item);
51
+ if (this.value.playing_id === item.id ||
52
+ this.value.loading_id === item.id) {
53
+ this.stop();
54
+ return;
55
+ }
56
+ this.stop();
57
+ const abort = this.playback;
58
+ this.patch({ loading_id: item.id });
59
+ try {
60
+ if (this.loaded !== item.id) {
61
+ const chat = await this.opts.chat.chatMessage({
62
+ id: talkie.chat_id,
63
+ chat_room_id: talkie.chat_room_id,
64
+ signal: abort.signal,
65
+ });
66
+ if (abort.signal.aborted)
67
+ return;
68
+ if (!chat.is_talkie ||
69
+ !chat.has_objects ||
70
+ !chat.objects_uploaded ||
71
+ chat.chat_room_id !== talkie.chat_room_id)
72
+ throw unavailable();
73
+ const out = await this.opts.storage.downloadObjects({
74
+ col: ColStorageChat,
75
+ owner_id: talkie.chat_id,
76
+ mime_prefix: MimePrefixAudio,
77
+ signal: abort.signal,
78
+ });
79
+ if (abort.signal.aborted)
80
+ return;
81
+ const object = out.value?.find((entry) => entry.mime_prefix === MimePrefixAudio);
82
+ const url = object?.public_url || object?.signed_url;
83
+ if (!url)
84
+ throw unavailable();
85
+ this.opts.player.load(url);
86
+ this.loaded = item.id;
87
+ }
88
+ await this.opts.player.play();
89
+ if (abort.signal.aborted)
90
+ return;
91
+ this.patch({ playing_id: item.id });
92
+ if (!item.is_read)
93
+ notifyObserver(() => this.opts.mark_read(item.id));
94
+ }
95
+ catch (error) {
96
+ if (abort.signal.aborted)
97
+ return;
98
+ // Keep a prepared source for a second user gesture if autoplay was blocked.
99
+ if (!(error instanceof Error && error.name === "NotAllowedError"))
100
+ this.loaded = "";
101
+ throw error;
102
+ }
103
+ finally {
104
+ if (!abort.signal.aborted)
105
+ this.patch({ loading_id: "" });
106
+ }
107
+ }
108
+ async select(item) {
109
+ const talkie = this.resolve(item);
110
+ const request = ++this.selection;
111
+ const owner = this.owner;
112
+ this.patch({ selecting_id: item.id, reply: undefined });
113
+ try {
114
+ const [rooms, participants, chat] = await Promise.all([
115
+ this.opts.chat.chatRooms({ ids: [talkie.chat_room_id] }),
116
+ this.opts.chat.chatRoomParticipants({
117
+ chat_room_ids: [talkie.chat_room_id],
118
+ }),
119
+ this.opts.chat.chatMessage({
120
+ id: talkie.chat_id,
121
+ chat_room_id: talkie.chat_room_id,
122
+ }),
123
+ ]);
124
+ if (request !== this.selection)
125
+ return;
126
+ const room = rooms.find((entry) => entry.id === talkie.chat_room_id);
127
+ const members = participants[talkie.chat_room_id];
128
+ if (!chat.is_talkie ||
129
+ !chat.objects_uploaded ||
130
+ !room ||
131
+ !members?.members.some((entry) => entry.owner_id === owner))
132
+ throw unavailable();
133
+ const names = members.users
134
+ .filter((entry) => entry.id !== owner)
135
+ .map((entry) => entry.full_name || entry.username);
136
+ this.patch({
137
+ reply: {
138
+ ...talkie,
139
+ owner_id: owner,
140
+ label: room.name.trim() || names.join(", ") || talkie.sender_name,
141
+ members: members.members.length,
142
+ },
143
+ });
144
+ }
145
+ catch (error) {
146
+ if (request === this.selection)
147
+ throw error;
148
+ }
149
+ finally {
150
+ if (request === this.selection)
151
+ this.patch({ selecting_id: "" });
152
+ }
153
+ }
154
+ // The caller freezes this target at pointer-down; release queues exactly one reply.
155
+ reply(file, target) {
156
+ if (!this.owner || target.owner_id !== this.owner)
157
+ throw unavailable();
158
+ return this.opts.queue.enqueue(newChatInput({
159
+ chat_room_id: target.chat_room_id,
160
+ quoted_message_id: target.chat_id,
161
+ text: "",
162
+ has_objects: true,
163
+ is_talkie: true,
164
+ }), { files: [file], save_to_personal_box: false, full_quality: false });
165
+ }
166
+ clearReply() {
167
+ ++this.selection;
168
+ this.patch({ reply: undefined, selecting_id: "" });
169
+ }
170
+ stop() {
171
+ this.playback.abort();
172
+ this.playback = new AbortController();
173
+ this.opts.player.pause();
174
+ this.patch({ playing_id: "", loading_id: "" });
175
+ }
176
+ ended() {
177
+ this.patch({ playing_id: "" });
178
+ }
179
+ failed() {
180
+ this.loaded = "";
181
+ this.stop();
182
+ }
183
+ clear() {
184
+ this.stop();
185
+ this.clearReply();
186
+ this.loaded = "";
187
+ this.opts.player.reset();
188
+ }
189
+ resolve(item) {
190
+ const talkie = notificationTalkie(item);
191
+ if (!this.owner || item.owner_id !== this.owner || !talkie)
192
+ throw unavailable();
193
+ return talkie;
194
+ }
195
+ patch(value) {
196
+ this.value = { ...this.value, ...value };
197
+ notifyObserver(() => this.opts.on_change(this.value));
198
+ }
199
+ }
200
+ function unavailable() {
201
+ return errResolveFailed({
202
+ resource: "talkie",
203
+ msg: "This voice message or conversation is no longer available.",
204
+ });
205
+ }
@@ -1,5 +1,6 @@
1
1
  import { type ContactsOperator, type UsersOperator } from "@fabriktor/client";
2
2
  import { Friend, Hired, Manager, Na, OldHire, type Contact, type ID, type OperationResult, type User } from "@fabriktor/schema";
3
+ import { PollScheduler } from "../core/poll.js";
3
4
  type ContactInsertOptions = Parameters<ContactsOperator["insertOneContact"]>[0];
4
5
  type ContactReplaceOptions = Parameters<ContactsOperator["replaceOneContact"]>[0];
5
6
  export type CreateContactOptions = ContactInsertOptions;
@@ -9,6 +10,7 @@ export type ActiveContactRelation = typeof Friend | typeof Hired | typeof Manage
9
10
  export type ContactsFXOptions = {
10
11
  contacts: ContactsOperator;
11
12
  users: UsersOperator;
13
+ polling?: PollScheduler;
12
14
  };
13
15
  export type LoadContactIndexOptions = {
14
16
  owner_id: string;
@@ -73,6 +75,7 @@ export interface ContactsFXOperator {
73
75
  export declare class ContactsFX implements ContactsFXOperator {
74
76
  private contacts;
75
77
  private users;
78
+ private readonly polling;
76
79
  constructor(opts: ContactsFXOptions);
77
80
  createContact(opts: CreateContactOptions): Promise<Contact>;
78
81
  replaceContact(opts: ReplaceContactOptions): Promise<Contact>;
@@ -4,7 +4,7 @@ import { errRequired, errResolveFailed, errValidation } from "../core/err.js";
4
4
  import { normalizeIDs, requiredOperationID } from "../core/id.js";
5
5
  import { mergeRecordsByID } from "../core/scope.js";
6
6
  import { runSearch } from "../core/search.js";
7
- const presenceIntervalMS = 120_000;
7
+ import { PollScheduler } from "../core/poll.js";
8
8
  const employmentUserBatchSize = 30;
9
9
  const resourceContact = "contact";
10
10
  const msgCreatedContactIDMissing = "Created contact response did not contain an ID.";
@@ -18,9 +18,11 @@ const msgPendingRelationRequired = "Contact request does not contain a pending r
18
18
  export class ContactsFX {
19
19
  contacts;
20
20
  users;
21
+ polling;
21
22
  constructor(opts) {
22
23
  this.contacts = opts.contacts;
23
24
  this.users = opts.users;
25
+ this.polling = opts.polling ?? new PollScheduler();
24
26
  }
25
27
  async createContact(opts) {
26
28
  const out = await this.contacts.insertOneContact(opts);
@@ -141,16 +143,14 @@ export class ContactsFX {
141
143
  running = false;
142
144
  }
143
145
  };
144
- const timer = setInterval(() => {
145
- void tick();
146
- }, presenceIntervalMS);
146
+ const stopPolling = this.polling.subscribe(tick);
147
147
  return {
148
148
  stop() {
149
149
  if (stopped) {
150
150
  return;
151
151
  }
152
152
  stopped = true;
153
- clearInterval(timer);
153
+ stopPolling();
154
154
  },
155
155
  };
156
156
  }
@@ -0,0 +1,15 @@
1
+ type PollTask = {
2
+ run: () => void | Promise<void>;
3
+ pending?: Promise<void>;
4
+ };
5
+ export declare class PollScheduler {
6
+ private readonly tasks;
7
+ private timer?;
8
+ private active;
9
+ subscribe(run: PollTask["run"]): () => void;
10
+ setActive(active: boolean): void;
11
+ refresh(): Promise<void>;
12
+ private run;
13
+ private schedule;
14
+ }
15
+ export {};
@@ -0,0 +1,59 @@
1
+ import { notifyObserver } from "./events.js";
2
+ const pollIntervalMS = 120_000;
3
+ // One timer for account background reads. Jobs run independently and never overlap themselves.
4
+ export class PollScheduler {
5
+ tasks = new Set();
6
+ timer;
7
+ active = true;
8
+ subscribe(run) {
9
+ const task = { run };
10
+ this.tasks.add(task);
11
+ this.schedule();
12
+ return () => {
13
+ this.tasks.delete(task);
14
+ this.schedule();
15
+ };
16
+ }
17
+ // Browser/native bindings own visibility and connectivity; FX owns the timer.
18
+ setActive(active) {
19
+ if (active === this.active)
20
+ return;
21
+ this.active = active;
22
+ this.schedule();
23
+ if (active)
24
+ void this.refresh();
25
+ }
26
+ async refresh() {
27
+ if (!this.active)
28
+ return;
29
+ await Promise.all([...this.tasks].map((task) => this.run(task)));
30
+ }
31
+ run(task) {
32
+ if (task.pending)
33
+ return task.pending;
34
+ const pending = Promise.resolve()
35
+ .then(() => {
36
+ if (this.active && this.tasks.has(task))
37
+ return task.run();
38
+ })
39
+ .catch((error) => notifyObserver(() => {
40
+ throw error;
41
+ }))
42
+ .finally(() => {
43
+ task.pending = undefined;
44
+ });
45
+ task.pending = pending;
46
+ return pending;
47
+ }
48
+ schedule() {
49
+ if (!this.active || !this.tasks.size) {
50
+ globalThis.clearInterval(this.timer);
51
+ this.timer = undefined;
52
+ }
53
+ else if (this.timer === undefined) {
54
+ this.timer = globalThis.setInterval(() => {
55
+ void this.refresh();
56
+ }, pollIntervalMS);
57
+ }
58
+ }
59
+ }
package/dist/src/fx.d.ts CHANGED
@@ -6,6 +6,7 @@ import type { CallsFX, CallsFXOperator } from "./calls/calls.js";
6
6
  import type { ChatFX, ChatFXOperator } from "./chat/chat.js";
7
7
  import type { ContactsFX, ContactsFXOperator } from "./contacts/contacts.js";
8
8
  import { EventBus } from "./core/events.js";
9
+ import { PollScheduler } from "./core/poll.js";
9
10
  import type { FeedFX, FeedFXOperator } from "./feed/feed.js";
10
11
  import type { FulfillmentsFX, FulfillmentsFXOperator } from "./fulfillments/fulfillments.js";
11
12
  import type { JobsFX, JobsFXOperator } from "./jobs/jobs.js";
@@ -62,6 +63,7 @@ export type DefaultFXOptions = {
62
63
  };
63
64
  export interface FXOperator {
64
65
  readonly events: EventBus;
66
+ readonly polling: PollScheduler;
65
67
  billable: BillableFXOperator;
66
68
  calls: CallsFXOperator;
67
69
  chat: ChatFXOperator;
@@ -85,6 +87,7 @@ export interface FXOperator {
85
87
  }
86
88
  export declare class FX implements FXOperator {
87
89
  readonly events: EventBus;
90
+ readonly polling: PollScheduler;
88
91
  billable: BillableFX;
89
92
  calls: CallsFX;
90
93
  chat: ChatFX;
package/dist/src/fx.js CHANGED
@@ -4,6 +4,7 @@ import { newCallsFX } from "./calls/calls.js";
4
4
  import { newChatFX } from "./chat/chat.js";
5
5
  import { newContactsFX } from "./contacts/contacts.js";
6
6
  import { EventBus } from "./core/events.js";
7
+ import { PollScheduler } from "./core/poll.js";
7
8
  import { newFeedFX } from "./feed/feed.js";
8
9
  import { newFulfillmentsFX } from "./fulfillments/fulfillments.js";
9
10
  import { newJobsFX } from "./jobs/jobs.js";
@@ -22,6 +23,7 @@ import { newTimesheetsFX } from "./timesheets/timesheets.js";
22
23
  import { newUsersFX } from "./users/users.js";
23
24
  export class FX {
24
25
  events = new EventBus();
26
+ polling = new PollScheduler();
25
27
  billable;
26
28
  calls;
27
29
  chat;
@@ -46,6 +48,7 @@ export class FX {
46
48
  this.contacts = newContactsFX({
47
49
  contacts: opts.contacts,
48
50
  users: opts.users,
51
+ polling: this.polling,
49
52
  });
50
53
  this.billable = newBillableFX({
51
54
  billable: opts.billable,
@@ -8,6 +8,7 @@ export * from "./chat/forms.js";
8
8
  export * from "./chat/optimistic.js";
9
9
  export * from "./chat/scroll.js";
10
10
  export * from "./chat/send-queue.js";
11
+ export * from "./chat/talkies.js";
11
12
  export * from "./contacts/contacts.js";
12
13
  export * from "./contacts/scope.js";
13
14
  export * from "./core/address.js";
@@ -18,6 +19,7 @@ export * from "./core/id.js";
18
19
  export * from "./core/links.js";
19
20
  export * from "./core/measurement.js";
20
21
  export * from "./core/multi-create.js";
22
+ export * from "./core/poll.js";
21
23
  export * from "./core/pre-action.js";
22
24
  export * from "./core/pull.js";
23
25
  export * from "./core/query.js";
package/dist/src/index.js CHANGED
@@ -8,6 +8,7 @@ export * from "./chat/forms.js";
8
8
  export * from "./chat/optimistic.js";
9
9
  export * from "./chat/scroll.js";
10
10
  export * from "./chat/send-queue.js";
11
+ export * from "./chat/talkies.js";
11
12
  export * from "./contacts/contacts.js";
12
13
  export * from "./contacts/scope.js";
13
14
  export * from "./core/address.js";
@@ -18,6 +19,7 @@ export * from "./core/id.js";
18
19
  export * from "./core/links.js";
19
20
  export * from "./core/measurement.js";
20
21
  export * from "./core/multi-create.js";
22
+ export * from "./core/poll.js";
21
23
  export * from "./core/pre-action.js";
22
24
  export * from "./core/pull.js";
23
25
  export * from "./core/query.js";
@@ -10,6 +10,8 @@ export type NotificationInboxState = SearchState<Notification> & {
10
10
  };
11
11
  export type NotificationInboxOptions = {
12
12
  notifications: NotificationsFXOperator;
13
+ notif_k?: Notification["notif_k"];
14
+ track_unread?: boolean;
13
15
  events: EventBus;
14
16
  on_change: (state: NotificationInboxState) => void;
15
17
  on_error?: (error: unknown) => void;
@@ -29,6 +31,7 @@ export declare class NotificationInboxController {
29
31
  private readonly reads;
30
32
  private readonly deletes;
31
33
  private readonly deleted;
34
+ private readonly read;
32
35
  constructor(options: NotificationInboxOptions);
33
36
  get state(): NotificationInboxState;
34
37
  setOwner(owner_id?: string, session_id?: string): void;
@@ -18,6 +18,7 @@ export class NotificationInboxController {
18
18
  reads = new Map();
19
19
  deletes = new Map();
20
20
  deleted = new Set();
21
+ read = new Set();
21
22
  constructor(options) {
22
23
  this.options = options;
23
24
  this.search = new SearchController({
@@ -27,6 +28,7 @@ export class NotificationInboxController {
27
28
  this.stopRead = options.events.subscribe(NotificationsEvents.Read, ({ owner_id, id }) => {
28
29
  if (owner_id !== this.ownerID)
29
30
  return;
31
+ this.read.add(id);
30
32
  this.search.patchResult(id, { is_read: true });
31
33
  void this.refreshUnread();
32
34
  });
@@ -43,7 +45,11 @@ export class NotificationInboxController {
43
45
  get state() {
44
46
  const state = this.search.state;
45
47
  // An older in-flight response must never restore a confirmed deletion.
46
- const results = state.results.filter((item) => !this.deleted.has(item.id));
48
+ const results = state.results
49
+ .filter((item) => !this.deleted.has(item.id))
50
+ .map((item) => this.read.has(item.id) && !item.is_read
51
+ ? { ...item, is_read: true }
52
+ : item);
47
53
  return {
48
54
  ...state,
49
55
  results,
@@ -83,7 +89,10 @@ export class NotificationInboxController {
83
89
  await Promise.all([
84
90
  this.search.state.ready
85
91
  ? this.search.refresh()
86
- : this.search.replace({ owner_id }),
92
+ : this.search.replace({
93
+ owner_id,
94
+ notif_k: this.options.notif_k,
95
+ }),
87
96
  this.refreshUnread(),
88
97
  ]);
89
98
  }
@@ -108,7 +117,10 @@ export class NotificationInboxController {
108
117
  await Promise.all([this.search.retry(), this.refreshUnread()]);
109
118
  }
110
119
  markRead(id) {
111
- if (!this.ownerID || this.deleted.has(id) || this.deletes.has(id))
120
+ if (!this.ownerID ||
121
+ this.read.has(id) ||
122
+ this.deleted.has(id) ||
123
+ this.deletes.has(id))
112
124
  return Promise.resolve();
113
125
  const pending = this.reads.get(id);
114
126
  if (pending)
@@ -179,6 +191,8 @@ export class NotificationInboxController {
179
191
  this.clear();
180
192
  }
181
193
  async refreshUnread() {
194
+ if (this.options.track_unread === false)
195
+ return;
182
196
  this.unreadRequest?.abort();
183
197
  const request = new AbortController();
184
198
  this.unreadRequest = request;
@@ -186,6 +200,7 @@ export class NotificationInboxController {
186
200
  const out = await this.options.notifications.searchNotifications({
187
201
  owner_id: this.ownerID,
188
202
  is_read: false,
203
+ notif_k: this.options.notif_k,
189
204
  per_page: 1,
190
205
  signal: request.signal,
191
206
  });
@@ -216,6 +231,7 @@ export class NotificationInboxController {
216
231
  this.reads.clear();
217
232
  this.deletes.clear();
218
233
  this.deleted.clear();
234
+ this.read.clear();
219
235
  this.search.clear();
220
236
  }
221
237
  publish() {
@@ -46,3 +46,4 @@ export declare class NotificationsFX implements NotificationsFXOperator {
46
46
  unregisterDeviceToken(opts: UnregisterDeviceTokenOptions): Promise<void>;
47
47
  }
48
48
  export declare function newNotificationsFX(opts: NotificationsFXOptions): NotificationsFX;
49
+ export declare function notificationToggles(toggles: Record<string, boolean>): Record<string, boolean>;
@@ -1,4 +1,4 @@
1
- import { IDKey, OwnerIDKey, ZeroID, PushTransportFCM, } from "@fabriktor/schema";
1
+ import { IDKey, NotifKChatChatsReceived, NotifKChatChatsTalkieReceived, OwnerIDKey, ZeroID, PushTransportFCM, } from "@fabriktor/schema";
2
2
  import { isClientErr, queryParams, } from "@fabriktor/client";
3
3
  import { errRequired } from "../core/err.js";
4
4
  import { createEvent, EventBus } from "../core/events.js";
@@ -137,3 +137,11 @@ export class NotificationsFX {
137
137
  export function newNotificationsFX(opts) {
138
138
  return new NotificationsFX(opts);
139
139
  }
140
+ export function notificationToggles(toggles) {
141
+ return {
142
+ ...toggles,
143
+ [NotifKChatChatsTalkieReceived]: toggles[NotifKChatChatsTalkieReceived] ??
144
+ toggles[NotifKChatChatsReceived] ??
145
+ false,
146
+ };
147
+ }
@@ -1,6 +1,7 @@
1
- import { type ColorMode, type InPrefApp } from "@fabriktor/schema";
1
+ import { type ColorMode, type InPrefApp, type PrefApp } from "@fabriktor/schema";
2
+ import type { PollScheduler } from "../core/poll.js";
2
3
  import type { PreferencesFXOperator } from "./preferences.js";
3
- export declare const colorModes: readonly ["light", "concrete", "dark"];
4
+ export declare const colorModes: readonly ["light", "dark"];
4
5
  export declare function isColorMode(value: unknown): value is ColorMode;
5
6
  export type AppPreferencesInput = Pick<InPrefApp, "color_mode" | "quiet_mode">;
6
7
  export type AppPreferencesState = AppPreferencesInput & {
@@ -12,6 +13,7 @@ export type AppPreferencesState = AppPreferencesInput & {
12
13
  };
13
14
  export type AppPreferencesOptions = {
14
15
  preferences: Pick<PreferencesFXOperator, "getPrefApp" | "savePrefApp">;
16
+ polling?: PollScheduler;
15
17
  on_change: (state: AppPreferencesState) => void;
16
18
  on_error?: (error: unknown) => void;
17
19
  };
@@ -24,10 +26,16 @@ export declare class AppPreferencesController {
24
26
  private pending?;
25
27
  private saving;
26
28
  private error?;
29
+ private stopPolling?;
30
+ private refreshRequested;
31
+ private channel?;
27
32
  constructor(options: AppPreferencesOptions);
28
33
  get state(): AppPreferencesState;
29
- setOwner(ownerID?: string, identity?: string): void;
34
+ setOwner(ownerID?: string, identity?: string, pref?: PrefApp): void;
35
+ startSync(name: string): () => void;
30
36
  refresh(): Promise<void>;
31
37
  save(input: Partial<AppPreferencesInput>): Promise<void>;
32
38
  private publish;
39
+ private invalidate;
40
+ private flushRefresh;
33
41
  }
@@ -1,11 +1,7 @@
1
- import { ColorModeConcrete, ColorModeDark, ColorModeLight, } from "@fabriktor/schema";
1
+ import { ColorModeDark, ColorModeLight, } from "@fabriktor/schema";
2
2
  import { notifyObserver } from "../core/events.js";
3
3
  import { errRequired, errValidation } from "../core/err.js";
4
- export const colorModes = [
5
- ColorModeLight,
6
- ColorModeConcrete,
7
- ColorModeDark,
8
- ];
4
+ export const colorModes = [ColorModeLight, ColorModeDark];
9
5
  export function isColorMode(value) {
10
6
  return colorModes.some((mode) => mode === value);
11
7
  }
@@ -20,13 +16,17 @@ export class AppPreferencesController {
20
16
  pending;
21
17
  saving = false;
22
18
  error;
19
+ stopPolling;
20
+ refreshRequested = false;
21
+ channel;
23
22
  constructor(options) {
24
23
  this.options = options;
25
24
  }
26
25
  get state() {
27
26
  const quiet = this.current?.quiet_mode ?? false;
27
+ const mode = this.current?.color_mode;
28
28
  return {
29
- color_mode: this.current?.color_mode ?? ColorModeDark,
29
+ color_mode: isColorMode(mode) ? mode : ColorModeDark,
30
30
  quiet_mode: quiet,
31
31
  ready: this.current !== undefined,
32
32
  loading: this.pending !== undefined,
@@ -35,26 +35,60 @@ export class AppPreferencesController {
35
35
  error: this.error,
36
36
  };
37
37
  }
38
- setOwner(ownerID = "", identity = "") {
38
+ // Bootstrap may supply the preference already fetched for this account.
39
+ setOwner(ownerID = "", identity = "", pref) {
39
40
  if (ownerID === this.ownerID && identity === this.identity)
40
41
  return;
41
42
  this.session.abort();
43
+ this.stopPolling?.();
44
+ this.stopPolling = undefined;
42
45
  this.session = new AbortController();
43
46
  this.ownerID = ownerID;
44
47
  this.identity = identity;
45
- this.current = undefined;
48
+ this.current = ownerID ? pref : undefined;
46
49
  this.pending = undefined;
47
50
  this.saving = false;
48
51
  this.error = undefined;
52
+ this.refreshRequested = false;
49
53
  this.publish();
50
- if (ownerID)
54
+ if (ownerID && !this.current)
51
55
  void this.refresh();
56
+ if (ownerID)
57
+ this.stopPolling = this.options.polling?.subscribe(() => this.refresh());
58
+ }
59
+ // Broadcast only invalidation; every tab still reads the authoritative backend.
60
+ startSync(name) {
61
+ this.channel?.close();
62
+ this.channel = undefined;
63
+ try {
64
+ if (typeof BroadcastChannel !== "undefined") {
65
+ this.channel = new BroadcastChannel(name);
66
+ this.channel.onmessage = ({ data }) => {
67
+ if (data?.type === "preferences-changed" &&
68
+ this.ownerID &&
69
+ data.owner_id === this.ownerID &&
70
+ data.identity === this.identity)
71
+ this.invalidate();
72
+ };
73
+ }
74
+ }
75
+ catch (error) {
76
+ notifyObserver(() => this.options.on_error?.(error));
77
+ }
78
+ return () => {
79
+ this.channel?.close();
80
+ this.channel = undefined;
81
+ };
52
82
  }
53
83
  refresh() {
54
84
  if (this.pending)
55
85
  return this.pending;
56
- if (!this.ownerID || this.saving)
86
+ if (!this.ownerID)
87
+ return Promise.resolve();
88
+ if (this.saving) {
89
+ this.refreshRequested = true;
57
90
  return Promise.resolve();
91
+ }
58
92
  const signal = this.session.signal;
59
93
  const ownerID = this.ownerID;
60
94
  const pending = Promise.resolve().then(async () => {
@@ -78,6 +112,7 @@ export class AppPreferencesController {
78
112
  if (!signal.aborted) {
79
113
  this.pending = undefined;
80
114
  this.publish();
115
+ this.flushRefresh();
81
116
  }
82
117
  }
83
118
  });
@@ -109,6 +144,16 @@ export class AppPreferencesController {
109
144
  return;
110
145
  this.current = pref;
111
146
  this.error = undefined;
147
+ try {
148
+ this.channel?.postMessage({
149
+ type: "preferences-changed",
150
+ owner_id: ownerID,
151
+ identity: this.identity,
152
+ });
153
+ }
154
+ catch (error) {
155
+ notifyObserver(() => this.options.on_error?.(error));
156
+ }
112
157
  }
113
158
  catch (error) {
114
159
  if (!signal.aborted)
@@ -118,10 +163,24 @@ export class AppPreferencesController {
118
163
  if (!signal.aborted) {
119
164
  this.saving = false;
120
165
  this.publish();
166
+ this.flushRefresh();
121
167
  }
122
168
  }
123
169
  }
124
170
  publish() {
125
171
  notifyObserver(() => this.options.on_change(this.state));
126
172
  }
173
+ // An invalidation received during a request must survive that request's result.
174
+ invalidate() {
175
+ if (this.pending || this.saving)
176
+ this.refreshRequested = true;
177
+ else
178
+ void this.refresh();
179
+ }
180
+ flushRefresh() {
181
+ if (this.refreshRequested && !this.saving) {
182
+ this.refreshRequested = false;
183
+ void this.refresh();
184
+ }
185
+ }
127
186
  }
@@ -50,7 +50,12 @@ export class RecordedFileWorkflow {
50
50
  });
51
51
  if (!this.current())
52
52
  return;
53
- const out = this.opts.queue.enqueue(newChatInput({ chat_room_id: room, text: "", has_objects: true }), {
53
+ const out = this.opts.queue.enqueue(newChatInput({
54
+ chat_room_id: room,
55
+ text: "",
56
+ has_objects: true,
57
+ is_talkie: true,
58
+ }), {
54
59
  files: [this.opts.file],
55
60
  save_to_personal_box: false,
56
61
  full_quality: false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabriktor/fx",
3
- "version": "0.0.186",
3
+ "version": "0.0.188",
4
4
  "description": "![Fabriktor Logo](./img/fabriktor-character.gif)",
5
5
  "type": "module",
6
6
  "exports": {
@@ -17,9 +17,9 @@
17
17
  "typescript": "^6.0.3"
18
18
  },
19
19
  "dependencies": {
20
- "@fabriktor/client": "0.0.114",
20
+ "@fabriktor/client": "0.0.115",
21
21
  "@fabriktor/fx": "0.0.94",
22
- "@fabriktor/schema": "0.0.85",
22
+ "@fabriktor/schema": "0.0.86",
23
23
  "convert": "8.0.2"
24
24
  }
25
25
  }