fsanyoto commited on
Commit
040bfb2
·
verified ·
1 Parent(s): 5888a21

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
RELEASES.json CHANGED
@@ -1,4 +1,4 @@
1
  {
2
- "current": "305493b0",
3
  "releases": []
4
  }
 
1
  {
2
+ "current": "94c73d86",
3
  "releases": []
4
  }
VERSION CHANGED
@@ -1 +1 @@
1
- 305493b0
 
1
+ 94c73d86
api/telnyx_whatsapp.py CHANGED
@@ -138,6 +138,107 @@ def _send(to, message, *, purpose, tenant, username, transport, store_):
138
  return copy.deepcopy(entry)
139
 
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  def send_template(to, template, params, *, purpose, tenant="", username="",
142
  transport=None, store_=None):
143
  _check_text(template)
 
138
  return copy.deepcopy(entry)
139
 
140
 
141
+ TELNYX_FAILED = {"delivery_failed", "sending_failed", "expired"}
142
+ UNDELIVERED = "WhatsApp could not deliver this message."
143
+
144
+
145
+ def _first_code(errors):
146
+ if isinstance(errors, list) and errors and isinstance(errors[0], dict):
147
+ return errors[0].get("code")
148
+ return None
149
+
150
+
151
+ def _status_updates(event_type, payload):
152
+ """Read (providerId, outcome, telnyxCode, metaCode) rows from one status event."""
153
+ if not isinstance(payload, dict):
154
+ return []
155
+ if event_type == "message.finalized":
156
+ provider_id = payload.get("id")
157
+ if payload.get("type") != "WHATSAPP" or not isinstance(provider_id, str) or not provider_id:
158
+ return []
159
+ recipients = payload.get("to") if isinstance(payload.get("to"), list) else []
160
+ states = {row.get("status") for row in recipients
161
+ if isinstance(row, dict) and isinstance(row.get("status"), str)}
162
+ if states & TELNYX_FAILED:
163
+ code = _first_code(payload.get("errors"))
164
+ return [(provider_id, "failed", None if code in (None, "") else str(code), None)]
165
+ return [(provider_id, "delivered", None, None)] if "delivered" in states else []
166
+ if event_type == "whatsapp.messages":
167
+ rows = []
168
+ for row in payload.get("statuses") if isinstance(payload.get("statuses"), list) else []:
169
+ # A malformed row is skipped: a status event never answers 400.
170
+ if (not isinstance(row, dict) or not isinstance(row.get("id"), str) or not row["id"]
171
+ or not isinstance(row.get("status"), str)):
172
+ continue
173
+ if row.get("status") == "failed":
174
+ code = _first_code(row.get("errors"))
175
+ if isinstance(code, str) and code.isdigit():
176
+ code = int(code)
177
+ meta = code if isinstance(code, int) and not isinstance(code, bool) else None
178
+ rows.append((row["id"], "failed", None, meta))
179
+ elif row.get("status") in {"delivered", "read"}:
180
+ rows.append((row["id"], "delivered", None, None))
181
+ return rows
182
+ return []
183
+
184
+
185
+ def _apply_status(entry, outcome, telnyx_code, meta_code):
186
+ before = dict(entry)
187
+ if outcome == "failed":
188
+ # Failed is terminal: a later event adds a code but never clears one.
189
+ entry.update(status="failed", error=UNDELIVERED)
190
+ if telnyx_code is not None:
191
+ entry["errorCode"] = telnyx_code
192
+ if meta_code is not None:
193
+ entry["metaCode"] = meta_code
194
+ elif entry.get("status") != "failed":
195
+ entry["status"] = "delivered"
196
+ return entry != before
197
+
198
+
199
+ def record_status(event_type, payload, *, store_=None):
200
+ """Apply a signed Telnyx delivery event to outbox entries by providerId; return entries changed."""
201
+ rows = _status_updates(event_type, payload)
202
+ if not rows:
203
+ return 0
204
+ selected = store_ if store_ is not None else _store
205
+ current = (selected.get(OUTBOX_KEY) or {}).get("messages") or []
206
+
207
+ def changes(messages):
208
+ changed = 0
209
+ for entry in messages:
210
+ if not isinstance(entry, dict) or not entry.get("providerId"):
211
+ continue
212
+ for provider_id, outcome, telnyx_code, meta_code in rows:
213
+ if entry["providerId"] == provider_id:
214
+ changed += _apply_status(entry, outcome, telnyx_code, meta_code)
215
+ return changed
216
+
217
+ # An unknown id or a repeated event writes nothing at all.
218
+ if not changes(copy.deepcopy(current)):
219
+ return 0
220
+ outcome = {"changed": 0}
221
+
222
+ def apply(doc):
223
+ doc["messages"] = list(doc.get("messages") or [])
224
+ outcome["changed"] = changes(doc["messages"])
225
+ return doc
226
+
227
+ selected.update(OUTBOX_KEY, apply)
228
+ return outcome["changed"]
229
+
230
+
231
+ def delivery_status(provider_id, *, store_=None):
232
+ """Return the outbox status of the newest entry sent as provider_id, or None."""
233
+ if not provider_id:
234
+ return None
235
+ messages = ((store_ if store_ is not None else _store).get(OUTBOX_KEY) or {}).get("messages") or []
236
+ for entry in reversed(messages):
237
+ if isinstance(entry, dict) and entry.get("providerId") == provider_id:
238
+ return entry.get("status")
239
+ return None
240
+
241
+
242
  def send_template(to, template, params, *, purpose, tenant="", username="",
243
  transport=None, store_=None):
