n8n 連携: セッションを作業区間に分ける make_blocks を追加

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-13 03:11:28 +09:00
co-authored by Claude Opus 5.5
parent e16189153c
commit c3c42d5988
2 changed files with 162 additions and 0 deletions
+67
View File
@@ -1191,6 +1191,73 @@ def to_fields(draft, defaults):
return fields
# ---------------------------------------------------------------- n8n 連携 (work_log への取り込み)
N8N_CONFIG = APP_DIR / "n8n.json"
N8N_GAP_MIN = 30 # この分数以上の空きで作業区間を切る
N8N_MIN_MIN = 5 # この分数未満の区間は一覧に出さない
N8N_MAX_DAYS = 62 # n8n の wt-import-rows と同じ上限
class N8nError(Exception):
"""n8n 連携で利用者に見せたいエラー (UI に文言をそのまま出す)。"""
def block_source(session_id, start_epoch):
"""作業区間の識別子。同じログからは毎回同じ値になる (二重登録を防ぐ鍵)。"""
return f"chktime:{session_id}:{int(round(start_epoch * 1000))}"
def make_blocks(session, gap_min=N8N_GAP_MIN, min_min=N8N_MIN_MIN, now=None):
"""1 セッションのターンを作業区間に分ける。
前のターンの応答完了から次の発言までの空きが gap_min 分未満ならつなぎ、
gap_min 分以上なら区間を切る。min_min 分未満の区間は捨てる (進行中は残す)。
最後の区間は、応答が返っていない / ログの更新から gap_min 分経っていない
なら進行中 (送れない) とする。
"""
now = time.time() if now is None else now
gap = gap_min * 60.0
groups = []
for turn in session["turns"]:
ts = turn["ts"]
if ts is None:
continue
end = turn["endTs"] if turn["endTs"] is not None else ts
if groups and ts - groups[-1]["end"] < gap:
group = groups[-1]
group["end"] = max(group["end"], end)
group["turns"] += 1
group["last"] = turn
else:
groups.append({"start": ts, "end": end, "turns": 1, "last": turn})
out = []
for index, group in enumerate(groups):
last = group["last"]
waiting = last["firstReplyTs"] is None and not last["interrupted"]
recent = now - (session.get("mtime") or group["end"]) < gap
in_progress = index == len(groups) - 1 and (waiting or recent)
minutes = (group["end"] - group["start"]) / 60.0
if minutes < min_min and not in_progress:
continue
out.append(
{
"source": block_source(session["id"], group["start"]),
"sessionId": session["id"],
"date": local_date(group["start"]),
"start": iso(group["start"]),
"end": iso(group["end"]),
"startEpoch": group["start"],
"endEpoch": group["end"],
"minutes": int(round(minutes)),
"turns": group["turns"],
"inProgress": in_progress,
}
)
return out
# ---------------------------------------------------------------- HTTP