244
  _check_text(template)
api/whatsapp_door.py CHANGED
@@ -146,6 +146,8 @@ def accept(raw: bytes, signature: str, timestamp: str, *, now=None):
146
  raise WhatsAppDoorRefusal("Telnyx webhook signature verification failed")
147
  try:
148
  data = json.loads(raw)["data"]
 
 
149
  if data["event_type"] != "message.received":
150
  return None
151
  payload = data["payload"]
 
146
  raise WhatsAppDoorRefusal("Telnyx webhook signature verification failed")
147
  try:
148
  data = json.loads(raw)["data"]
149
+ # A delivery status updates the outbox only: no receipt claim, no window stamp, no turn.
150
+ telnyx_whatsapp.record_status(data["event_type"], data.get("payload"))
151
  if data["event_type"] != "message.received":
152
  return None
153
  payload = data["payload"]
api/whatsapp_identity.py CHANGED
@@ -22,6 +22,7 @@ LOCK_S = 900
22
  PHONE_TAKEN = "This number is already connected to another Loopable account."
23
  CODE_WRONG = "That code is not right. Check the latest WhatsApp message and try again."
24
  CODE_EXPIRED = "That code has expired. Send a new code."
 
25
 
26
 
27
  class WhatsAppRefusal(ValueError):
@@ -145,6 +146,16 @@ def start(tenant, username, phone, *, now=None, sender=None):
145
  p: row for p, row in doc.items()
146
  if p != phone or row.get("codeHash") != pending["codeHash"]})
147
  raise WhatsAppRefusal("The code could not be sent. Try again.")
 
 
 
 
 
 
 
 
 
 
148
  return {"state": "pending", "phone": phone, "expiresAt": pending["expiresAt"]}
149
 
150
 
@@ -201,4 +212,6 @@ def status(tenant, username, *, now=None):
201
  "message": _lock_sentence(pending, now)}
202
  if pending["expiresAt"] <= now:
203
  return {"state": "none"}
 
 
204
  return {"state": "pending", "phone": phone, "expiresAt": pending["expiresAt"]}
 
22
  PHONE_TAKEN = "This number is already connected to another Loopable account."
23
  CODE_WRONG = "That code is not right. Check the latest WhatsApp message and try again."
24
  CODE_EXPIRED = "That code has expired. Send a new code."
25
+ CODE_UNDELIVERED = "The code could not be delivered to this number."
26
 
27
 
28
  class WhatsAppRefusal(ValueError):
 
146
  p: row for p, row in doc.items()
147
  if p != phone or row.get("codeHash") != pending["codeHash"]})
148
  raise WhatsAppRefusal("The code could not be sent. Try again.")
149
+ provider_id = delivery.get("providerId") if isinstance(delivery, dict) else None
150
+ if provider_id:
151
+ # status() reads the outbox by this id, so a later refusal can reach the caller.
152
+ def remember(doc):
153
+ row = doc.get(phone)
154
+ if isinstance(row, dict) and row.get("codeHash") == pending["codeHash"]:
155
+ row["providerId"] = provider_id
156
+ return doc
157
+
158
+ _store.update(CODES_KEY, remember)
159
  return {"state": "pending", "phone": phone, "expiresAt": pending["expiresAt"]}
160
 
161
 
 
212
  "message": _lock_sentence(pending, now)}
213
  if pending["expiresAt"] <= now:
214
  return {"state": "none"}
215
+ if telnyx_whatsapp.delivery_status(pending.get("providerId")) == "failed":
216
+ return {"state": "undelivered", "phone": phone, "message": CODE_UNDELIVERED}
217
  return {"state": "pending", "phone": phone, "expiresAt": pending["expiresAt"]}
web/public/AIOS_DEPLOY_RECEIPT CHANGED
@@ -1 +1 @@
1
- e3a0975a29152a470fa71f77964586c6ff4e4c64574582260ed33d39319cef89
 
1
+ cf02d45da669a38d7b9e5a915c88f36142bd50980ddb140e547cc7f387fb721d
web/src/settings/channels/WhatsAppSection.tsx CHANGED
@@ -2,7 +2,8 @@ import { useEffect, useState } from "react";
2
  import type { FormEvent } from "react";
3
  import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant } from "../../apiContract";
4
 
5
- export type WhatsAppViewState = "empty" | "sending" | "code" | "connected" | "wrong" | "locked";
 
6
 
7
  type ViewProps = {
8
  state: WhatsAppViewState;
@@ -21,6 +22,9 @@ type ViewProps = {
21
  const WRONG_CODE = "That code is not right. Check the latest WhatsApp message and try again.";
22
  const LOCKED = "Too many wrong codes. Try again in 15 minutes.";
23
  const UNAVAILABLE = "WhatsApp is unavailable right now. Try again.";
 
 
 
24
 
25
  function screenSentence(value: unknown, fallback: string): string {
26
  return typeof value === "string" && value.trim() && !/[\u2013\u2014]/.test(value)
@@ -31,7 +35,8 @@ export function WhatsAppSectionView(props: ViewProps) {
31
  const { state, phone = "", code = "", busy = false, noPermission = false } = props;
32
  const disabled = busy || state === "sending" || state === "locked" || noPermission;
33
  const codeEntry = state === "code" || state === "wrong" || state === "locked";
34
- const fallback = state === "locked" ? LOCKED : state === "wrong" ? WRONG_CODE : "";
 
35
  const message = screenSentence(props.message, fallback);
36
  const submit = (event: FormEvent<HTMLFormElement>, action?: () => void) => {
37
  event.preventDefault();
@@ -90,13 +95,21 @@ export function WhatsAppSectionView(props: ViewProps) {
90
  );
91
  }
92
 
93
- type Status = {
94
- state: "none" | "pending" | "connected" | "locked";
95
  phone?: string;
 
96
  lockedUntil?: number;
97
  message?: string;
98
  };
99
 
 
 
 
 
 
 
 
100
  class ChannelError extends Error {
101
  status: number;
102
  code: string;
@@ -134,13 +147,17 @@ export default function WhatsAppSection({ onChanged }: { onChanged?: () => void
134
  const [busy, setBusy] = useState(true);
135
  const [noPermission, setNoPermission] = useState(false);
136
  const [lockedUntil, setLockedUntil] = useState<number | null>(null);
 
137
 
138
  function accept(result: Status) {
139
- setState(result.state === "none" ? "empty" : result.state === "pending" ? "code" : result.state);
140
- setPhone(result.phone ?? "");
 
 
141
  setCode("");
142
- setMessage(screenSentence(result.message, result.state === "locked" ? LOCKED : ""));
143
  setLockedUntil(result.lockedUntil ?? null);
 
144
  onChanged?.();
145
  }
146
 
@@ -183,6 +200,26 @@ export default function WhatsAppSection({ onChanged }: { onChanged?: () => void
183
  return () => window.clearTimeout(timer);
184
  }, [state, lockedUntil]);
185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  async function act(method: string, path: string, body?: object) {
187
  if (busy || noPermission) return;
188
  setBusy(true);
 
2
  import type { FormEvent } from "react";
3
  import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant } from "../../apiContract";
4
 
5
+ export type WhatsAppViewState =
6
+ "empty" | "sending" | "code" | "connected" | "wrong" | "locked" | "undelivered";
7
 
8
  type ViewProps = {
9
  state: WhatsAppViewState;
 
22
  const WRONG_CODE = "That code is not right. Check the latest WhatsApp message and try again.";
23
  const LOCKED = "Too many wrong codes. Try again in 15 minutes.";
24
  const UNAVAILABLE = "WhatsApp is unavailable right now. Try again.";
25
+ export const UNDELIVERED = "The code could not be delivered to this number.";
26
+ // The code state asks the server this often whether the send failed after acceptance.
27
+ const POLL_MS = 5000;
28
 
29
  function screenSentence(value: unknown, fallback: string): string {
30
  return typeof value === "string" && value.trim() && !/[\u2013\u2014]/.test(value)
 
35
  const { state, phone = "", code = "", busy = false, noPermission = false } = props;
36
  const disabled = busy || state === "sending" || state === "locked" || noPermission;
37
  const codeEntry = state === "code" || state === "wrong" || state === "locked";
38
+ const fallback = state === "locked" ? LOCKED : state === "wrong" ? WRONG_CODE
39
+ : state === "undelivered" ? UNDELIVERED : "";
40
  const message = screenSentence(props.message, fallback);
41
  const submit = (event: FormEvent<HTMLFormElement>, action?: () => void) => {
42
  event.preventDefault();
 
95
  );
96
  }
97
 
98
+ export type Status = {
99
+ state: "none" | "pending" | "connected" | "locked" | "undelivered";
100
  phone?: string;
101
+ expiresAt?: number;
102
  lockedUntil?: number;
103
  message?: string;
104
  };
105
 
106
+ /** Maps a server status to the view state and the screened sentence it shows. */
107
+ export function statusView(result: Status): { state: WhatsAppViewState; message: string } {
108
+ const state = result.state === "none" ? "empty" : result.state === "pending" ? "code" : result.state;
109
+ const fallback = result.state === "locked" ? LOCKED : result.state === "undelivered" ? UNDELIVERED : "";
110
+ return { state, message: screenSentence(result.message, fallback) };
111
+ }
112
+
113
  class ChannelError extends Error {
114
  status: number;
115
  code: string;
 
147
  const [busy, setBusy] = useState(true);
148
  const [noPermission, setNoPermission] = useState(false);
149
  const [lockedUntil, setLockedUntil] = useState<number | null>(null);
150
+ const [expiresAt, setExpiresAt] = useState<number | null>(null);
151
 
152
  function accept(result: Status) {
153
+ const view = statusView(result);
154
+ setState(view.state);
155
+ // An undelivered code keeps the typed number so the user can fix it or send again.
156
+ setPhone((current) => result.phone ?? (result.state === "undelivered" ? current : ""));
157
  setCode("");
158
+ setMessage(view.message);
159
  setLockedUntil(result.lockedUntil ?? null);
160
+ setExpiresAt(result.expiresAt ?? null);
161
  onChanged?.();
162
  }
163
 
 
200
  return () => window.clearTimeout(timer);
201
  }, [state, lockedUntil]);
202
 
203
+ // A send Telnyx accepted can still fail at Meta, so the code state polls until expiry.
204
+ useEffect(() => {
205
+ if (state !== "code" || expiresAt === null) return;
206
+ let live = true;
207
+ let controller: AbortController | null = null;
208
+ const timer = window.setInterval(() => {
209
+ if (Date.now() >= expiresAt * 1000) {
210
+ window.clearInterval(timer);
211
+ return;
212
+ }
213
+ controller?.abort();
214
+ controller = new AbortController();
215
+ void call("GET", "", undefined, controller.signal).then((result) => {
216
+ // A pending answer changes nothing and must not clear a code being typed.
217
+ if (live && result.state !== "pending") accept(result);
218
+ }).catch(() => undefined);
219
+ }, POLL_MS);
220
+ return () => { live = false; window.clearInterval(timer); controller?.abort(); };
221
+ }, [state, expiresAt]);
222
+
223
  async function act(method: string, path: string, body?: object) {
224
  if (busy || noPermission) return;
225
  setBusy(true);